PageSourceSearch

https://carecounsel.com/etc/clientlibs/shc/all.lc-1788552815549-lc.min.js

js carecounsel.com collected 2026-10-06 07:24:25 UTC 2,112,198 bytes, 37,805 lines download raw bytes

vendor: 2,998 bytes, lines 1-4
1/* Modernizr 2.7.1 (Custom Build) | MIT & BSD
2 * Build: http://modernizr.com/download/#-fontface-backgroundsize-borderimage-borderradius-boxshadow-flexbox-hsla-multiplebgs-opacity-rgba-textshadow-cssanimations-csscolumns-generatedcontent-cssgradients-cssreflections-csstransforms-csstransforms3d-csstransitions-applicationcache-canvas-canvastext-draganddrop-hashchange-history-audio-video-indexeddb-input-inputtypes-localstorage-postmessage-sessionstorage-websockets-websqldatabase-webworkers-geolocation-inlinesvg-smil-svg-svgclippaths-touch-webgl-shiv-mq-cssclasses-addtest-prefixed-teststyles-testprop-testallprops-hasevent-prefixes-domprefixes-load
3 */
4;window.Modernizr=function(a,b,c){function D(a){j.cssText=a}function E(a,b){return D(n.join(a+";")+(b||""))}function F(a,b){return typeof a===b}function G(a,b){return!!~(""+a).indexOf(b)}function H(a,b){for(var d in a){var e=a[d];if(!G(e,"-")&&j[e]!==c)return b=="pfx"?e:!0}return!1}function I(a,b,d){for(var e in a){var f=b[a[e]];if(f!==c)return d===!1?a[e]:F(f,"function")?f.bind(d||b):f}return!1}function J(a,b,c){var d=a.charAt(0).toUpperCase()+a.slice(1),e=(a+" "+p.join(d+" ")+d).split(" ");return F(b,"string")||F(b,"undefined")?H(e,b):(e=(a+" "+q.join(d+" ")+d).split(" "),I(e,b,c))}function K(){e.input=function(c){for(var d=0,e=c.length;d<e;d++)u[c[d]]=c[d]in k;return u.list&&(u.list=!!b.createElement("datalist")&&!!a.HTMLDataListElement),u}("autocomplete autofocus list placeholder max min multiple pattern required step".split(" ")),e.inputtypes=function(a){for(var d=0,e,f,h,i=a.length;d<i;d++)k.setAttribute("type",f=a[d]),e=k.type!=="text",e&&(k.value=l,k.style.cssText="position:absolute;visibility:hidden;",/^range$/.test(f)&&k.style.WebkitAppearance!==c?(g.appendChild(k),h=b.defaultView,e=h.getComputedStyle&&h.getComputedStyle(k,null).WebkitAppearance!=="textfield"&&k.offsetHeight!==0,g.removeChild(k)):/^(search|tel)$/.test(f)||(/^(url|email)$/.test(f)?e=k.checkValidity&&k.checkValidity()===!1:e=k.value!=l)),t[a[d]]=!!e;return t}("search tel url email datetime date month week time datetime-local number range color".split(" "))}var d="2.7.1",e={},f=!0,g=b.documentElement,h="modernizr",i=b.createElement(h),j=i.style,k=b.createElement("input"),l=":)",m={}.toString,n=" -webkit- -moz- -o- -ms- ".split(" "),o="Webkit Moz O ms",p=o.split(" "),q=o.toLowerCase().split(" "),r={svg:"http://www.w3.org/2000/svg"},s={},t={},u={},v=[],w=v.slice,x,y=function(a,c,d,e){var f,i,j,k,l=b.createElement("div"),m=b.body,n=m||b.createElement("body");if(parseInt(d,10))while(d--)j=b.createElement("div"),j.id=e?e[d]:h+(d+1),l.appendChild(j);return f=["&#173;",'<style id="s',h,'">',a,"</style>"].join(""),l.id=h,(m?l:n).innerHTML+=f,n.appendChild(l),m||(n.style.background="",n.style.overflow="hidden",k=g.style.overflow,g.style.overflow="hidden",g.appendChild(n)),i=c(l,a),m?l.parentNode.removeChild(l):(n.parentNode.removeChild(n),g.style.overflow=k),!!i},z=function(b){var c=a.matchMedia||a.msMatchMedia;if(c)return c(b).matches
vendor: 12,505 bytes, line 4
4;var d;return y("@media "+b+" { #"+h+" { position: absolute; } }",function(b){d=(a.getComputedStyle?getComputedStyle(b,null):b.currentStyle)["position"]=="absolute"}),d},A=function(){function d(d,e){e=e||b.createElement(a[d]||"div"),d="on"+d;var f=d in e;return f||(e.setAttribute||(e=b.createElement("div")),e.setAttribute&&e.removeAttribute&&(e.setAttribute(d,""),f=F(e[d],"function"),F(e[d],"undefined")||(e[d]=c),e.removeAttribute(d))),e=null,f}var a={select:"input",change:"input",submit:"form",reset:"form",error:"img",load:"img",abort:"img"};return d}(),B={}.hasOwnProperty,C;!F(B,"undefined")&&!F(B.call,"undefined")?C=function(a,b){return B.call(a,b)}:C=function(a,b){return b in a&&F(a.constructor.prototype[b],"undefined")},Function.prototype.bind||(Function.prototype.bind=function(b){var c=this;if(typeof c!="function")throw new TypeError;var d=w.call(arguments,1),e=function(){if(this instanceof e){var a=function(){};a.prototype=c.prototype;var f=new a,g=c.apply(f,d.concat(w.call(arguments)));return Object(g)===g?g:f}return c.apply(b,d.concat(w.call(arguments)))};return e}),s.flexbox=function(){return J("flexWrap")},s.canvas=function(){var a=b.createElement("canvas");return!!a.getContext&&!!a.getContext("2d")},s.canvastext=function(){return!!e.canvas&&!!F(b.createElement("canvas").getContext("2d").fillText,"function")},s.webgl=function(){return!!a.WebGLRenderingContext},s.touch=function(){var c;return"ontouchstart"in a||a.DocumentTouch&&b instanceof DocumentTouch?c=!0:y(["@media (",n.join("touch-enabled),("),h,")","{#modernizr{top:9px;position:absolute}}"].join(""),function(a){c=a.offsetTop===9}),c},s.geolocation=function(){return"geolocation"in navigator},s.postmessage=function(){return!!a.postMessage},s.websqldatabase=function(){return!!a.openDatabase},s.indexedDB=function(){return!!J("indexedDB",a)},s.hashchange=function(){return A("hashchange",a)&&(b.documentMode===c||b.documentMode>7)},s.history=function(){return!!a.history&&!!history.pushState},s.draganddrop=function(){var a=b.createElement("div");return"draggable"in a||"ondragstart"in a&&"ondrop"in a},s.websockets=function(){return"WebSocket"in a||"MozWebSocket"in a},s.rgba=function(){return D("background-color:rgba(150,255,150,.5)"),G(j.backgroundColor,"rgba")},s.hsla=function(){return D("background-color:hsla(120,40%,100%,.5)"),G(j.backgroundColor,"rgba")||G(j.backgroundColor,"hsla")},s.multiplebgs=function(){return D("background:url(https://),url(https://),red url(https://)"),/(url\s*\(.*?){3}/.test(j.background)},s.backgroundsize=function(){return J("backgroundSize")},s.borderimage=function(){return J("borderImage")},s.borderradius=function(){return J("borderRadius")},s.boxshadow=function(){return J("boxShadow")},s.textshadow=function(){return b.createElement("div").style.textShadow===""},s.opacity=function(){return E("opacity:.55"),/^0.55$/.test(j.opacity)},s.cssanimations=function(){return J("animationName")},s.csscolumns=function(){return J("columnCount")},s.cssgradients=function(){var a="background-image:",b="gradient(linear,left top,right bottom,from(#9f9),to(white));",c="linear-gradient(left top,#9f9, white);";return D((a+"-webkit- ".split(" ").join(b+a)+n.join(c+a)).slice(0,-a.length)),G(j.backgroundImage,"gradient")},s.cssreflections=function(){return J("boxReflect")},s.csstransforms=function(){return!!J("transform")},s.csstransforms3d=function(){var a=!!J("perspective");return a&&"webkitPerspective"in g.style&&y("@media (transform-3d),(-webkit-transform-3d){#modernizr{left:9px;position:absolute;height:3px;}}",function(b,c){a=b.offsetLeft===9&&b.offsetHeight===3}),a},s.csstransitions=function(){return J("transition")},s.fontface=function(){var a;return y('@font-face {font-family:"font";src:url("https://")}',function(c,d){var e=b.getElementById("smodernizr"),f=e.sheet||e.styleSheet,g=f?f.cssRules&&f.cssRules[0]?f.cssRules[0].cssText:f.cssText||"":"";a=/src/i.test(g)&&g.indexOf(d.split(" ")[0])===0}),a},s.generatedcontent=function(){var a;return y(["#",h,"{font:0/0 a}#",h,':after{content:"',l,'";visibility:hidden;font:3px/1 a}'].join(""),function(b){a=b.offsetHeight>=3}),a},s.video=function(){var a=b.createElement("video"),c=!1;try{if(c=!!a.canPlayType)c=new Boolean(c),c.ogg=a.canPlayType('video/ogg; codecs="theora"').replace(/^no$/,""),c.h264=a.canPlayType('video/mp4; codecs="avc1.42E01E"').replace(/^no$/,""),c.webm=a.canPlayType('video/webm; codecs="vp8, vorbis"').replace(/^no$/,"")}catch(d){}return c},s.audio=function(){var a=b.createElement("audio"),c=!1;try{if(c=!!a.canPlayType)c=new Boolean(c),c.ogg=a.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,""),c.mp3=a.canPlayType("audio/mpeg;").replace(/^no$/,""),c.wav=a.canPlayType('audio/wav; codecs="1"').replace(/^no$/,""),c.m4a=(a.canPlayType("audio/x-m4a;")||a.canPlayType("audio/aac;")).replace(/^no$/,"")}catch(d){}return c},s.localstorage=function(){try{return localStorage.setItem(h,h),localStorage.removeItem(h),!0}catch(a){return!1}},s.sessionstorage=function(){try{return sessionStorage.setItem(h,h),sessionStorage.removeItem(h),!0}catch(a){return!1}},s.webworkers=function(){return!!a.Worker},s.applicationcache=function(){return!!a.applicationCache},s.svg=function(){return!!b.createElementNS&&!!b.createElementNS(r.svg,"svg").createSVGRect},s.inlinesvg=function(){var a=b.createElement("div");return a.innerHTML="<svg/>",(a.firstChild&&a.firstChild.namespaceURI)==r.svg},s.smil=function(){return!!b.createElementNS&&/SVGAnimate/.test(m.call(b.createElementNS(r.svg,"animate")))},s.svgclippaths=function(){return!!b.createElementNS&&/SVGClipPath/.test(m.call(b.createElementNS(r.svg,"clipPath")))};for(var L in s)C(s,L)&&(x=L.toLowerCase(),e[x]=s[L](),v.push((e[x]?"":"no-")+x));return e.input||K(),e.addTest=function(a,b){if(typeof a=="object")for(var d in a)C(a,d)&&e.addTest(d,a[d]);else{a=a.toLowerCase();if(e[a]!==c)return e;b=typeof b=="function"?b():b,typeof f!="undefined"&&f&&(g.className+=" "+(b?"":"no-")+a),e[a]=b}return e},D(""),i=k=null,function(a,b){function l(a,b){var c=a.createElement("p"),d=a.getElementsByTagName("head")[0]||a.documentElement;return c.innerHTML="x<style>"+b+"</style>",d.insertBefore(c.lastChild,d.firstChild)}function m(){var a=s.elements;return typeof a=="string"?a.split(" "):a}function n(a){var b=j[a[h]];return b||(b={},i++,a[h]=i,j[i]=b),b}function o(a,c,d){c||(c=b);if(k)return c.createElement(a);d||(d=n(c));var g;return d.cache[a]?g=d.cache[a].cloneNode():f.test(a)?g=(d.cache[a]=d.createElem(a)).cloneNode():g=d.createElem(a),g.canHaveChildren&&!e.test(a)&&!g.tagUrn?d.frag.appendChild(g):g}function p(a,c){a||(a=b);if(k)return a.createDocumentFragment();c=c||n(a);var d=c.frag.cloneNode(),e=0,f=m(),g=f.length;for(;e<g;e++)d.createElement(f[e]);return d}function q(a,b){b.cache||(b.cache={},b.createElem=a.createElement,b.createFrag=a.createDocumentFragment,b.frag=b.createFrag()),a.createElement=function(c){return s.shivMethods?o(c,a,b):b.createElem(c)},a.createDocumentFragment=Function("h,f","return function(){var n=f.cloneNode(),c=n.createElement;h.shivMethods&&("+m().join().replace(/[\w\-]+/g,function(a){return b.createElem(a),b.frag.createElement(a),'c("'+a+'")'})+");return n}")(s,b.frag)}function r(a){a||(a=b);var c=n(a);return s.shivCSS&&!g&&!c.hasCSS&&(c.hasCSS=!!l(a,"article,aside,dialog,figcaption,figure,footer,header,hgroup,main,nav,section{display:block}mark{background:#FF0;color:#000}template{display:none}")),k||q(a,c),a}var c="3.7.0",d=a.html5||{},e=/^<|^(?:button|map|select|textarea|object|iframe|option|optgroup)$/i,f=/^(?: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,g,h="_html5shiv",i=0,j={},k;(function(){try{var a=b.createElement("a");a.innerHTML="<xyz></xyz>",g="hidden"in a,k=a.childNodes.length==1||function(){b.createElement("a");var a=b.createDocumentFragment();return typeof a.cloneNode=="undefined"||typeof a.createDocumentFragment=="undefined"||typeof a.createElement=="undefined"}()}catch(c){g=!0,k=!0}})();var s={elements:d.elements||"abbr article aside audio bdi canvas data datalist details dialog figcaption figure footer header hgroup main mark meter nav output progress section summary template time video",version:c,shivCSS:d.shivCSS!==!1,supportsUnknownElements:k,shivMethods:d.shivMethods!==!1,type:"default",shivDocument:r,createElement:o,createDocumentFragment:p};a.html5=s,r(b)}(this,b),e._version=d,e._prefixes=n,e._domPrefixes=q,e._cssomPrefixes=p,e.mq=z,e.hasEvent=A,e.testProp=function(a){return H([a])},e.testAllProps=J,e.testStyles=y,e.prefixed=function(a,b,c){return b?J(a,b,c):J(a,"pfx")},g.className=g.className.replace(/(^|\s)no-js(\s|$)/,"$1$2")+(f?" js "+v.join(" "):""),e}(this,this.document),function(a,b,c){function d(a){return"[object Function]"==o.call(a)}function e(a){return"string"==typeof a}function f(){}function g(a){return!a||"loaded"==a||"complete"==a||"uninitialized"==a}function h(){var a=p.shift();q=1,a?a.t?m(function(){("c"==a.t?B.injectCss:B.injectJs)(a.s,0,a.a,a.x,a.e,1)},0):(a(),h()):q=0}function i(a,c,d,e,f,i,j){function k(b){if(!o&&g(l.readyState)&&(u.r=o=1,!q&&h(),l.onload=l.onreadystatechange=null,b)){"img"!=a&&m(function(){t.removeChild(l)},50);for(var d in y[c])y[c].hasOwnProperty(d)&&y[c][d].onload()}}var j=j||B.errorTimeout,l=b.createElement(a),o=0,r=0,u={t:d,s:c,e:f,a:i,x:j};1===y[c]&&(r=1,y[c]=[]),"object"==a?l.data=c:(l.src=c,l.type=a),l.width=l.height="0",l.onerror=l.onload=l.onreadystatechange=function(){k.call(this,r)},p.splice(e,0,u),"img"!=a&&(r||2===y[c]?(t.insertBefore(l,s?null:n),m(k,j)):y[c].push(l))}function j(a,b,c,d,f){return q=0,b=b||"j",e(a)?i("c"==b?v:u,a,b,this.i++,c,d,f):(p.splice(this.i++,0,a),1==p.length&&h()),this}function k(){var a=B;return a.loader={load:j,i:0},a}var l=b.documentElement,m=a.setTimeout,n=b.getElementsByTagName("script")[0],o={}.toString,p=[],q=0,r="MozAppearance"in l.style,s=r&&!!b.createRange().compareNode,t=s?l:n.parentNode,l=a.opera&&"[object Opera]"==o.call(a.opera),l=!!b.attachEvent&&!l,u=r?"object":l?"script":"img",v=l?"script":u,w=Array.isArray||function(a){return"[object Array]"==o.call(a)},x=[],y={},z={timeout:function(a,b){return b.length&&(a.timeout=b[0]),a}},A,B;B=function(a){function b(a){var a=a.split("!"),b=x.length,c=a.pop(),d=a.length,c={url:c,origUrl:c,prefixes:a},e,f,g;for(f=0;f<d;f++)g=a[f].split("="),(e=z[g.shift()])&&(c=e(c,g));for(f=0;f<b;f++)c=x[f](c);return c}function g(a,e,f,g,h){var i=b(a),j=i.autoCallback;i.url.split(".").pop().split("?").shift(),i.bypass||(e&&(e=d(e)?e:e[a]||e[g]||e[a.split("/").pop().split("?")[0]]),i.instead?i.instead(a,e,f,g,h):(y[i.url]?i.noexec=!0:y[i.url]=1,f.load(i.url,i.forceCSS||!i.forceJS&&"css"==i.url.split(".").pop().split("?").shift()?"c":c,i.noexec,i.attrs,i.timeout),(d(e)||d(j))&&f.load(function(){k(),e&&e(i.origUrl,h,g),j&&j(i.origUrl,h,g),y[i.url]=2})))}function h(a,b){function c(a,c){if(a){if(e(a))c||(j=function(){var a=[].slice.call(arguments);k.apply(this,a),l()}),g(a,j,b,0,h);else if(Object(a)===a)for(n in m=function(){var b=0,c;for(c in a)a.hasOwnProperty(c)&&b++;return b}(),a)a.hasOwnProperty(n)&&(!c&&!--m&&(d(j)?j=function(){var a=[].slice.call(arguments);k.apply(this,a),l()}:j[n]=function(a){return function(){var b=[].slice.call(arguments);a&&a.apply(this,b),l()}}(k[n])),g(a[n],j,b,n,h))}else!c&&l()}var h=!!a.test,i=a.load||a.both,j=a.callback||f,k=j,l=a.complete||f,m,n;c(h?a.yep:a.nope,!!i),i&&c(i)}var i,j,l=this.yepnope.loader;if(e(a))g(a,0,l,0);else if(w(a))for(i=0;i<a.length;i++)j=a[i],e(j)?g(j,0,l,0):w(j)?B(j):Object(j)===j&&h(j,l);else Object(a)===a&&h(a,l)},B.addPrefix=function(a,b){z[a]=b},B.addFilter=function(a){x.push(a)},B.errorTimeout=1e4,null==b.readyState&&b.addEventListener&&(b.readyState="loading",b.addEventListener("DOMContentLoaded",A=function(){b.removeEventListener("DOMContentLoaded",A,0),b.readyState="complete"},0)),a.yepnope=k(),a.yepnope.executeStack=h,a.yepnope.injectJs=function(a,c,d,e,i,j){var k=b.createElement("script"),l,o,e=e||B.errorTimeout;k.src=a;for(o in d)k.setAttribute(o,d[o]);c=j?h:c||f,k.onreadystatechange=k.onload=function(){!l&&g(k.readyState)&&(l=1,c(),k.onload=k.onreadystatechange=null)},m(function(){l||(l=1,c(1))},e),i?k.onload():n.parentNode.insertBefore(k,n)},a.yepnope.injectCss=function(a,c,d,e,g,i){var e=b.createElement("link"),j,c=i?h:c||f;e.href=a,e.rel="stylesheet",e.type="text/css";for(j in d)e.setAttribute(j,d[j]);g||(n.parentNode.insertBefore(e,n),m(c,0))}}(this,document),Modernizr.load=function(){yepnope.apply(window,[].slice.call(arguments,0))};
vendor: 1,764 bytes, lines 4-8
4
5
6/*! jQuery Mobile v1.4.0 | Copyright 2010, 2013 jQuery Foundation, Inc. | jquery.org/license */
7
8(function(e,t,n){typeof define=="function"&&define.amd?define(["jquery"],function(r){return n(r,e,t),r.mobile}):n(e.jQuery,e,t)})(this,document,function(e,t,n,r){(function(e,t,n,r){function T(e){while(e&&typeof e.originalEvent!="undefined")e=e.originalEvent;return e}function N(t,n){var i=t.type,s,o,a,l,c,h,p,d,v;t=e.Event(t),t.type=n,s=t.originalEvent,o=e.event.props,i.search(/^(mouse|click)/)>-1&&(o=f);if(s)for(p=o.length,l;p;)l=o[--p],t[l]=s[l];i.search(/mouse(down|up)|click/)>-1&&!t.which&&(t.which=1);if(i.search(/^touch/)!==-1){a=T(s),i=a.touches,c=a.changedTouches,h=i&&i.length?i[0]:c&&c.length?c[0]:r;if(h)for(d=0,v=u.length;d<v;d++)l=u[d],t[l]=h[l]}return t}function C(t){var n={},r,s;while(t){r=e.data(t,i);for(s in r)r[s]&&(n[s]=n.hasVirtualBinding=!0);t=t.parentNode}return n}function k(t,n){var r;while(t){r=e.data(t,i);if(r&&(!n||r[n]))return t;t=t.parentNode}return null}function L(){g=!1}function A(){g=!0}function O(){E=0,v.length=0,m=!1,A()}function M(){L()}function _(){D(),c=setTimeout(function(){c=0,O()},e.vmouse.resetTimerDuration)}function D(){c&&(clearTimeout(c),c=0)}function P(t,n,r){var i;if(r&&r[t]||!r&&k(n.target,t))i=N(n,t),e(n.target).trigger(i);return i}function H(t){var n=e.data(t.target,s),r;!m&&(!E||E!==n)&&(r=P("v"+t.type,t),r&&(r.isDefaultPrevented()&&t.preventDefault(),r.isPropagationStopped()&&t.stopPropagation(),r.isImmediatePropagationStopped()&&t.stopImmediatePropagation()))}function B(t){var n=T(t).touches,r,i,o;n&&n.length===1&&(r=t.target,i=C(r),i.hasVirtualBinding&&(E=w++,e.data(r,s,E),D(),M(),d=!1,o=T(t).touches[0],h=o.pageX,p=o.pageY,P("vmouseover",t,i),P("vmousedown",t,i)))}function j(e){if(g)return;
8d||P("vmousecancel",e,C(e.target)),d=!0,_()}function F(t){if(g)return;var n=T(t).touches[0],r=d,i=e.vmouse.moveDistanceThreshold,s=C(t.target);d=d||Math.abs(n.pageX-h)>i||Math.abs(n.pageY-p)>i,d&&!r&&P("vmousecancel",t,s),P("vmousemove",t,s),_()}function I(e){if(g)return;A();var t=C(e.target),n,r;P("vmouseup",e,t),d||(n=P("vclick",e,t),n&&n.isDefaultPrevented()&&(r=T(e).changedTouches[0],v.push({touchID:E,x:r.clientX,y:r.clientY}),m=!0)),P("vmouseout",e,t),d=!1,_()}function q(t){var n=e.data(t,i),r;if(n)for(r in n)if(n[r])return!0;return!1}function R(){}function U(t){var n=t.substr(1);return{setup:function(){q(this)||e.data(this,i,{});var r=e.data(this,i);r[t]=!0,l[t]=(l[t]||0)+1,l[t]===1&&b.bind(n,H),e(this).bind(n,R),y&&(l.touchstart=(l.touchstart||0)+1,l.touchstart===1&&b.bind("touchstart",B).bind("touchend",I).bind("touchmove",F).bind("scroll",j))},teardown:function(){--l[t],l[t]||b.unbind(n,H),y&&(--l.touchstart,l.touchstart||b.unbind("touchstart",B).unbind("touchmove",F).unbind("touchend",I).unbind("scroll",j));var r=e(this),s=e.data(this,i);s&&(s[t]=!1),r.unbind(n,R),q(this)||r.removeData(i)}}}var i="virtualMouseBindings",s="virtualTouchID",o="vmouseover vmousedown vmousemove vmouseup vclick vmouseout vmousecancel".split(" "),u="clientX clientY pageX pageY screenX screenY".split(" "),a=e.event.mouseHooks?e.event.mouseHooks.props:[],f=e.event.props.concat(a),l={},c=0,h=0,p=0,d=!1,v=[],m=!1,g=!1,y="addEventListener"in n,b=e(n),w=1,E=0,S,x;e.vmouse={moveDistanceThreshold:10,clickDistanceThreshold:10,resetTimerDuration:1500};for(x=0;x<o.length;x++)e.event.special[o[x]]=U(o[x]);y&&n.addEventListener("click",function(t){var n=v.length,r=t.target,i,o,u,a,f,l;if(n){i=t.clientX,o=t.clientY,S=e.vmouse.clickDistanceThreshold,u=r;while(u){for(a=0;a<n;a++){f=v[a],l=0;if(u===r&&Math.abs(f.x-i)<S&&Math.abs(f.y-o)<S||e.data(u,s)===f.touchID){t.preventDefault(),t.stopPropagation();return}}u=u.parentNode}}},!0)})(e,t,n),function(e){e.mobile={}}(e),function(e,t){var r={touch:"ontouchend"in n};e.mobile.support=e.mobile.support||{},e.extend(e.support,r),e.extend(e.mobile.support,r)}(e),function(e,t,r){function l(t,n,r){var i=r.type;r.type=n,e.event.dispatch.call(t,r),r.type=i}var i=e(n),s=e.mobile.support.touch,o="touchmove scroll",u=s?"touchstart":"mousedown",a=s?"touchend":"mouseup",f=s?"touchmove":"mousemove";e.each("touchstart touchmove touchend tap taphold swipe swipeleft swiperight scrollstart scrollstop".split(" "),function(t,n){e.fn[n]=function(e){return e?this.bind(n,e):this.trigger(n)},e.attrFn&&(e.attrFn[n]=!0)}),e.event.special.scrollstart={enabled:!0,setup:function(){function s(e,n){r=n,l(t,r?"scrollstart":"scrollstop",e)}var t=this,n=e(t),r,i;n.bind(o,function(t){if(!e.event.special.scrollstart.enabled)return;r||s(t,!0),clearTimeout(i),i=setTimeout(function(){s(t,!1)},50)})},teardown:function(){e(this).unbind(o)}},e.event.special.tap={tapholdThreshold:750,emitTapOnTaphold:!0,setup:function(){var t=this,n=e(t),r=!1;n.bind("vmousedown",function(s){function a(){clearTimeout(u)}function f(){a(),n.unbind("vclick",c).unbind("vmouseup",a),i.unbind("vmousecancel",f)}function c(e){f(),!r&&o===e.target?l(t,"tap",e):r&&e.stopPropagation()}r=!1;if(s.which&&s.which!==1)return!1;var o=s.target,u;n.bind("vmouseup",a).bind("vclick",c),i.bind("vmousecancel",f),u=setTimeout(function(){e.event.special.tap.emitTapOnTaphold||(r=!0),l(t,"taphold",e.Event("taphold",{target:o}))},e.event.special.tap.tapholdThreshold)})},teardown:function(){e(this).unbind("vmousedown").unbind("vclick").unbind("vmouseup"),i.unbind("vmousecancel")}},e.event.special.swipe={scrollSupressionThreshold:30,durationThreshold:1e3,horizontalDistanceThreshold:30,verticalDistanceThreshold:75,start:function(t){var n=t.originalEvent.touches?t.originalEvent.touches[0]:t;return{time:(new Date).getTime(),coords:[n.pageX,n.pageY],origin:e(t.target)}},stop:function(e){var t=e.originalEvent.touches?e.originalEvent.touches[0]:e;return{time:(new Date).getTime(),coords:[t.pageX,t.pageY]}},handleSwipe:function(t,n,r,i){if(n.time-t.time<e.event.special.swipe.durationThreshold&&Math.abs(t.coords[0]-n.
8coords[0])>e.event.special.swipe.horizontalDistanceThreshold&&Math.abs(t.coords[1]-n.coords[1])<e.event.special.swipe.verticalDistanceThreshold){var s=t.coords[0]>n.coords[0]?"swipeleft":"swiperight";return l(r,"swipe",e.Event("swipe",{target:i,swipestart:t,swipestop:n})),l(r,s,e.Event(s,{target:i,swipestart:t,swipestop:n})),!0}return!1},setup:function(){var t=this,n=e(t);n.bind(u,function(r){function l(n){if(!s)return;i=e.event.special.swipe.stop(n),u||(u=e.event.special.swipe.handleSwipe(s,i,t,o)),Math.abs(s.coords[0]-i.coords[0])>e.event.special.swipe.scrollSupressionThreshold&&n.preventDefault()}var i,s=e.event.special.swipe.start(r),o=r.target,u=!1;n.bind(f,l).one(a,function(){u=!0,n.unbind(f,l)})})},teardown:function(){e(this).unbind(u).unbind(f).unbind(a)}},e.each({scrollstop:"scrollstart",taphold:"tap",swipeleft:"swipe",swiperight:"swipe"},function(t,n){e.event.special[t]={setup:function(){e(this).bind(n,e.noop)},teardown:function(){e(this).unbind(n)}}})}(e,this)});
vendor: 27,822 bytes, lines 9-15
9/*!
10 * Bootstrap v3.0.3 (http://getbootstrap.com)
11 * Copyright 2013 Twitter, Inc.
12 * Licensed under http://www.apache.org/licenses/LICENSE-2.0
13 */
14
15if("undefined"==typeof jQuery)throw new Error("Bootstrap requires jQuery");+function(a){"use strict";function b(){var a=document.createElement("bootstrap"),b={WebkitTransition:"webkitTransitionEnd",MozTransition:"transitionend",OTransition:"oTransitionEnd otransitionend",transition:"transitionend"};for(var c in b)if(void 0!==a.style[c])return{end:b[c]}}a.fn.emulateTransitionEnd=function(b){var c=!1,d=this;a(this).one(a.support.transition.end,function(){c=!0});var e=function(){c||a(d).trigger(a.support.transition.end)};return setTimeout(e,b),this},a(function(){a.support.transition=b()})}(jQuery),+function(a){"use strict";var b='[data-dismiss="alert"]',c=function(c){a(c).on("click",b,this.close)};c.prototype.close=function(b){function c(){f.trigger("closed.bs.alert").remove()}var d=a(this),e=d.attr("data-target");e||(e=d.attr("href"),e=e&&e.replace(/.*(?=#[^\s]*$)/,""));var f=a(e);b&&b.preventDefault(),f.length||(f=d.hasClass("alert")?d:d.parent()),f.trigger(b=a.Event("close.bs.alert")),b.isDefaultPrevented()||(f.removeClass("in"),a.support.transition&&f.hasClass("fade")?f.one(a.support.transition.end,c).emulateTransitionEnd(150):c())};var d=a.fn.alert;a.fn.alert=function(b){return this.each(function(){var d=a(this),e=d.data("bs.alert");e||d.data("bs.alert",e=new c(this)),"string"==typeof b&&e[b].call(d)})},a.fn.alert.Constructor=c,a.fn.alert.noConflict=function(){return a.fn.alert=d,this},a(document).on("click.bs.alert.data-api",b,c.prototype.close)}(jQuery),+function(a){"use strict";var b=function(c,d){this.$element=a(c),this.options=a.extend({},b.DEFAULTS,d)};b.DEFAULTS={loadingText:"loading..."},b.prototype.setState=function(a){var b="disabled",c=this.$element,d=c.is("input")?"val":"html",e=c.data();a+="Text",e.resetText||c.data("resetText",c[d]()),c[d](e[a]||this.options[a]),setTimeout(function(){"loadingText"==a?c.addClass(b).attr(b,b):c.removeClass(b).removeAttr(b)},0)},b.prototype.toggle=function(){var a=this.$element.closest('[data-toggle="buttons"]'),b=!0;if(a.length){var c=this.$element.find("input");"radio"===c.prop("type")&&(c.prop("checked")&&this.$element.hasClass("active")?b=!1:a.find(".active").removeClass("active")),b&&c.prop("checked",!this.$element.hasClass("active")).trigger("change")}b&&this.$element.toggleClass("active")};var c=a.fn.button;a.fn.button=function(c){return this.each(function(){var d=a(this),e=d.data("bs.button"),f="object"==typeof c&&c;e||d.data("bs.button",e=new b(this,f)),"toggle"==c?e.toggle():c&&e.setState(c)})},a.fn.button.Constructor=b,a.fn.button.noConflict=function(){return a.fn.button=c,this},a(document).on("click.bs.button.data-api","[data-toggle^=button]",function(b){var c=a(b.target);c.hasClass("btn")||(c=c.closest(".btn")),c.button("toggle"),b.preventDefault()})}(jQuery),+function(a){"use strict";var b=function(b,c){this.$element=a(b),this.$indicators=this.$element.find(".carousel-indicators"),this.options=c,this.paused=this.sliding=this.interval=this.$active=this.$items=null,"hover"==this.options.pause&&this.$element.on("mouseenter",a.proxy(this.pause,this)).on("mouseleave",a.proxy(this.cycle,this))};b.DEFAULTS={interval:5e3,pause:"hover",wrap:!0},b.prototype.cycle=function(b){return b||(this.paused=!1),this.interval&&clearInterval(this.interval),this.options.interval&&!this.paused&&(this.interval=setInterval(a.proxy(this.next,this),this.options.interval)),this},b.prototype.getActiveIndex=function(){return this.$active=this.$element.find(".item.active"),this.$items=this.$active.parent().children(),this.$items.index(this.$active)},b.prototype.to=function(b){var c=this,d=this.getActiveIndex();return b>this.$items.length-1||0>b?void 0:this.sliding?this.$element.one("slid.bs.carousel",function(){c.to(b)}):d==b?this.pause().cycle():this.slide(b>d?"next":"prev",a(this.$items[b]))},b.prototype.pause=function(b){return b||(this.paused=!0),this.$element.find(".next, .prev").length&&a.support.transition.end&&(this.$element.trigger(a.support.transition.end),this.cycle(!0)),this.interval=clearInterval(this.interval),this},b.prototype.next=function(){return this.sliding?void 0:this.slide("next")},b.prototype.prev=function(){return this.sliding?void 0:this.slide("prev")},b.prototype.slide=function(b,c){var d=this.$element.find(".item.active"),e=c||d[b](),f=this.interval,g="next"==b?"left":"right",h="next"==b?"first":"last",i=this;if(!e.length){if(!this.options.wrap)return;e=this.$element.find(".item")[h]()}this.sliding=!0,f&&this.pause();var j=a.Event("slide.bs.carousel",{relatedTarget:e[0],direction:g});if(!e.hasClass("active")){if(this.$indicators.length&&(this.$indicators.find(".active").removeClass("active"),this.$element.one("slid.bs.carousel",function(){var b=a(i.$indicators.children()[i.getActiveIndex()]);b&&b.addClass("active")})),a.support.transition&&this.$element.hasClass("slide")){if(this.$element.trigger(j),j.isDefaultPrevented())return;e.addClass(b),e[0].offsetWidth,d.addClass(g),e.addClass(g),d.one(a.support.transition.end,function(){e.removeClass([b,g].join(" ")).addClass("active"),d.removeClass(["active",g].join(" ")),i.sliding=!1,setTimeout(function(){i.$element.trigger("slid.bs.carousel")},0)}).emulateTransitionEnd(600)}else{if(this.$element.trigger(j),j.isDefaultPrevented())return;d.removeClass("active"),e.addClass("active"),this.sliding=!1,this.$element.trigger("slid.bs.carousel")}return f&&this.cycle(),this}};var c=a.fn.carousel;a.fn.carousel=function(c){return this.each(function(){var d=a(this),e=d.data("bs.carousel"),f=a.extend({},b.DEFAULTS,d.data(),"object"==typeof c&&c),g="string"==typeof c?c:f.slide;e||d.data("bs.carousel",e=new b(this,f)),"number"==typeof c?e.to(c):g?e[g]():f.interval&&e.pause().cycle()})},a.fn.carousel.Constructor=b,a.fn.carousel.noConflict=function(){return a.fn.carousel=c,this},a(document).on("click.bs.carousel.data-api","[data-slide], [data-slide-to]",function(b){var c,d=a(this),e=a(d.attr("data-target")||(c=d.attr("href"))&&c.replace(/.*(?=#[^\s]+$)/,"")),f=a.extend({},e.data(),d.data()),g=d.attr("data-slide-to");g&&(f.interval=!1),e.carousel(f),(g=d.attr("data-slide-to"))&&e.data("bs.carousel").to(g),b.preventDefault()}),a(window).on("load",function(){a('[data-ride="carousel"]').each(function(){var b=a(this);b.carousel(b.data())})})}(jQuery),+function(a){"use strict";var b=function(c,d){this.$element=a(c),this.options=a.extend({},b.DEFAULTS,d),this.transitioning=null,this.options.parent&&(this.$parent=a(this.options.parent)),this.options.toggle&&this.toggle()};b.DEFAULTS={toggle:!0},b.prototype.dimension=function(){var a=this.$element.hasClass("width");return a?"width":"height"},b.prototype.show=function(){if(!this.transitioning&&!this.$element.hasClass("in")){var b=a.Event("show.bs.collapse");if(this.$element.trigger(b),!b.isDefaultPrevented()){var c=this.$parent&&this.$parent.find("> .panel > .in");if(c&&c.length){var d=c.data("bs.collapse");if(d&&d.transitioning)return;c.collapse("hide"),d||c.data("bs.collapse",null)}var e=this.dimension();this.$element.removeClass("collapse").addClass("collapsing")[e](0),this.transitioning=1;var f=function(){this.$element.removeClass("collapsing").addClass("in")[e]("auto"),this.transitioning=0,this.$element.trigger("shown.bs.collapse")};if(!a.support.transition)return f.call(this);var g=a.camelCase(["scroll",e].join("-"));this.$element.one(a.support.transition.end,a.proxy(f,this)).emulateTransitionEnd(350)[e](this.$element[0][g])}}},b.prototype.hide=function(){if(!this.transitioning&&this.$element.hasClass("in")){var b=a.Event("hide.bs.collapse");if(this.$element.trigger(b),!b.isDefaultPrevented()){var c=this.dimension();this.$element[c](this.$element[c]())[0].offsetHeight,this.$element.addClass("collapsing").removeClass("collapse").removeClass("in"),this.transitioning=1;var d=function(){this.transitioning=0,this.$element.trigger("hidden.bs.collapse").removeClass("collapsing").addClass("collapse")};return a.support.transition?(this.$element[c](0).one(a.support.transition.end,a.proxy(d,this)).emulateTransitionEnd(350),void 0):d.call(this)}}},b.prototype.toggle=function(){this[this.$element.hasClass("in")?"hide":"show"]()};var c=a.fn.collapse;a.fn.collapse=function(c){return this.each(function(){var d=a(this),e=d.data("bs.collapse"),f=a.extend({},b.DEFAULTS,d.data(),"object"==typeof c&&c);e||d.data("bs.collapse",e=new b(this,f)),"string"==typeof c&&e[c]()})},a.fn.collapse.Constructor=b,a.fn.collapse.noConflict=function(){return a.fn.collapse=c,this},a(document).on("click.bs.collapse.data-api","[data-toggle=collapse]",function(b){var c,d=a(this),e=d.attr("data-target")||b.preventDefault()||(c=d.attr("href"))&&c.replace(/.*(?=#[^\s]+$)/,""),f=a(e),g=f.data("bs.collapse"),h=g?"toggle":d.data(),i=d.attr("data-parent"),j=i&&a(i);g&&g.transitioning||(j&&j.find('[data-toggle=collapse][data-parent="'+i+'"]').not(d).addClass("collapsed"),d[f.hasClass("in")?"addClass":"removeClass"]("collapsed")),f.collapse(h)})}(jQuery),+function(a){"use strict";function b(){a(d).remove(),a(e).each(function(b){var d=c(a(this));d.hasClass("open")&&(d.trigger(b=a.Event("hide.bs.dropdown")),b.isDefaultPrevented()||d.removeClass("open").trigger("hidden.bs.dropdown"))})}function c(b){var c=b.attr("data-target");c||(c=b.attr("href"),c=c&&/#/.test(c)&&c.replace(/.*(?=#[^\s]*$)/,""));var d=c&&a(c);return d&&d.length?d:b.parent()}var d=".dropdown-backdrop",e="[data-toggle=dropdown]",f=function(b){a(b).on("click.bs.dropdown",this.toggle)};f.prototype.toggle=function(d){var e=a(this);if(!e.is(".disabled, :disabled")){var f=c(e),g=f.hasClass("open");if(b(),!g){if("ontouchstart"in document.documentElement&&!f.closest(".navbar-nav").length&&a('<div class="dropdown-backdrop"/>').insertAfter(a(this)).on("click",b),f.trigger(d=a.Event("show.bs.dropdown")),d.isDefaultPrevented())return;f.toggleClass("open").trigger("shown.bs.dropdown"),e.focus()}return!1}},f.prototype.keydown=function(b){if(/(38|40|27)/.test(b.keyCode)){var d=a(this);if(b.preventDefault(),b.stopPropagation(),!d.is(".disabled, :disabled")){var f=c(d),g=f.hasClass("open");if(!g||g&&27==b.keyCode)return 27==b.which&&f.find(e).focus(),d.click();var h=a("[role=menu] li:not(.divider):visible a",f);if(h.length){var i=h.index(h.filter(":focus"));38==b.keyCode&&i>0&&i--,40==b.keyCode&&i<h.length-1&&i++,~i||(i=0),h.eq(i).focus()}}}};var g=a.fn.dropdown;a.fn.dropdown=function(b){return this.each(function(){var c=a(this),d=c.data("bs.dropdown");d||c.data("bs.dropdown",d=new f(this)),"string"==typeof b&&d[b].call(c)})},a.fn.dropdown.Constructor=f,a.fn.dropdown.noConflict=function(){return a.fn.dropdown=g,this},a(document).on("click.bs.dropdown.data-api",b).on("click.bs.dropdown.data-api",".dropdown form",function(a){a.stopPropagation()}).on("click.bs.dropdown.data-api",e,f.prototype.toggle).on("keydown.bs.dropdown.data-api",e+", [role=menu]",f.prototype.keydown)}(jQuery),+function(a){"use strict";var b=function(b,c){this.options=c,this.$element=a(b),this.$backdrop=this.isShown=null,this.options.remote&&this.$element.load(this.options.remote)};b.DEFAULTS={backdrop:!0,keyboard:!0,show:!0},b.prototype.toggle=function(a){return this[this.isShown?"hide":"show"](a)},b.prototype.show=function(b){var c=this,d=a.Event("show.bs.modal",{relatedTarget:b});this.$element.trigger(d),this.isShown||d.isDefaultPrevented()||(this.isShown=!0,this.escape(),this.$element.on("click.dismiss.modal",'[data-dismiss="modal"]',a.proxy(this.hide,this)),this.backdrop(function(){var d=a.support.transition&&c.$element.hasClass("fade");c.$element.parent().length||c.$element.appendTo(document.body),c.$element.show(),d&&c.$element[0].offsetWidth,c.$element.addClass("in").attr("aria-hidden",!1),c.enforceFocus();var e=a.Event("shown.bs.modal",{relatedTarget:b});d?c.$element.find(".modal-dialog").one(a.support.transition.end,function(){c.$element.focus().trigger(e)}).emulateTransitionEnd(300):c.$element.focus().trigger(e)}))},b.prototype.hide=function(b){b&&b.preventDefault(),b=a.Event("hide.bs.modal"),this.$element.trigger(b),this.isShown&&!b.isDefaultPrevented()&&(this.isShown=!1,this.escape(),a(document).off("focusin.bs.modal"),this.$element.removeClass("in").attr("aria-hidden",!0).off("click.dismiss.modal"),a.support.transition&&this.$element.hasClass("fade")?this.$element.one(a.support.transition.end,a.proxy(this.hideModal,this)).emulateTransitionEnd(300):this.hideModal())},b.prototype.enforceFocus=function(){a(document).off("focusin.bs.modal").on("focusin.bs.modal",a.proxy(function(a){this.$element[0]===a.target||this.$element.has(a.target).length||this.$element.focus()},this))},b.prototype.escape=function(){this.isShown&&this.options.keyboard?this.$element.on("keyup.dismiss.bs.modal",a.proxy(function(a){27==a.which&&this.hide()},this)):this.isShown||this.$element.off("keyup.dismiss.bs.modal")},b.prototype.hideModal=function(){var a=this;this.$element.hide(),this.backdrop(function(){a.removeBackdrop(),a.$element.trigger("hidden.bs.modal")})},b.prototype.removeBackdrop=function(){this.$backdrop&&this.$backdrop.remove(),this.$backdrop=null},b.prototype.backdrop=function(b){var c=this.$element.hasClass("fade")?"fade":"";if(this.isShown&&this.options.backdrop){var d=a.support.transition&&c;if(this.$backdrop=a('<div class="modal-backdrop '+c+'" />').appendTo(document.body),this.$element.on("click.dismiss.modal",a.proxy(function(a){a.target===a.currentTarget&&("static"==this.options.backdrop?this.$element[0].focus.call(this.$element[0]):this.hide.call(this))},this)),d&&this.$backdrop[0].offsetWidth,this.$backdrop.addClass("in"),!b)return;d?this.$backdrop.one(a.support.transition.end,b).emulateTransitionEnd(150):b()}else!this.isShown&&this.$backdrop?(this.$backdrop.removeClass("in"),a.support.transition&&this.$element.hasClass("fade")?this.$backdrop.one(a.support.transition.end,b).emulateTransitionEnd(150):b()):b&&b()};var c=a.fn.modal;a.fn.modal=function(c,d){return this.each(function(){var e=a(this),f=e.data("bs.modal"),g=a.extend({},b.DEFAULTS,e.data(),"object"==typeof c&&c);f||e.data("bs.modal",f=new b(this,g)),"string"==typeof c?f[c](d):g.show&&f.show(d)})},a.fn.modal.Constructor=b,a.fn.modal.noConflict=function(){return a.fn.modal=c,this},a(document).on("click.bs.modal.data-api",'[data-toggle="modal"]',function(b){var c=a(this),d=c.attr("href"),e=a(c.attr("data-target")||d&&d.replace(/.*(?=#[^\s]+$)/,"")),f=e.data("modal")?"toggle":a.extend({remote:!/#/.test(d)&&d},e.data(),c.data());b.preventDefault(),e.modal(f,this).one("hide",function(){c.is(":visible")&&c.focus()})}),a(document).on("show.bs.modal",".modal",function(){a(document.body).addClass("modal-open")}).on("hidden.bs.modal",".modal",function(){a(document.body).removeClass("modal-open")})}(jQuery),+function(a){"use strict";var b=function(a,b){this.type=this.options=this.enabled=this.timeout=this.hoverState=this.$element=null,this.init("tooltip",a,b)};b.DEFAULTS={animation:!0,placement:"top",selector:!1,template:'<div class="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>',trigger:"hover focus",title:"",delay:0,html:!1,container:!1},b.prototype.init=function(b,c,d){this.enabled=!0,this.type=b,this.$element=a(c),this.options=this.getOptions(d);for(var e=this.options.trigger.split(" "),f=e.length;f--;){var g=e[f];if("click"==g)this.$element.on("click."+this.type,this.options.selector,a.proxy(this.toggle,this));else if("manual"!=g){var h="hover"==g?"mouseenter":"focus",i="hover"==g?"mouseleave":"blur";this.$element.on(h+"."+this.type,this.options.selector,a.proxy(this.enter,this)),this.$element.on(i+"."+this.type,this.options.selector,a.proxy(this.leave,this))}}this.options.selector?this._options=a.extend({},this.options,{trigger:"manual",selector:""}):this.fixTitle()},b.prototype.getDefaults=function(){return b.DEFAULTS},b.prototype.getOptions=function(b){return b=a.extend({},this.getDefaults(),this.$element.data(),b),b.delay&&"number"==typeof b.delay&&(b.delay={show:b.delay,hide:b.delay}),b},b.prototype.getDelegateOptions=function(){var b={},c=this.getDefaults();return this._options&&a.each(this._options,function(a,d){c[a]!=d&&(b[a]=d)}),b},b.prototype.enter=function(b){var c=b instanceof this.constructor?b:a(b.currentTarget)[this.type](this.getDelegateOptions()).data("bs."+this.type);return clearTimeout(c.timeout),c.hoverState="in",c.options.delay&&c.options.delay.show?(c.timeout=setTimeout(function(){"in"==c.hoverState&&c.show()},c.options.delay.show),void 0):c.show()},b.prototype.leave=function(b){var c=b instanceof this.constructor?b:a(b.currentTarget)[this.type](this.getDelegateOptions()).data("bs."+this.type);return clearTimeout(c.timeout),c.hoverState="out",c.options.delay&&c.options.delay.hide?(c.timeout=setTimeout(function(){"out"==c.hoverState&&c.hide()},c.options.delay.hide),void 0):c.hide()},b.prototype.show=function(){var b=a.Event("show.bs."+this.type);if(this.hasContent()&&this.enabled){if(this.$element.trigger(b),b.isDefaultPrevented())return;var c=this.tip();this.setContent(),this.options.animation&&c.addClass("fade");var d="function"==typeof this.options.placement?this.options.placement.call(this,c[0],this.$element[0]):this.options.placement,e=/\s?auto?\s?/i,f=e.test(d);f&&(d=d.replace(e,"")||"top"),c.detach().css({top:0,left:0,display:"block"}).addClass(d),this.options.container?c.appendTo(this.options.container):c.insertAfter(this.$element);var g=this.getPosition(),h=c[0].offsetWidth,i=c[0].offsetHeight;if(f){var j=this.$element.parent(),k=d,l=document.documentElement.scrollTop||document.body.scrollTop,m="body"==this.options.container?window.innerWidth:j.outerWidth(),n="body"==this.options.container?window.innerHeight:j.outerHeight(),o="body"==this.options.container?0:j.offset().left;d="bottom"==d&&g.top+g.height+i-l>n?"top":"top"==d&&g.top-l-i<0?"bottom":"right"==d&&g.right+h>m?"left":"left"==d&&g.left-h<o?"right":d,c.removeClass(k).addClass(d)}var p=this.getCalculatedOffset(d,g,h,i);this.applyPlacement(p,d),this.$element.trigger("shown.bs."+this.type)}},b.prototype.applyPlacement=function(a,b){var c,d=this.tip(),e=d[0].offsetWidth,f=d[0].offsetHeight,g=parseInt(d.css("margin-top"),10),h=parseInt(d.css("margin-left"),10);isNaN(g)&&(g=0),isNaN(h)&&(h=0),a.top=a.top+g,a.left=a.left+h,d.offset(a).addClass("in");var i=d[0].offsetWidth,j=d[0].offsetHeight;if("top"==b&&j!=f&&(c=!0,a.top=a.top+f-j),/bottom|top/.test(b)){var k=0;a.left<0&&(k=-2*a.left,a.left=0,d.offset(a),i=d[0].offsetWidth,j=d[0].offsetHeight),this.replaceArrow(k-e+i,i,"left")}else this.replaceArrow(j-f,j,"top");c&&d.offset(a)},b.prototype.replaceArrow=function(a,b,c){this.arrow().css(c,a?50*(1-a/b)+"%":"")},b.prototype.setContent=function(){var a=this.tip(),b=this.getTitle();a.find(".tooltip-inner")[this.options.html?"html":"text"](b),a.removeClass("fade in top bottom left right")},b.prototype.hide=function(){function b(){"in"!=c.hoverState&&d.detach()}var c=this,d=this.tip(),e=a.Event("hide.bs."+this.type);return this.$element.trigger(e),e.isDefaultPrevented()?void 0:(d.removeClass("in"),a.support.transition&&this.$tip.hasClass("fade")?d.one(a.support.transition.end,b).emulateTransitionEnd(150):b(),this.$element.trigger("hidden.bs."+this.type),this)},b.prototype.fixTitle=function(){var a=this.$element;(a.attr("title")||"string"!=typeof a.attr("data-original-title"))&&a.attr("data-original-title",a.attr("title")||"").attr("title","")},b.prototype.hasContent=function(){return this.getTitle()},b.prototype.getPosition=function(){var b=this.$element[0];return a.extend({},"function"==typeof b.getBoundingClientRect?b.getBoundingClientRect():{width:b.offsetWidth,height:b.offsetHeight},this.$element.offset())},b.prototype.getCalculatedOffset=function(a,b,c,d){return"bottom"==a?{top:b.top+b.height,left:b.left+b.width/2-c/2}:"top"==a?{top:b.top-d,left:b.left+b.width/2-c/2}:"left"==a?{top:b.top+b.height/2-d/2,left:b.left-c}:{top:b.top+b.height/2-d/2,left:b.left+b.width}},b.prototype.getTitle=function(){var a,b=this.$element,c=this.options;return a=b.attr("data-original-title")||("function"==typeof c.title?c.title.call(b[0]):c.title)},b.prototype.tip=function(){return this.$tip=this.$tip||a(this.options.template)},b.prototype.arrow=function(){return this.$arrow=this.$arrow||this.tip().find(".tooltip-arrow")},b.prototype.validate=function(){this.$element[0].parentNode||(this.hide(),this.$element=null,this.options=null)},b.prototype.enable=function(){this.enabled=!0},b.prototype.disable=function(){this.enabled=!1},b.prototype.toggleEnabled=function(){this.enabled=!this.enabled},b.prototype.toggle=function(b){var c=b?a(b.currentTarget)[this.type](this.getDelegateOptions()).data("bs."+this.type):this;c.tip().hasClass("in")?c.leave(c):c.enter(c)},b.prototype.destroy=function(){this.hide().$element.off("."+this.type).removeData("bs."+this.type)};var c=a.fn.tooltip;a.fn.tooltip=function(c){return this.each(function(){var d=a(this),e=d.data("bs.tooltip"),f="object"==typeof c&&c;e||d.data("bs.tooltip",e=new b(this,f)),"string"==typeof c&&e[c]()})},a.fn.tooltip.Constructor=b,a.fn.tooltip.noConflict=function(){return a.fn.tooltip=c,this}}(jQuery),+function(a){"use strict";var b=function(a,b){this.init("popover",a,b)};if(!a.fn.tooltip)throw new Error("Popover requires tooltip.js");b.DEFAULTS=a.extend({},a.fn.tooltip.Constructor.DEFAULTS,{placement:"right",trigger:"click",content:"",template:'<div class="popover"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content"></div></div>'}),b.prototype=a.extend({},a.fn.tooltip.Constructor.prototype),b.prototype.constructor=b,b.prototype.getDefaults=function(){return b.DEFAULTS},b.prototype.setContent=function(){var a=this.tip(),b=this.getTitle(),c=this.getContent();a.find(".popover-title")[this.options.html?"html":"text"](b),a.find(".popover-content")[this.options.html?"html":"text"](c),a.removeClass("fade top bottom left right in"),a.find(".popover-title").html()||a.find(".popover-title").hide()},b.prototype.hasContent=function(){return this.getTitle()||this.getContent()},b.prototype.getContent=function(){var a=this.$element,b=this.options;return a.attr("data-content")||("function"==typeof b.content?b.content.call(a[0]):b.content)},b.prototype.arrow=function(){return this.$arrow=this.$arrow||this.tip().find(".arrow")},b.prototype.tip=function(){return this.$tip||(this.$tip=a(this.options.template)),this.$tip};var c=a.fn.popover;a.fn.popover=function(c){return this.each(function(){var d=a(this),e=d.data("bs.popover"),f="object"==typeof c&&c;e||d.data("bs.popover",e=new b(this,f)),"string"==typeof c&&e[c]()})},a.fn.popover.Constructor=b,a.fn.popover.noConflict=function(){return a.fn.popover=c,this}}(jQuery),+function(a){"use strict";function b(c,d){var e,f=a.proxy(this.process,this);this.$element=a(c).is("body")?a(window):a(c),this.$body=a("body"),this.$scrollElement=this.$element.on("scroll.bs.scroll-spy.data-api",f),this.options=a.extend({},b.DEFAULTS,d),this.selector=(this.options.target||(e=a(c).attr("href"))&&e.replace(/.*(?=#[^\s]+$)/,"")||"")+" .nav li > a",this.offsets=a([]),this.targets=a([]),this.activeTarget=null,this.refresh(),this.process()}b.DEFAULTS={offset:10},b.prototype.refresh=function(){var b=this.$element[0]==window?"offset":"position";this.offsets=a([]),this.targets=a([]);var c=this;this.$body.find(this.selector).map(function(){var d=a(this),e=d.data("target")||d.attr("href"),f=/^#\w/.test(e)&&a(e);return f&&f.length&&[[f[b]().top+(!a.isWindow(c.$scrollElement.get(0))&&c.$scrollElement.scrollTop()),e]]||null}).sort(function(a,b){return a[0]-b[0]}).each(function(){c.offsets.push(this[0]),c.targets.push(this[1])})},b.prototype.process=function(){var a,b=this.$scrollElement.scrollTop()+this.options.offset,c=this.$scrollElement[0].scrollHeight||this.$body[0].scrollHeight,d=c-this.$scrollElement.height(),e=this.offsets,f=this.targets,g=this.activeTarget;if(b>=d)return g!=(a=f.last()[0])&&this.activate(a);for(a=e.length;a--;)g!=f[a]&&b>=e[a]&&(!e[a+1]||b<=e[a+1])&&this.activate(f[a])},b.prototype.activate=function(b){this.activeTarget=b,a(this.selector).parents(".active").removeClass("active");var c=this.selector+'[data-target="'+b+'"],'+this.selector+'[href="'+b+'"]',d=a(c).parents("li").addClass("active");d.parent(".dropdown-menu").length&&(d=d.closest("li.dropdown").addClass("active")),d.trigger("activate.bs.scrollspy")};var c=a.fn.scrollspy;a.fn.scrollspy=function(c){return this.each(function(){var d=a(this),e=d.data("bs.scrollspy"),f="object"==typeof c&&c;e||d.data("bs.scrollspy",e=new b(this,f)),"string"==typeof c&&e[c]()})},a.fn.scrollspy.Constructor=b,a.fn.scrollspy.noConflict=function(){return a.fn.scrollspy=c,this},a(window).on("load",function(){a('[data-spy="scroll"]').each(function(){var b=a(this);b.scrollspy(b.data())})})}(jQuery),+function(a){"use strict";var b=function(b){this.element=a(b)};b.prototype.show=function(){var b=this.element,c=b.closest("ul:not(.dropdown-menu)"),d=b.data("target");if(d||(d=b.attr("href"),d=d&&d.replace(/.*(?=#[^\s]*$)/,"")),!b.parent("li").hasClass("active")){var e=c.find(".active:last a")[0],f=a.Event("show.bs.tab",{relatedTarget:e});if(b.trigger(f),!f.isDefaultPrevented()){var g=a(d);this.activate(b.parent("li"),c),this.activate(g,g.parent(),function(){b.trigger({type:"shown.bs.tab",relatedTarget:e})})}}},b.prototype.activate=function(b,c,d){function e(){f.removeClass("active").find("> .dropdown-menu > .active").removeClass("active"),b.addClass("active"),g?(b[0].offsetWidth,b.addClass("in")):b.removeClass("fade"),b.parent(".dropdown-menu")&&b.closest("li.dropdown").addClass("active"),d&&d()}var f=c.find("> .active"),g=d&&a.support.transition&&f.hasClass("fade");g?f.one(a.support.transition.end,e).emulateTransitionEnd(150):e(),f.removeClass("in")};var c=a.fn.tab;a.fn.tab=function(c){return this.each(function(){var d=a(this),e=d.data("bs.tab");e||d.data("bs.tab",e=new b(this)),"string"==typeof c&&e[c]()})},a.fn.tab.Constructor=b,a.fn.tab.noConflict=function(){return a.fn.tab=c,this},a(document).on("click.bs.tab.data-api",'[data-toggle="tab"], [data-toggle="pill"]',function(b){b.preventDefault(),a(this).tab("show")})}(jQuery),+function(a){"use strict";var b=function(c,d){this.options=a.extend({},b.DEFAULTS,d),this.$window=a(window).on("scroll.bs.affix.data-api",a.proxy(this.checkPosition,this)).on("click.bs.affix.data-api",a.proxy(this.checkPositionWithEventLoop,this)),this.$element=a(c),this.affixed=this.unpin=null,this.checkPosition()};b.RESET="affix affix-top affix-bottom",b.DEFAULTS={offset:0},b.prototype.checkPositionWithEventLoop=function(){setTimeout(a.proxy(this.checkPosition,this),1)},b.prototype.checkPosition=function(){if(this.$element.is(":visible")){var c=a(document).height(),d=this.$window.scrollTop(),e=this.$element.offset(),f=this.options.offset,g=f.top,h=f.bottom;"object"!=typeof f&&(h=g=f),"function"==typeof g&&(g=f.top()),"function"==typeof h&&(h=f.bottom());var i=null!=this.unpin&&d+this.unpin<=e.top?!1:null!=h&&e.top+this.$element.height()>=c-h?"bottom":null!=g&&g>=d?"top":!1;this.affixed!==i&&(this.unpin&&this.$element.css("top",""),this.affixed=i,this.unpin="bottom"==i?e.top-d:null,this.$element.removeClass(b.RESET).addClass("affix"+(i?"-"+i:"")),"bottom"==i&&this.$element.offset({top:document.body.offsetHeight-h-this.$element.height()}))}};var c=a.fn.affix;a.fn.affix=function(c){return this.each(function(){var d=a(this),e=d.data("bs.affix"),f="object"==typeof c&&c;e||d.data("bs.affix",e=new b(this,f)),"string"==typeof c&&e[c]()})},a.fn.affix.Constructor=b,a.fn.affix.noConflict=function(){return a.fn.affix=c,this},a(window).on("load",function(){a('[data-spy="affix"]').each(function(){var b=a(this),c=b.data();c.offset=c.offset||{},c.offsetBottom&&(c.offset.bottom=c.offsetBottom),c.offsetTop&&(c.offset.top=c.offsetTop),b.affix(c)})})}(jQuery);
vendor: 20,971 bytes, lines 15-42
15
16/**!
17
18 @license
19 handlebars v4.7.6
20
21Copyright (C) 2011-2019 by Yehuda Katz
22
23Permission is hereby granted, free of charge, to any person obtaining a copy
24of this software and associated documentation files (the "Software"), to deal
25in the Software without restriction, including without limitation the rights
26to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
27copies of the Software, and to permit persons to whom the Software is
28furnished to do so, subject to the following conditions:
29
30The above copyright notice and this permission notice shall be included in
31all copies or substantial portions of the Software.
32
33THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
34IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
35FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
36AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
37LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
38OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
39THE SOFTWARE.
40
41*/
42!function(a,b){"object"==typeof exports&&"object"==typeof module?module.exports=b():"function"==typeof define&&define.amd?define([],b):"object"==typeof exports?exports.Handlebars=b():a.Handlebars=b()}(this,function(){return function(a){function b(d){if(c[d])return c[d].exports;var e=c[d]={exports:{},id:d,loaded:!1};return a[d].call(e.exports,e,e.exports,b),e.loaded=!0,e.exports}var c={};return b.m=a,b.c=c,b.p="",b(0)}([function(a,b,c){"use strict";function d(){var a=r();return a.compile=function(b,c){return k.compile(b,c,a)},a.precompile=function(b,c){return k.precompile(b,c,a)},a.AST=i["default"],a.Compiler=k.Compiler,a.JavaScriptCompiler=m["default"],a.Parser=j.parser,a.parse=j.parse,a.parseWithoutProcessing=j.parseWithoutProcessing,a}var e=c(1)["default"];b.__esModule=!0;var f=c(2),g=e(f),h=c(45),i=e(h),j=c(46),k=c(51),l=c(52),m=e(l),n=c(49),o=e(n),p=c(44),q=e(p),r=g["default"].create,s=d();s.create=d,q["default"](s),s.Visitor=o["default"],s["default"]=s,b["default"]=s,a.exports=b["default"]},function(a,b){"use strict";b["default"]=function(a){return a&&a.__esModule?a:{"default":a}},b.__esModule=!0},function(a,b,c){"use strict";function d(){var a=new h.HandlebarsEnvironment;return n.extend(a,h),a.SafeString=j["default"],a.Exception=l["default"],a.Utils=n,a.escapeExpression=n.escapeExpression,a.VM=p,a.template=function(b){return p.template(b,a)},a}var e=c(3)["default"],f=c(1)["default"];b.__esModule=!0;var g=c(4),h=e(g),i=c(37),j=f(i),k=c(6),l=f(k),m=c(5),n=e(m),o=c(38),p=e(o),q=c(44),r=f(q),s=d();s.create=d,r["default"](s),s["default"]=s,b["default"]=s,a.exports=b["default"]},function(a,b){"use strict";b["default"]=function(a){if(a&&a.__esModule)return a;var b={};if(null!=a)for(var c in a)Object.prototype.hasOwnProperty.call(a,c)&&(b[c]=a[c]);return b["default"]=a,b},b.__esModule=!0},function(a,b,c){"use strict";function d(a,b,c){this.helpers=a||{},this.partials=b||{},this.decorators=c||{},i.registerDefaultHelpers(this),j.registerDefaultDecorators(this)}var e=c(1)["default"];b.__esModule=!0,b.HandlebarsEnvironment=d;var f=c(5),g=c(6),h=e(g),i=c(10),j=c(30),k=c(32),l=e(k),m=c(33),n="4.7.6";b.VERSION=n;var o=8;b.COMPILER_REVISION=o;var p=7;b.LAST_COMPATIBLE_COMPILER_REVISION=p;var q={1:"<= 1.0.rc.2",2:"== 1.0.0-rc.3",3:"== 1.0.0-rc.4",4:"== 1.x.x",5:"== 2.0.0-alpha.x",6:">= 2.0.0-beta.1",7:">= 4.0.0 <4.3.0",8:">= 4.3.0"};b.REVISION_CHANGES=q;var r="[object Object]";d.prototype={constructor:d,logger:l["default"],log:l["default"].log,registerHelper:function(a,b){if(f.toString.call(a)===r){if(b)throw new h["default"]("Arg not supported with multiple helpers");f.extend(this.helpers,a)}else this.helpers[a]=b},unregisterHelper:function(a){delete this.helpers[a]},registerPartial:function(a,b){if(f.toString.call(a)===r)f.extend(this.partials,a);else{if("undefined"==typeof b)throw new h["default"]('Attempting to register a partial called "'+a+'" as undefined');this.partials[a]=b}},unregisterPartial:function(a){delete this.partials[a]},registerDecorator:function(a,b){if(f.toString.call(a)===r){if(b)throw new h["default"]("Arg not supported with multiple decorators");f.extend(this.decorators,a)}else this.decorators[a]=b},unregisterDecorator:function(a){delete this.decorators[a]},resetLoggedPropertyAccesses:function(){m.resetLoggedProperties()}};var s=l["default"].log;b.log=s,b.createFrame=f.createFrame,b.logger=l["default"]},function(a,b){"use strict";function c(a){return k[a]}function d(a){for(var b=1;b<arguments.length;b++)for(var c in arguments[b])Object.prototype.hasOwnProperty.call(arguments[b],c)&&(a[c]=arguments[b][c]);return a}function e(a,b){for(var c=0,d=a.length;c<d;c++)if(a[c]===b)return c;return-1}function f(a){if("string"!=typeof a){if(a&&a.toHTML)return a.toHTML();if(null==a)return"";if(!a)return a+"";a=""+a}return m.test(a)?a.replace(l,c):a}function g(a){return!a&&0!==a||!(!p(a)||0!==a.length)}function h(a){var b=d({},a);return b._parent=a,b}function i(a,b){return a.path=b,a}function j(a,b){return(a?a+".":"")+b}b.__esModule=!0,b.extend=d,b.indexOf=e,b.escapeExpression=f,b.isEmpty=g,b.createFrame=h,b.blockParams=i,b.appendContextPath=j;var k={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#x27;","`":"&#x60;","=":"&#x3D;"},l=/[&<>"'`=]/g,m=/[&<>"'`=]/,n=Object.prototype.toString;b.toString=n;var o=function(a){return"function"==typeof a};o(/x/)&&(b.isFunction=o=function(a){return"function"==typeof a&&"[object Function]"===n.call(a)}),b.isFunction=o;var p=Array.isArray||function(a){return!(!a||"object"!=typeof a)&&"[object Array]"===n.call(a)};b.isArray=p},function(a,b,c){"use strict";function d(a,b){var c=b&&b.loc,g=void 0,h=void 0,i=void 0,j=void 0;c&&(g=c.start.line,h=c.end.line,i=c.start.column,j=c.end.column,a+=" - "+g+":"+i);for(var k=Error.prototype.constructor.call(this,a),l=0;l<f.length;l++)this[f[l]]=k[f[l]];Error.captureStackTrace&&Error.captureStackTrace(this,d);try{c&&(this.lineNumber=g,this.endLineNumber=h,e?(Object.defineProperty(this,"column",{value:i,enumerable:!0}),Object.defineProperty(this,"endColumn",{value:j,enumerable:!0})):(this.column=i,this.endColumn=j))}catch(m){}}var e=c(7)["default"];b.__esModule=!0;var f=["description","fileName","lineNumber","endLineNumber","message","name","number","stack"];d.prototype=new Error,b["default"]=d,a.exports=b["default"]},function(a,b,c){a.exports={"default":c(8),__esModule:!0}},function(a,b,c){var d=c(9);a.exports=function(a,b,c){return d.setDesc(a,b,c)}},function(a,b){var c=Object;a.exports={create:c.create,getProto:c.getPrototypeOf,isEnum:{}.propertyIsEnumerable,getDesc:c.getOwnPropertyDescriptor,setDesc:c.defineProperty,setDescs:c.defineProperties,getKeys:c.keys,getNames:c.getOwnPropertyNames,getSymbols:c.getOwnPropertySymbols,each:[].forEach}},function(a,b,c){"use strict";function d(a){h["default"](a),j["default"](a),l["default"](a),n["default"](a),p["default"](a),r["default"](a),t["default"](a)}function e(a,b,c){a.helpers[b]&&(a.hooks[b]=a.helpers[b],c||delete a.helpers[b])}var f=c(1)["default"];b.__esModule=!0,b.registerDefaultHelpers=d,b.moveHelperToHooks=e;var g=c(11),h=f(g),i=c(12),j=f(i),k=c(25),l=f(k),m=c(26),n=f(m),o=c(27),p=f(o),q=c(28),r=f(q),s=c(29),t=f(s)},function(a,b,c){"use strict";b.__esModule=!0;var d=c(5);b["default"]=function(a){a.registerHelper("blockHelperMissing",function(b,c){var e=c.inverse,f=c.fn;if(b===!0)return f(this);if(b===!1||null==b)return e(this);if(d.isArray(b))return b.length>0?(c.ids&&(c.ids=[c.name]),a.helpers.each(b,c)):e(this);if(c.data&&c.ids){var g=d.createFrame(c.data);g.contextPath=d.appendContextPath(c.data.contextPath,c.name),c={data:g}}return f(b,c)})},a.exports=b["default"]},function(a,b,c){(function(d){"use strict";var e=c(13)["default"],f=c(1)["default"];b.__esModule=!0;var g=c(5),h=c(6),i=f(h);b["default"]=function(a){a.registerHelper("each",function(a,b){function c(b,c,d){l&&(l.key=b,l.index=c,l.first=0===c,l.last=!!d,m&&(l.contextPath=m+b)),k+=f(a[b],{data:l,blockParams:g.blockParams([a[b],b],[m+b,null])})}if(!b)throw new i["default"]("Must pass iterator to #each");var f=b.fn,h=b.inverse,j=0,k="",l=void 0,m=void 0;if(b.data&&b.ids&&(m=g.appendContextPath(b.data.contextPath,b.ids[0])+"."),g.isFunction(a)&&(a=a.call(this)),b.data&&(l=g.createFrame(b.data)),a&&"object"==typeof a)if(g.isArray(a))for(var n=a.length;j<n;j++)j in a&&c(j,j,j===a.length-1);else if(d.Symbol&&a[d.Symbol.iterator]){for(var o=[],p=a[d.Symbol.iterator](),q=p.next();!q.done;q=p.next())o.push(q.value);a=o;for(var n=a.length;j<n;j++)c(j,j,j===a.length-1)}else!function(){var b=void 0;e(a).forEach(function(a){void 0!==b&&c(b,j-1),b=a,j++}),void 0!==b&&c(b,j-1,!0)}();return 0===j&&(k=h(this)),k})},a.exports=b["default"]}).call(b,function(){return this}())},function(a,b,c){a.exports={"default":c(14),__esModule:!0}},function(a,b,c){c(15),a.exports=c(21).Object.keys},function(a,b,c){var d=c(16);c(18)("keys",function(a){return function(b){return a(d(b))}})},function(a,b,c){var d=c(17);a.exports=function(a){return Object(d(a))}},function(a,b){a.exports=function(a){if(void 0==a)throw TypeError("Can't call method on  "+a);return a}},function(a,b,c){var d=c(19),e=c(21),f=c(24);a.exports=function(a,b){var c=(e.Object||{})[a]||Object[a],g={};g[a]=b(c),d(d.S+d.F*f(function(){c(1)}),"Object",g)}},function(a,b,c){var d=c(20),e=c(21),f=c(22),g="prototype",h=function(a,b,c){var i,j,k,l=a&h.F,m=a&h.G,n=a&h.S,o=a&h.P,p=a&h.B,q=a&h.W,r=m?e:e[b]||(e[b]={}),s=m?d:n?d[b]:(d[b]||{})[g];m&&(c=b);for(i in c)j=!l&&s&&i in s,j&&i in r||(k=j?s[i]:c[i],r[i]=m&&"function"!=typeof s[i]?c[i]:p&&j?f(k,d):q&&s[i]==k?function(a){var b=function(b){return this instanceof a?new a(b):a(b)};return b[g]=a[g],b}(k):o&&"function"==typeof k?f(Function.call,k):k,o&&((r[g]||(r[g]={}))[i]=k))};h.F=1,h.G=2,h.S=4,h.P=8,h.B=16,h.W=32,a.exports=h},function(a,b){var c=a.exports="undefined"!=typeof window&&window.Math==Math?window:"undefined"!=typeof self&&self.Math==Math?self:Function("return this")();"number"==typeof __g&&(__g=c)},function(a,b){var c=a.exports={version:"1.2.6"};"number"==typeof __e&&(__e=c)},function(a,b,c){var d=c(23);a.exports=function(a,b,c){if(d(a),void 0===b)return a;switch(c){case 1:return function(c){return a.call(b,c)};case 2:return function(c,d){return a.call(b,c,d)};case 3:return function(c,d,e){return a.call(b,c,d,e)}}return function(){return a.apply(b,arguments)}}},function(a,b){a.exports=function(a){if("function"!=typeof a)throw TypeError(a+" is not a function!");return a}},function(a,b){a.exports=function(a){try{return!!a()}catch(b){return!0}}},function(a,b,c){"use strict";var d=c(1)["default"];b.__esModule=!0;var e=c(6),f=d(e);b["default"]=function(a){a.registerHelper("helperMissing",function(){if(1!==arguments.length)throw new f["default"]('Missing helper: "'+arguments[arguments.length-1].name+'"')})},a.exports=b["default"]},function(a,b,c){"use strict";var d=c(1)["default"];b.__esModule=!0;var e=c(5),f=c(6),g=d(f);b["default"]=function(a){a.registerHelper("if",function(a,b){if(2!=arguments.length)throw new g["default"]("#if requires exactly one argument");return e.isFunction(a)&&(a=a.call(this)),!b.hash.includeZero&&!a||e.isEmpty(a)?b.inverse(this):b.fn(this)}),a.registerHelper("unless",function(b,c){if(2!=arguments.length)throw new g["default"]("#unless requires exactly one argument");return a.helpers["if"].call(this,b,{fn:c.inverse,inverse:c.fn,hash:c.hash})})},a.exports=b["default"]},function(a,b){"use strict";b.__esModule=!0,b["default"]=function(a){a.registerHelper("log",function(){for(var b=[void 0],c=arguments[arguments.length-1],d=0;d<arguments.length-1;d++)b.push(arguments[d]);var e=1;null!=c.hash.level?e=c.hash.level:c.data&&null!=c.data.level&&(e=c.data.level),b[0]=e,a.log.apply(a,b)})},a.exports=b["default"]},function(a,b){"use strict";b.__esModule=!0,b["default"]=function(a){a.registerHelper("lookup",function(a,b,c){return a?c.lookupProperty(a,b):a})},a.exports=b["default"]},function(a,b,c){"use strict";var d=c(1)["default"];b.__esModule=!0;var e=c(5),f=c(6),g=d(f);b["default"]=function(a){a.registerHelper("with",function(a,b){if(2!=arguments.length)throw new g["default"]("#with requires exactly one argument");e.isFunction(a)&&(a=a.call(this));var c=b.fn;if(e.isEmpty(a))return b.inverse(this);var d=b.data;return b.data&&b.ids&&(d=e.createFrame(b.data),d.contextPath=e.appendContextPath(b.data.contextPath,b.ids[0])),c(a,{data:d,blockParams:e.blockParams([a],[d&&d.contextPath])})})},a.exports=b["default"]},function(a,b,c){"use strict";function d(a){g["default"](a)}var e=c(1)["default"];b.__esModule=!0,b.registerDefaultDecorators=d;var f=c(31),g=e(f)},function(a,b,c){"use strict";b.__esModule=!0;var d=c(5);b["default"]=function(a){a.registerDecorator("inline",function(a,b,c,e){var f=a;return b.partials||(b.partials={},f=function(e,f){var g=c.partials;c.partials=d.extend({},g,b.partials);var h=a(e,f);return c.partials=g,h}),b.partials[e.args[0]]=e.fn,f})},a.exports=b["default"]},function(a,b,c){"use strict";b.__esModule=!0;var d=c(5),e={methodMap:["debug","info","warn","error"],level:"info",lookupLevel:function(a){if("string"==typeof a){var b=d.indexOf(e.methodMap,a.toLowerCase());a=b>=0?b:parseInt(a,10)}return a},log:function(a){if(a=e.lookupLevel(a),"undefined"!=typeof console&&e.lookupLevel(e.level)<=a){var b=e.methodMap[a];console[b]||(b="log");for(var c=arguments.length,d=Array(c>1?c-1:0),f=1;f<c;f++)d[f-1]=arguments[f];console[b].apply(console,d)}}};b["default"]=e,a.exports=b["default"]},function(a,b,c){"use strict";function d(a){var b=i(null);b.constructor=!1,b.__defineGetter__=!1,b.__defineSetter__=!1,b.__lookupGetter__=!1;var c=i(null);return c.__proto__=!1,{properties:{whitelist:l.createNewLookupObject(c,a.allowedProtoProperties),defaultValue:a.allowProtoPropertiesByDefault},methods:{whitelist:l.createNewLookupObject(b,a.allowedProtoMethods),defaultValue:a.allowProtoMethodsByDefault}}}function e(a,b,c){return"function"==typeof a?f(b.methods,c):f(b.properties,c)}function f(a,b){return void 0!==a.whitelist[b]?a.whitelist[b]===!0:void 0!==a.defaultValue?a.defaultValue:(g(b),!1)}function g(a){o[a]!==!0&&(o[a]=!0,n.log("error",'Handlebars: Access has been denied to resolve the property "'+a+'" because it is not an "own property" of its parent.\nYou can add a runtime option to disable the check or this warning:\nSee https://handlebarsjs.com/api-reference/runtime-options.html#options-to-control-prototype-access for details'))}function h(){j(o).forEach(function(a){delete o[a]})}var i=c(34)["default"],j=c(13)["default"],k=c(3)["default"];b.__esModule=!0,b.createProtoAccessControl=d,b.resultIsAllowed=e,b.resetLoggedProperties=h;var l=c(36),m=c(32),n=k(m),o=i(null)},function(a,b,c){a.exports={"default":c(35),__esModule:!0}},function(a,b,c){var d=c(9);a.exports=function(a,b){return d.create(a,b)}},function(a,b,c){"use strict";function d(){for(var a=arguments.length,b=Array(a),c=0;c<a;c++)b[c]=arguments[c];return f.extend.apply(void 0,[e(null)].concat(b))}var e=c(34)["default"];b.__esModule=!0,b.createNewLookupObject=d;var f=c(5)},function(a,b){"use strict";function c(a){this.string=a}b.__esModule=!0,c.prototype.toString=c.prototype.toHTML=function(){return""+this.string},b["default"]=c,a.exports=b["default"]},function(a,b,c){"use strict";function d(a){var b=a&&a[0]||1,c=v.COMPILER_REVISION;if(!(b>=v.LAST_COMPATIBLE_COMPILER_REVISION&&b<=v.COMPILER_REVISION)){if(b<v.LAST_COMPATIBLE_COMPILER_REVISION){var d=v.REVISION_CHANGES[c],e=v.REVISION_CHANGES[b];throw new u["default"]("Template was precompiled with an older version of Handlebars than the current runtime. Please update your precompiler to a newer version ("+d+") or downgrade your runtime to an older version ("+e+").")}throw new u["default"]("Template was precompiled with a newer version of Handlebars than the current runtime. Please update your runtime to a newer version ("+a[1]+").")}}function e(a,b){function c(c,d,e){e.hash&&(d=s.extend({},d,e.hash),e.ids&&(e.ids[0]=!0)),c=b.VM.resolvePartial.call(this,c,d,e);var f=s.extend({},e,{hooks:this.hooks,protoAccessControl:this.protoAccessControl}),g=b.VM.invokePartial.call(this,c,d,f);if(null==g&&b.compile&&(e.partials[e.name]=b.compile(c,a.compilerOptions,b),g=e.partials[e.name](d,f)),null!=g){if(e.indent){for(var h=g.split("\n"),i=0,j=h.length;i<j&&(h[i]||i+1!==j);i++)h[i]=e.indent+h[i];g=h.join("\n")}return g}throw new u["default"]("The partial "+e.name+" could not be compiled when running in runtime-only mode")}function d(b){function c(b){return""+a.main(g,b,g.helpers,g.partials,f,i,h)}var e=arguments.length<=1||void 0===arguments[1]?{}:arguments[1],f=e.data;d._setup(e),!e.partial&&a.useData&&(f=j(b,f));var h=void 0,i=a.useBlockParams?[]:void 0;return a.useDepths&&(h=e.depths?b!=e.depths[0]?[b].concat(e.depths):e.depths:[b]),(c=k(a.main,c,g,e.depths||[],f,i))(b,e)}if(!b)throw new u["default"]("No environment passed to template");if(!a||!a.main)throw new u["default"]("Unknown template object: "+typeof a);a.main.decorator=a.main_d,b.VM.checkRevision(a.compiler);var e=a.compiler&&7===a.compiler[0],g={strict:function(a,b,c){if(!(a&&b in a))throw new u["default"]('"'+b+'" not defined in '+a,{loc:c});return a[b]},lookupProperty:function(a,b){var c=a[b];return null==c?c:Object.prototype.hasOwnProperty.call(a,b)?c:y.resultIsAllowed(c,g.protoAccessControl,b)?c:void 0},lookup:function(a,b){for(var c=a.length,d=0;d<c;d++){var e=a[d]&&g.lookupProperty(a[d],b);if(null!=e)return a[d][b]}},lambda:function(a,b){return"function"==typeof a?a.call(b):a},escapeExpression:s.escapeExpression,invokePartial:c,fn:function(b){var c=a[b];return c.decorator=a[b+"_d"],c},programs:[],program:function(a,b,c,d,e){var g=this.programs[a],h=this.fn(a);return b||e||d||c?g=f(this,a,h,b,c,d,e):g||(g=this.programs[a]=f(this,a,h)),g},data:function(a,b){for(;a&&b--;)a=a._parent;return a},mergeIfNeeded:function(a,b){var c=a||b;return a&&b&&a!==b&&(c=s.extend({},b,a)),c},nullContext:n({}),noop:b.VM.noop,compilerInfo:a.compiler};return d.isTop=!0,d._setup=function(c){if(c.partial)g.protoAccessControl=c.protoAccessControl,g.helpers=c.helpers,g.partials=c.partials,g.decorators=c.decorators,g.hooks=c.hooks;else{var d=s.extend({},b.helpers,c.helpers);l(d,g),g.helpers=d,a.usePartial&&(g.partials=g.mergeIfNeeded(c.partials,b.partials)),(a.usePartial||a.useDecorators)&&(g.decorators=s.extend({},b.decorators,c.decorators)),g.hooks={},g.protoAccessControl=y.createProtoAccessControl(c);var f=c.allowCallsToHelperMissing||e;w.moveHelperToHooks(g,"helperMissing",f),w.moveHelperToHooks(g,"blockHelperMissing",f)}},d._child=function(b,c,d,e){if(a.useBlockParams&&!d)throw new u["default"]("must pass block params");if(a.useDepths&&!e)throw new u["default"]("must pass parent depths");return f(g,b,a[b],c,0,d,e)},d}function f(a,b,c,d,e,f,g){function h(b){var e=arguments.length<=1||void 0===arguments[1]?{}:arguments[1],h=g;return!g||b==g[0]||b===a.nullContext&&null===g[0]||(h=[b].concat(g)),c(a,b,a.helpers,a.partials,e.data||d,f&&[e.blockParams].concat(f),h)}return h=k(c,h,a,g,d,f),h.program=b,h.depth=g?g.length:0,h.blockParams=e||0,h}function g(a,b,c){return a?a.call||c.name||(c.name=a,a=c.partials[a]):a="@partial-block"===c.name?c.data["partial-block"]:c.partials[c.name],a}function h(a,b,c){var d=c.data&&c.data["partial-block"];c.partial=!0,c.ids&&(c.data.contextPath=c.ids[0]||c.data.contextPath);var e=void 0;if(c.fn&&c.fn!==i&&!function(){c.data=v.createFrame(c.data);var a=c.fn;e=c.data["partial-block"]=function(b){var c=arguments.length<=1||void 0===arguments[1]?{}:arguments[1];return c.data=v.createFrame(c.data),c.data["partial-block"]=d,a(b,c)},a.partials&&(c.partials=s.extend({},c.partials,a.partials))}(),void 0===a&&e&&(a=e),void 0===a)throw new u["default"]("The partial "+c.name+" could not be found");if(a instanceof Function)return a(b,c)}function i(){return""}function j(a,b){return b&&"root"in b||(b=b?v.createFrame(b):{},b.root=a),b}function k(a,b,c,d,e,f){if(a.decorator){var g={};b=a.decorator(b,g,c,d&&d[0],e,f,d),s.extend(b,g)}return b}function l(a,b){o(a).forEach(function(c){var d=a[c];a[c]=m(d,b)})}function m(a,b){var c=b.lookupProperty;return x.wrapHelper(a,function(a){return s.extend({lookupProperty:c},a)})}var n=c(39)["default"],o=c(13)["default"],p=c(3)["default"],q=c(1)["default"];b.__esModule=!0,b.checkRevision=d,b.template=e,b.wrapProgram=f,b.resolvePartial=g,b.invokePartial=h,b.noop=i;var r=c(5),s=p(r),t=c(6),u=q(t),v=c(4),w=c(10),x=c(43),y=c(33)},function(a,b,c){a.exports={"default":c(40),__esModule:!0}},function(a,b,c){c(41),a.exports=c(21).Object.seal},function(a,b,c){var d=c(42);c(18)("seal",function(a){return function(b){return a&&d(b)?a(b):b}})},function(a,b){a.exports=function(a){return"object"==typeof a?null!==a:"function"==typeof a}},function(a,b){"use strict";function c(a,b){if("function"!=typeof a)return a;var c=function(){var c=arguments[arguments.length-1];return arguments[arguments.length-1]=b(c),a.apply(this,arguments)};return c}
42b.__esModule=!0,b.wrapHelper=c},function(a,b){(function(c){"use strict";b.__esModule=!0,b["default"]=function(a){var b="undefined"!=typeof c?c:window,d=b.Handlebars;a.noConflict=function(){return b.Handlebars===a&&(b.Handlebars=d),a}},a.exports=b["default"]}).call(b,function(){return this}())},function(a,b){"use strict";b.__esModule=!0;var c={helpers:{helperExpression:function(a){return"SubExpression"===a.type||("MustacheStatement"===a.type||"BlockStatement"===a.type)&&!!(a.params&&a.params.length||a.hash)},scopedId:function(a){return/^\.|this\b/.test(a.original)},simpleId:function(a){return 1===a.parts.length&&!c.helpers.scopedId(a)&&!a.depth}}};b["default"]=c,a.exports=b["default"]},function(a,b,c){"use strict";function d(a,b){if("Program"===a.type)return a;i["default"].yy=o,o.locInfo=function(a){return new o.SourceLocation(b&&b.srcName,a)};var c=i["default"].parse(a);return c}function e(a,b){var c=d(a,b),e=new k["default"](b);return e.accept(c)}var f=c(1)["default"],g=c(3)["default"];b.__esModule=!0,b.parseWithoutProcessing=d,b.parse=e;var h=c(47),i=f(h),j=c(48),k=f(j),l=c(50),m=g(l),n=c(5);b.parser=i["default"];var o={};n.extend(o,m)},function(a,b){"use strict";b.__esModule=!0
vendor: 10,940 bytes, line 42
42;var c=function(){function a(){this.yy={}}var b={trace:function(){},yy:{},symbols_:{error:2,root:3,program:4,EOF:5,program_repetition0:6,statement:7,mustache:8,block:9,rawBlock:10,partial:11,partialBlock:12,content:13,COMMENT:14,CONTENT:15,openRawBlock:16,rawBlock_repetition0:17,END_RAW_BLOCK:18,OPEN_RAW_BLOCK:19,helperName:20,openRawBlock_repetition0:21,openRawBlock_option0:22,CLOSE_RAW_BLOCK:23,openBlock:24,block_option0:25,closeBlock:26,openInverse:27,block_option1:28,OPEN_BLOCK:29,openBlock_repetition0:30,openBlock_option0:31,openBlock_option1:32,CLOSE:33,OPEN_INVERSE:34,openInverse_repetition0:35,openInverse_option0:36,openInverse_option1:37,openInverseChain:38,OPEN_INVERSE_CHAIN:39,openInverseChain_repetition0:40,openInverseChain_option0:41,openInverseChain_option1:42,inverseAndProgram:43,INVERSE:44,inverseChain:45,inverseChain_option0:46,OPEN_ENDBLOCK:47,OPEN:48,mustache_repetition0:49,mustache_option0:50,OPEN_UNESCAPED:51,mustache_repetition1:52,mustache_option1:53,CLOSE_UNESCAPED:54,OPEN_PARTIAL:55,partialName:56,partial_repetition0:57,partial_option0:58,openPartialBlock:59,OPEN_PARTIAL_BLOCK:60,openPartialBlock_repetition0:61,openPartialBlock_option0:62,param:63,sexpr:64,OPEN_SEXPR:65,sexpr_repetition0:66,sexpr_option0:67,CLOSE_SEXPR:68,hash:69,hash_repetition_plus0:70,hashSegment:71,ID:72,EQUALS:73,blockParams:74,OPEN_BLOCK_PARAMS:75,blockParams_repetition_plus0:76,CLOSE_BLOCK_PARAMS:77,path:78,dataName:79,STRING:80,NUMBER:81,BOOLEAN:82,UNDEFINED:83,NULL:84,DATA:85,pathSegments:86,SEP:87,$accept:0,$end:1},terminals_:{2:"error",5:"EOF",14:"COMMENT",15:"CONTENT",18:"END_RAW_BLOCK",19:"OPEN_RAW_BLOCK",23:"CLOSE_RAW_BLOCK",29:"OPEN_BLOCK",33:"CLOSE",34:"OPEN_INVERSE",39:"OPEN_INVERSE_CHAIN",44:"INVERSE",47:"OPEN_ENDBLOCK",48:"OPEN",51:"OPEN_UNESCAPED",54:"CLOSE_UNESCAPED",55:"OPEN_PARTIAL",60:"OPEN_PARTIAL_BLOCK",65:"OPEN_SEXPR",68:"CLOSE_SEXPR",72:"ID",73:"EQUALS",75:"OPEN_BLOCK_PARAMS",77:"CLOSE_BLOCK_PARAMS",80:"STRING",81:"NUMBER",82:"BOOLEAN",83:"UNDEFINED",84:"NULL",85:"DATA",87:"SEP"},productions_:[0,[3,2],[4,1],[7,1],[7,1],[7,1],[7,1],[7,1],[7,1],[7,1],[13,1],[10,3],[16,5],[9,4],[9,4],[24,6],[27,6],[38,6],[43,2],[45,3],[45,1],[26,3],[8,5],[8,5],[11,5],[12,3],[59,5],[63,1],[63,1],[64,5],[69,1],[71,3],[74,3],[20,1],[20,1],[20,1],[20,1],[20,1],[20,1],[20,1],[56,1],[56,1],[79,2],[78,1],[86,3],[86,1],[6,0],[6,2],[17,0],[17,2],[21,0],[21,2],[22,0],[22,1],[25,0],[25,1],[28,0],[28,1],[30,0],[30,2],[31,0],[31,1],[32,0],[32,1],[35,0],[35,2],[36,0],[36,1],[37,0],[37,1],[40,0],[40,2],[41,0],[41,1],[42,0],[42,1],[46,0],[46,1],[49,0],[49,2],[50,0],[50,1],[52,0],[52,2],[53,0],[53,1],[57,0],[57,2],[58,0],[58,1],[61,0],[61,2],[62,0],[62,1],[66,0],[66,2],[67,0],[67,1],[70,1],[70,2],[76,1],[76,2]],performAction:function(a,b,c,d,e,f,g){var h=f.length-1;switch(e){case 1:return f[h-1];case 2:this.$=d.prepareProgram(f[h]);break;case 3:this.$=f[h];break;case 4:this.$=f[h];break;case 5:this.$=f[h];break;case 6:this.$=f[h];break;case 7:this.$=f[h];break;case 8:this.$=f[h];break;case 9:this.$={type:"CommentStatement",value:d.stripComment(f[h]),strip:d.stripFlags(f[h],f[h]),loc:d.locInfo(this._$)};break;case 10:this.$={type:"ContentStatement",original:f[h],value:f[h],loc:d.locInfo(this._$)};break;case 11:this.$=d.prepareRawBlock(f[h-2],f[h-1],f[h],this._$);break;case 12:this.$={path:f[h-3],params:f[h-2],hash:f[h-1]};break;case 13:this.$=d.prepareBlock(f[h-3],f[h-2],f[h-1],f[h],!1,this._$);break;case 14:this.$=d.prepareBlock(f[h-3],f[h-2],f[h-1],f[h],!0,this._$);break;case 15:this.$={open:f[h-5],path:f[h-4],params:f[h-3],hash:f[h-2],blockParams:f[h-1],strip:d.stripFlags(f[h-5],f[h])};break;case 16:this.$={path:f[h-4],params:f[h-3],hash:f[h-2],blockParams:f[h-1],strip:d.stripFlags(f[h-5],f[h])};break;case 17:this.$={path:f[h-4],params:f[h-3],hash:f[h-2],blockParams:f[h-1],strip:d.stripFlags(f[h-5],f[h])};break;case 18:this.$={strip:d.stripFlags(f[h-1],f[h-1]),program:f[h]};break;case 19:var i=d.prepareBlock(f[h-2],f[h-1],f[h],f[h],!1,this._$),j=d.prepareProgram([i],f[h-1].loc);j.chained=!0,this.$={strip:f[h-2].strip,program:j,chain:!0};break;case 20:this.$=f[h];break;case 21:this.$={path:f[h-1],strip:d.stripFlags(f[h-2],f[h])};break;case 22:this.$=d.prepareMustache(f[h-3],f[h-2],f[h-1],f[h-4],d.stripFlags(f[h-4],f[h]),this._$);break;case 23:this.$=d.prepareMustache(f[h-3],f[h-2],f[h-1],f[h-4],d.stripFlags(f[h-4],f[h]),this._$);break;case 24:this.$={type:"PartialStatement",name:f[h-3],params:f[h-2],hash:f[h-1],indent:"",strip:d.stripFlags(f[h-4],f[h]),loc:d.locInfo(this._$)};break;case 25:this.$=d.preparePartialBlock(f[h-2],f[h-1],f[h],this._$);break;case 26:this.$={path:f[h-3],params:f[h-2],hash:f[h-1],strip:d.stripFlags(f[h-4],f[h])};break;case 27:this.$=f[h];break;case 28:this.$=f[h];break;case 29:this.$={type:"SubExpression",path:f[h-3],params:f[h-2],hash:f[h-1],loc:d.locInfo(this._$)};break;case 30:this.$={type:"Hash",pairs:f[h],loc:d.locInfo(this._$)};break;case 31:this.$={type:"HashPair",key:d.id(f[h-2]),value:f[h],loc:d.locInfo(this._$)};break;case 32:this.$=d.id(f[h-1]);break;case 33:this.$=f[h];break;case 34:this.$=f[h];break;case 35:this.$={type:"StringLiteral",value:f[h],original:f[h],loc:d.locInfo(this._$)};break;case 36:this.$={type:"NumberLiteral",value:Number(f[h]),original:Number(f[h]),loc:d.locInfo(this._$)};break;case 37:this.$={type:"BooleanLiteral",value:"true"===f[h],original:"true"===f[h],loc:d.locInfo(this._$)};break;case 38:this.$={type:"UndefinedLiteral",original:void 0,value:void 0,loc:d.locInfo(this._$)};break;case 39:this.$={type:"NullLiteral",original:null,value:null,loc:d.locInfo(this._$)};break;case 40:this.$=f[h];break;case 41:this.$=f[h];break;case 42:this.$=d.preparePath(!0,f[h],this._$);break;case 43:this.$=d.preparePath(!1,f[h],this._$);break;case 44:f[h-2].push({part:d.id(f[h]),original:f[h],separator:f[h-1]}),this.$=f[h-2];break;case 45:this.$=[{part:d.id(f[h]),original:f[h]}];break;case 46:this.$=[];break;case 47:f[h-1].push(f[h]);break;case 48:this.$=[];break;case 49:f[h-1].push(f[h]);break;case 50:this.$=[];break;case 51:f[h-1].push(f[h]);break;case 58:this.$=[];break;case 59:f[h-1].push(f[h]);break;case 64:this.$=[];break;case 65:f[h-1].push(f[h]);break;case 70:this.$=[];break;case 71:f[h-1].push(f[h]);break;case 78:this.$=[];break;case 79:f[h-1].push(f[h]);break;case 82:this.$=[];break;case 83:f[h-1].push(f[h]);break;case 86:this.$=[];break;case 87:f[h-1].push(f[h]);break;case 90:this.$=[];break;case 91:f[h-1].push(f[h]);break;case 94:this.$=[];break;case 95:f[h-1].push(f[h]);break;case 98:this.$=[f[h]];break;case 99:f[h-1].push(f[h]);break;case 100:this.$=[f[h]];break;case 101:f[h-1].push(f[h])}},table:[{3:1,4:2,5:[2,46],6:3,14:[2,46],15:[2,46],19:[2,46],29:[2,46],34:[2,46],48:[2,46],51:[2,46],55:[2,46],60:[2,46]},{1:[3]},{5:[1,4]},{5:[2,2],7:5,8:6,9:7,10:8,11:9,12:10,13:11,14:[1,12],15:[1,20],16:17,19:[1,23],24:15,27:16,29:[1,21],34:[1,22],39:[2,2],44:[2,2],47:[2,2],48:[1,13],51:[1,14],55:[1,18],59:19,60:[1,24]},{1:[2,1]},{5:[2,47],14:[2,47],15:[2,47],19:[2,47],29:[2,47],34:[2,47],39:[2,47],44:[2,47],47:[2,47],48:[2,47],51:[2,47],55:[2,47],60:[2,47]},{5:[2,3],14:[2,3],15:[2,3],19:[2,3],29:[2,3],34:[2,3],39:[2,3],44:[2,3],47:[2,3],48:[2,3],51:[2,3],55:[2,3],60:[2,3]},{5:[2,4],14:[2,4],15:[2,4],19:[2,4],29:[2,4],34:[2,4],39:[2,4],44:[2,4],47:[2,4],48:[2,4],51:[2,4],55:[2,4],60:[2,4]},{5:[2,5],14:[2,5],15:[2,5],19:[2,5],29:[2,5],34:[2,5],39:[2,5],44:[2,5],47:[2,5],48:[2,5],51:[2,5],55:[2,5],60:[2,5]},{5:[2,6],14:[2,6],15:[2,6],19:[2,6],29:[2,6],34:[2,6],39:[2,6],44:[2,6],47:[2,6],48:[2,6],51:[2,6],55:[2,6],60:[2,6]},{5:[2,7],14:[2,7],15:[2,7],19:[2,7],29:[2,7],34:[2,7],39:[2,7],44:[2,7],47:[2,7],48:[2,7],51:[2,7],55:[2,7],60:[2,7]},{5:[2,8],14:[2,8],15:[2,8],19:[2,8],29:[2,8],34:[2,8],39:[2,8],44:[2,8],47:[2,8],48:[2,8],51:[2,8],55:[2,8],60:[2,8]},{5:[2,9],14:[2,9],15:[2,9],19:[2,9],29:[2,9],34:[2,9],39:[2,9],44:[2,9],47:[2,9],48:[2,9],51:[2,9],55:[2,9],60:[2,9]},{20:25,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:36,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{4:37,6:3,14:[2,46],15:[2,46],19:[2,46],29:[2,46],34:[2,46],39:[2,46],44:[2,46],47:[2,46],48:[2,46],51:[2,46],55:[2,46],60:[2,46]},{4:38,6:3,14:[2,46],15:[2,46],19:[2,46],29:[2,46],34:[2,46],44:[2,46],47:[2,46],48:[2,46],51:[2,46],55:[2,46],60:[2,46]},{15:[2,48],17:39,18:[2,48]},{20:41,56:40,64:42,65:[1,43],72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{4:44,6:3,14:[2,46],15:[2,46],19:[2,46],29:[2,46],34:[2,46],47:[2,46],48:[2,46],51:[2,46],55:[2,46],60:[2,46]},{5:[2,10],14:[2,10],15:[2,10],18:[2,10],19:[2,10],29:[2,10],34:[2,10],39:[2,10],44:[2,10],47:[2,10],48:[2,10],51:[2,10],55:[2,10],60:[2,10]},{20:45,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:46,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:47,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:41,56:48,64:42,65:[1,43],72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{33:[2,78],49:49,65:[2,78],72:[2,78],80:[2,78],81:[2,78],82:[2,78],83:[2,78],84:[2,78],85:[2,78]},{23:[2,33],33:[2,33],54:[2,33],65:[2,33],68:[2,33],72:[2,33],75:[2,33],80:[2,33],81:[2,33],82:[2,33],83:[2,33],84:[2,33],85:[2,33]},{23:[2,34],33:[2,34],54:[2,34],65:[2,34],68:[2,34],72:[2,34],75:[2,34],80:[2,34],81:[2,34],82:[2,34],83:[2,34],84:[2,34],85:[2,34]},{23:[2,35],33:[2,35],54:[2,35],65:[2,35],68:[2,35],72:[2,35],75:[2,35],80:[2,35],81:[2,35],82:[2,35],83:[2,35],84:[2,35],85:[2,35]},{23:[2,36],33:[2,36],54:[2,36],65:[2,36],68:[2,36],72:[2,36],75:[2,36],80:[2,36],81:[2,36],82:[2,36],83:[2,36],84:[2,36],85:[2,36]},{23:[2,37],33:[2,37],54:[2,37],65:[2,37],68:[2,37],72:[2,37],75:[2,37],80:[2,37],81:[2,37],82:[2,37],83:[2,37],84:[2,37],85:[2,37]},{23:[2,38],33:[2,38],54:[2,38],65:[2,38],68:[2,38],72:[2,38],75:[2,38],80:[2,38],81:[2,38],82:[2,38],83:[2,38],84:[2,38],85:[2,38]},{23:[2,39],33:[2,39],54:[2,39],65:[2,39],68:[2,39],72:[2,39],75:[2,39],80:[2,39],81:[2,39],82:[2,39],83:[2,39],84:[2,39],85:[2,39]},{23:[2,43],33:[2,43],54:[2,43],65:[2,43],68:[2,43],72:[2,43],75:[2,43],80:[2,43],81:[2,43],82:[2,43],83:[2,43],84:[2,43],85:[2,43],87:[1,50]},{72:[1,35],86:51},{23:[2,45],33:[2,45],54:[2,45],65:[2,45],68:[2,45],72:[2,45],75:[2,45],80:[2,45],81:[2,45],82:[2,45],83:[2,45],84:[2,45],85:[2,45],87:[2,45]},{52:52,54:[2,82],65:[2,82],72:[2,82],80:[2,82],81:[2,82],82:[2,82],83:[2,82],84:[2,82],85:[2,82]},{25:53,38:55,39:[1,57],43:56,44:[1,58],45:54,47:[2,54]},{28:59,43:60,44:[1,58],47:[2,56]},{13:62,15:[1,20],18:[1,61]},{33:[2,86],57:63,65:[2,86],72:[2,86],80:[2,86],81:[2,86],82:[2,86],83:[2,86],84:[2,86],85:[2,86]},{33:[2,40],65:[2,40],72:[2,40],80:[2,40],81:[2,40],82:[2,40],83:[2,40],84:[2,40],85:[2,40]},{33:[2,41],65:[2,41],
42
vendor: 16,566 bytes, line 43
4372:[2,41],80:[2,41],81:[2,41],82:[2,41],83:[2,41],84:[2,41],85:[2,41]},{20:64,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{26:65,47:[1,66]},{30:67,33:[2,58],65:[2,58],72:[2,58],75:[2,58],80:[2,58],81:[2,58],82:[2,58],83:[2,58],84:[2,58],85:[2,58]},{33:[2,64],35:68,65:[2,64],72:[2,64],75:[2,64],80:[2,64],81:[2,64],82:[2,64],83:[2,64],84:[2,64],85:[2,64]},{21:69,23:[2,50],65:[2,50],72:[2,50],80:[2,50],81:[2,50],82:[2,50],83:[2,50],84:[2,50],85:[2,50]},{33:[2,90],61:70,65:[2,90],72:[2,90],80:[2,90],81:[2,90],82:[2,90],83:[2,90],84:[2,90],85:[2,90]},{20:74,33:[2,80],50:71,63:72,64:75,65:[1,43],69:73,70:76,71:77,72:[1,78],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{72:[1,79]},{23:[2,42],33:[2,42],54:[2,42],65:[2,42],68:[2,42],72:[2,42],75:[2,42],80:[2,42],81:[2,42],82:[2,42],83:[2,42],84:[2,42],85:[2,42],87:[1,50]},{20:74,53:80,54:[2,84],63:81,64:75,65:[1,43],69:82,70:76,71:77,72:[1,78],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{26:83,47:[1,66]},{47:[2,55]},{4:84,6:3,14:[2,46],15:[2,46],19:[2,46],29:[2,46],34:[2,46],39:[2,46],44:[2,46],47:[2,46],48:[2,46],51:[2,46],55:[2,46],60:[2,46]},{47:[2,20]},{20:85,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{4:86,6:3,14:[2,46],15:[2,46],19:[2,46],29:[2,46],34:[2,46],47:[2,46],48:[2,46],51:[2,46],55:[2,46],60:[2,46]},{26:87,47:[1,66]},{47:[2,57]},{5:[2,11],14:[2,11],15:[2,11],19:[2,11],29:[2,11],34:[2,11],39:[2,11],44:[2,11],47:[2,11],48:[2,11],51:[2,11],55:[2,11],60:[2,11]},{15:[2,49],18:[2,49]},{20:74,33:[2,88],58:88,63:89,64:75,65:[1,43],69:90,70:76,71:77,72:[1,78],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{65:[2,94],66:91,68:[2,94],72:[2,94],80:[2,94],81:[2,94],82:[2,94],83:[2,94],84:[2,94],85:[2,94]},{5:[2,25],14:[2,25],15:[2,25],19:[2,25],29:[2,25],34:[2,25],39:[2,25],44:[2,25],47:[2,25],48:[2,25],51:[2,25],55:[2,25],60:[2,25]},{20:92,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:74,31:93,33:[2,60],63:94,64:75,65:[1,43],69:95,70:76,71:77,72:[1,78],75:[2,60],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:74,33:[2,66],36:96,63:97,64:75,65:[1,43],69:98,70:76,71:77,72:[1,78],75:[2,66],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:74,22:99,23:[2,52],63:100,64:75,65:[1,43],69:101,70:76,71:77,72:[1,78],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:74,33:[2,92],62:102,63:103,64:75,65:[1,43],69:104,70:76,71:77,72:[1,78],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{33:[1,105]},{33:[2,79],65:[2,79],72:[2,79],80:[2,79],81:[2,79],82:[2,79],83:[2,79],84:[2,79],85:[2,79]},{33:[2,81]},{23:[2,27],33:[2,27],54:[2,27],65:[2,27],68:[2,27],72:[2,27],75:[2,27],80:[2,27],81:[2,27],82:[2,27],83:[2,27],84:[2,27],85:[2,27]},{23:[2,28],33:[2,28],54:[2,28],65:[2,28],68:[2,28],72:[2,28],75:[2,28],80:[2,28],81:[2,28],82:[2,28],83:[2,28],84:[2,28],85:[2,28]},{23:[2,30],33:[2,30],54:[2,30],68:[2,30],71:106,72:[1,107],75:[2,30]},{23:[2,98],33:[2,98],54:[2,98],68:[2,98],72:[2,98],75:[2,98]},{23:[2,45],33:[2,45],54:[2,45],65:[2,45],68:[2,45],72:[2,45],73:[1,108],75:[2,45],80:[2,45],81:[2,45],82:[2,45],83:[2,45],84:[2,45],85:[2,45],87:[2,45]},{23:[2,44],33:[2,44],54:[2,44],65:[2,44],68:[2,44],72:[2,44],75:[2,44],80:[2,44],81:[2,44],82:[2,44],83:[2,44],84:[2,44],85:[2,44],87:[2,44]},{54:[1,109]},{54:[2,83],65:[2,83],72:[2,83],80:[2,83],81:[2,83],82:[2,83],83:[2,83],84:[2,83],85:[2,83]},{54:[2,85]},{5:[2,13],14:[2,13],15:[2,13],19:[2,13],29:[2,13],34:[2,13],39:[2,13],44:[2,13],47:[2,13],48:[2,13],51:[2,13],55:[2,13],60:[2,13]},{38:55,39:[1,57],43:56,44:[1,58],45:111,46:110,47:[2,76]},{33:[2,70],40:112,65:[2,70],72:[2,70],75:[2,70],80:[2,70],81:[2,70],82:[2,70],83:[2,70],84:[2,70],85:[2,70]},{47:[2,18]},{5:[2,14],14:[2,14],15:[2,14],19:[2,14],29:[2,14],34:[2,14],39:[2,14],44:[2,14],47:[2,14],48:[2,14],51:[2,14],55:[2,14],60:[2,14]},{33:[1,113]},{33:[2,87],65:[2,87],72:[2,87],80:[2,87],81:[2,87],82:[2,87],83:[2,87],84:[2,87],85:[2,87]},{33:[2,89]},{20:74,63:115,64:75,65:[1,43],67:114,68:[2,96],69:116,70:76,71:77,72:[1,78],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{33:[1,117]},{32:118,33:[2,62],74:119,75:[1,120]},{33:[2,59],65:[2,59],72:[2,59],75:[2,59],80:[2,59],81:[2,59],82:[2,59],83:[2,59],84:[2,59],85:[2,59]},{33:[2,61],75:[2,61]},{33:[2,68],37:121,74:122,75:[1,120]},{33:[2,65],65:[2,65],72:[2,65],75:[2,65],80:[2,65],81:[2,65],82:[2,65],83:[2,65],84:[2,65],85:[2,65]},{33:[2,67],75:[2,67]},{23:[1,123]},{23:[2,51],65:[2,51],72:[2,51],80:[2,51],81:[2,51],82:[2,51],83:[2,51],84:[2,51],85:[2,51]},{23:[2,53]},{33:[1,124]},{33:[2,91],65:[2,91],72:[2,91],80:[2,91],81:[2,91],82:[2,91],83:[2,91],84:[2,91],85:[2,91]},{33:[2,93]},{5:[2,22],14:[2,22],15:[2,22],19:[2,22],29:[2,22],34:[2,22],39:[2,22],44:[2,22],47:[2,22],48:[2,22],51:[2,22],55:[2,22],60:[2,22]},{23:[2,99],33:[2,99],54:[2,99],68:[2,99],72:[2,99],75:[2,99]},{73:[1,108]},{20:74,63:125,64:75,65:[1,43],72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{5:[2,23],14:[2,23],15:[2,23],19:[2,23],29:[2,23],34:[2,23],39:[2,23],44:[2,23],47:[2,23],48:[2,23],51:[2,23],55:[2,23],60:[2,23]},{47:[2,19]},{47:[2,77]},{20:74,33:[2,72],41:126,63:127,64:75,65:[1,43],69:128,70:76,71:77,72:[1,78],75:[2,72],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{5:[2,24],14:[2,24],15:[2,24],19:[2,24],29:[2,24],34:[2,24],39:[2,24],44:[2,24],47:[2,24],48:[2,24],51:[2,24],55:[2,24],60:[2,24]},{68:[1,129]},{65:[2,95],68:[2,95],72:[2,95],80:[2,95],81:[2,95],82:[2,95],83:[2,95],84:[2,95],85:[2,95]},{68:[2,97]},{5:[2,21],14:[2,21],15:[2,21],19:[2,21],29:[2,21],34:[2,21],39:[2,21],44:[2,21],47:[2,21],48:[2,21],51:[2,21],55:[2,21],60:[2,21]},{33:[1,130]},{33:[2,63]},{72:[1,132],76:131},{33:[1,133]},{33:[2,69]},{15:[2,12],18:[2,12]},{14:[2,26],15:[2,26],19:[2,26],29:[2,26],34:[2,26],47:[2,26],48:[2,26],51:[2,26],55:[2,26],60:[2,26]},{23:[2,31],33:[2,31],54:[2,31],68:[2,31],72:[2,31],75:[2,31]},{33:[2,74],42:134,74:135,75:[1,120]},{33:[2,71],65:[2,71],72:[2,71],75:[2,71],80:[2,71],81:[2,71],82:[2,71],83:[2,71],84:[2,71],85:[2,71]},{33:[2,73],75:[2,73]},{23:[2,29],33:[2,29],54:[2,29],65:[2,29],68:[2,29],72:[2,29],75:[2,29],80:[2,29],81:[2,29],82:[2,29],83:[2,29],84:[2,29],85:[2,29]},{14:[2,15],15:[2,15],19:[2,15],29:[2,15],34:[2,15],39:[2,15],44:[2,15],47:[2,15],48:[2,15],51:[2,15],55:[2,15],60:[2,15]},{72:[1,137],77:[1,136]},{72:[2,100],77:[2,100]},{14:[2,16],15:[2,16],19:[2,16],29:[2,16],34:[2,16],44:[2,16],47:[2,16],48:[2,16],51:[2,16],55:[2,16],60:[2,16]},{33:[1,138]},{33:[2,75]},{33:[2,32]},{72:[2,101],77:[2,101]},{14:[2,17],15:[2,17],19:[2,17],29:[2,17],34:[2,17],39:[2,17],44:[2,17],47:[2,17],48:[2,17],51:[2,17],55:[2,17],60:[2,17]}],defaultActions:{4:[2,1],54:[2,55],56:[2,20],60:[2,57],73:[2,81],82:[2,85],86:[2,18],90:[2,89],101:[2,53],104:[2,93],110:[2,19],111:[2,77],116:[2,97],119:[2,63],122:[2,69],135:[2,75],136:[2,32]},parseError:function(a,b){throw new Error(a)},parse:function(a){function b(){var a;return a=c.lexer.lex()||1,"number"!=typeof a&&(a=c.symbols_[a]||a),a}var c=this,d=[0],e=[null],f=[],g=this.table,h="",i=0,j=0,k=0;this.lexer.setInput(a),this.lexer.yy=this.yy,this.yy.lexer=this.lexer,this.yy.parser=this,"undefined"==typeof this.lexer.yylloc&&(this.lexer.yylloc={});var l=this.lexer.yylloc;f.push(l);var m=this.lexer.options&&this.lexer.options.ranges;"function"==typeof this.yy.parseError&&(this.parseError=this.yy.parseError);for(var n,o,p,q,r,s,t,u,v,w={};;){if(p=d[d.length-1],this.defaultActions[p]?q=this.defaultActions[p]:(null!==n&&"undefined"!=typeof n||(n=b()),q=g[p]&&g[p][n]),"undefined"==typeof q||!q.length||!q[0]){var x="";if(!k){v=[];for(s in g[p])this.terminals_[s]&&s>2&&v.push("'"+this.terminals_[s]+"'");x=this.lexer.showPosition?"Parse error on line "+(i+1)+":\n"+this.lexer.showPosition()+"\nExpecting "+v.join(", ")+", got '"+(this.terminals_[n]||n)+"'":"Parse error on line "+(i+1)+": Unexpected "+(1==n?"end of input":"'"+(this.terminals_[n]||n)+"'"),this.parseError(x,{text:this.lexer.match,token:this.terminals_[n]||n,line:this.lexer.yylineno,loc:l,expected:v})}}if(q[0]instanceof Array&&q.length>1)throw new Error("Parse Error: multiple actions possible at state: "+p+", token: "+n);switch(q[0]){case 1:d.push(n),e.push(this.lexer.yytext),f.push(this.lexer.yylloc),d.push(q[1]),n=null,o?(n=o,o=null):(j=this.lexer.yyleng,h=this.lexer.yytext,i=this.lexer.yylineno,l=this.lexer.yylloc,k>0&&k--);break;case 2:if(t=this.productions_[q[1]][1],w.$=e[e.length-t],w._$={first_line:f[f.length-(t||1)].first_line,last_line:f[f.length-1].last_line,first_column:f[f.length-(t||1)].first_column,last_column:f[f.length-1].last_column},m&&(w._$.range=[f[f.length-(t||1)].range[0],f[f.length-1].range[1]]),r=this.performAction.call(w,h,j,i,this.yy,q[1],e,f),"undefined"!=typeof r)return r;t&&(d=d.slice(0,-1*t*2),e=e.slice(0,-1*t),f=f.slice(0,-1*t)),d.push(this.productions_[q[1]][0]),e.push(w.$),f.push(w._$),u=g[d[d.length-2]][d[d.length-1]],d.push(u);break;case 3:return!0}}return!0}},c=function(){var a={EOF:1,parseError:function(a,b){if(!this.yy.parser)throw new Error(a);this.yy.parser.parseError(a,b)},setInput:function(a){return this._input=a,this._more=this._less=this.done=!1,this.yylineno=this.yyleng=0,this.yytext=this.matched=this.match="",this.conditionStack=["INITIAL"],this.yylloc={first_line:1,first_column:0,last_line:1,last_column:0},this.options.ranges&&(this.yylloc.range=[0,0]),this.offset=0,this},input:function(){var a=this._input[0];this.yytext+=a,this.yyleng++,this.offset++,this.match+=a,this.matched+=a;var b=a.match(/(?:\r\n?|\n).*/g);return b?(this.yylineno++,this.yylloc.last_line++):this.yylloc.last_column++,this.options.ranges&&this.yylloc.range[1]++,this._input=this._input.slice(1),a},unput:function(a){var b=a.length,c=a.split(/(?:\r\n?|\n)/g);this._input=a+this._input,this.yytext=this.yytext.substr(0,this.yytext.length-b-1),this.offset-=b;var d=this.match.split(/(?:\r\n?|\n)/g);this.match=this.match.substr(0,this.match.length-1),this.matched=this.matched.substr(0,this.matched.length-1),c.length-1&&(this.yylineno-=c.length-1);var e=this.yylloc.range;return this.yylloc={first_line:this.yylloc.first_line,last_line:this.yylineno+1,first_column:this.yylloc.first_column,last_column:c?(c.length===d.length?this.yylloc.first_column:0)+d[d.length-c.length].length-c[0].length:this.yylloc.first_column-b},this.options.ranges&&(this.yylloc.range=[e[0],e[0]+this.yyleng-b]),this},more:function(){return this._more=!0,this},less:function(a){this.unput(this.match.slice(a))},pastInput:function(){var a=this.matched.substr(0,this.matched.length-this.match.length);return(a.length>20?"...":"")+a.substr(-20).replace(/\n/g,"")},upcomingInput:function(){var a=this.match;return a.length<20&&(a+=this._input.substr(0,20-a.length)),(a.substr(0,20)+(a.length>20?"...":"")).replace(/\n/g,"")},showPosition:function(){var a=this.pastInput(),b=new Array(a.length+1).join("-");return a+this.upcomingInput()+"\n"+b+"^"},next:function(){if(this.done)return this.EOF;this._input||(this.done=!0);var a,b,c,d,e;this._more||(this.yytext="",this.match="");for(var f=this._currentRules(),g=0;g<f.length&&(c=this._input.match(this.rules[f[g]]),!c||b&&!(c[0].length>b[0].length)||(b=c,d=g,this.options.flex));g++);return b?(e=b[0].match(/(?:\r\n?|\n).*/g),e&&(this.yylineno+=e.length),this.yylloc={first_line:this.yylloc.last_line,last_line:this.yylineno+1,first_column:this.yylloc.last_column,last_column:e?e[e.length-1].length-e[e.length-1].match(/\r?\n?/)[0].length:this.yylloc.last_column+b[0].length},this.yytext+=b[0],this.match+=b[0],this.matches=b,this.yyleng=this.yytext.length,this.options.ranges&&(this.yylloc.range=[this.offset,this.offset+=this.yyleng]),this._more=!1,this._input=this._input.slice(b[0].length),this.matched+=b[0],a=this.performAction.call(this,this.yy,this,f[d],this.conditionStack[this.conditionStack.length-1]),this.done&&this._input&&(this.done=!1),a?a:void 0):""===this._input?this.EOF:this.parseError("Lexical error on line "+(this.yylineno+1)+". Unrecognized text.\n"+this.showPosition(),{text:"",token:null,line:this.yylineno})},lex:function(){var a=this.next();return"undefined"!=typeof a?a:this.lex()},begin:function(a){this.conditionStack.push(a)},popState:function(){return this.conditionStack.pop()},_currentRules:function(){return this.conditions[this.conditionStack[this.conditionStack.length-1]].rules},topState:function(){return this.conditionStack[this.conditionStack.length-2]},pushState:function(a){this.begin(a)}};return a.options={},a.performAction=function(a,b,c,d){function e(a,c){return b.yytext=b.yytext.substring(a,b.yyleng-c+a)}switch(c){case 0:if("\\\\"===b.yytext.slice(-2)?(e(0,1),this.begin("mu")):"\\"===b.yytext.slice(-1)?(e(0,1),this.begin("emu")):this.begin("mu"),b.yytext)return 15;break;case 1:return 15;case 2:return this.popState(),15;case 3:return this.begin("raw"),15;case 4:return this.popState(),"raw"===this.conditionStack[this.conditionStack.length-1]?15:(e(5,9),"END_RAW_BLOCK");case 5:return 15;case 6:return this.popState(),14;case 7:return 65;case 8:return 68;case 9:return 19;case 10:return this.popState(),this.begin("raw"),23;case 11:return 55;case 12:return 60;case 13:return 29;case 14:return 47;case 15:return this.popState(),44;case 16:return this.popState(),44;case 17:return 34;case 18:return 39;case 19:return 51;case 20:return 48;case 21:this.unput(b.yytext),this.popState(),this.begin("com");break;case 22:return this.popState(),14;case 23:return 48;case 24:return 73;case 25:return 72;case 26:return 72;case 27:return 87;case 28:break;case 29:return this.popState(),54;case 30:return this.popState(),33;case 31:return b.yytext=e(1,2).replace(/\\"/g,'"'),80;case 32:return b.yytext=e(1,2).replace(/\\'/g,"'"),80;case 33:return 85;case 34:return 82;case 35:return 82;case 36:return 83;case 37:return 84;case 38:return 81;case 39:return 75;case 40:return 77;case 41:return 72;case 42:return b.yytext=b.yytext.replace(/\\([\\\]])/g,"$1"),72;case 43:return"INVALID";case 44:return 5}},a.rules=[/^(?:[^\x00]*?(?=(\{\{)))/,/^(?:[^\x00]+)/,/^(?:[^\x00]{2,}?(?=(\{\{|\\\{\{|\\\\\{\{|$)))/,/^(?:\{\{\{\{(?=[^\/]))/,/^(?:\{\{\{\{\/[^\s!"#%-,\.\/;->@\[-\^`\{-~]+(?=[=}\s\/.])\}\}\}\})/,/^(?:[^\x00]+?(?=(\{\{\{\{)))/,/^(?:[\s\S]*?--(~)?\}\})/,/^(?:\()/,/^(?:\))/,/^(?:\{\{\{\{)/,/^(?:\}\}\}\})/,/^(?:\{\{(~)?>)/,/^(?:\{\{(~)?#>)/,/^(?:\{\{(~)?#\*?)/,/^(?:\{\{(~)?\/)/,/^(?:\{\{(~)?\^\s*(~)?\}\})/,/^(?:\{\{(~)?\s*else\s*(~)?\}\})/,/^(?:\{\{(~)?\^)/,/^(?:\{\{(~)?\s*else\b)/,/^(?:\{\{(~)?\{)/,/^(?:\{\{(~)?&)/,/^(?:\{\{(~)?!--)/,/^(?:\{\{(~)?![\s\S]*?\}\})/,/^(?:\{\{(~)?\*?)/,/^(?:=)/,/^(?:\.\.)/,/^(?:\.(?=([=~}\s\/.)|])))/,/^(?:[\/.])/,/^(?:\s+)/,/^(?:\}(~)?\}\})/,/^(?:(~)?\}\})/,/^(?:"(\\["]|[^"])*")/,/^(?:'(\\[']|[^'])*')/,/^(?:@)/,/^(?:true(?=([~}\s)])))/,/^(?:false(?=([~}\s)])))/,/^(?:undefined(?=([~}\s)])))/,/^(?:null(?=([~}\s)])))/,/^(?:-?[0-9]+(?:\.[0-9]+)?(?=([~}\s)])))/,/^(?:as\s+\|)/,/^(?:\|)/,/^(?:([^\s!"#%-,\.\/;->@\[-\^`\{-~]+(?=([=~}\s\/.)|]))))/,/^(?:\[(\\\]|[^\]])*\])/,/^(?:.)/,/^(?:$)/],a.conditions={mu:{rules:[7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44],inclusive:!1},emu:{rules:[2],inclusive:!1},com:{rules:[6],inclusive:!1},raw:{rules:[3,4,5],inclusive:!1},INITIAL:{rules:[0,1,44],inclusive:!0}},a}();return b.lexer=c,a.prototype=b,b.Parser=a,new a}();b["default"]=c,a.exports=b["default"]},function(a,b,c){"use strict";function d(){var a=arguments.length<=0||void 0===arguments[0]?{}:arguments[0];this.options=a}function e(a,b,c){void 0===b&&(b=a.length);var d=a[b-1],e=a[b-2];return d?"ContentStatement"===d.type?(e||!c?/\r?\n\s*?$/:/(^|\r?\n)\s*?$/).test(d.original):void 0:c}function f(a,b,c){void 0===b&&(b=-1);var d=a[b+1],e=a[b+2];return d?"ContentStatement"===d.type?(e||!c?/^\s*?\r?\n/:/^\s*?(\r?\n|$)/).test(d.original):void 0:c}function g(a,b,c){var d=a[null==b?0:b+1];if(d&&"ContentStatement"===d.type&&(c||!d.rightStripped)){var e=d.value;d.value=d.value.replace(c?/^\s+/:/^[ \t]*\r?\n?/,""),d.rightStripped=d.value!==e}}function h(a,b,c){var d=a[null==b?a.length-1:b-1];if(d&&"ContentStatement"===d.type&&(c||!d.leftStripped)){var e=d.value;return d.value=d.value.replace(c?/\s+$/:/[ \t]+$/,""),d.leftStripped=d.value!==e,d.leftStripped}}var i=c(1)["default"];b.__esModule=!0;var j=c(
4349
vendor: 6,533 bytes, line 43
43),k=i(j);d.prototype=new k["default"],d.prototype.Program=function(a){var b=!this.options.ignoreStandalone,c=!this.isRootSeen;this.isRootSeen=!0;for(var d=a.body,i=0,j=d.length;i<j;i++){var k=d[i],l=this.accept(k);if(l){var m=e(d,i,c),n=f(d,i,c),o=l.openStandalone&&m,p=l.closeStandalone&&n,q=l.inlineStandalone&&m&&n;l.close&&g(d,i,!0),l.open&&h(d,i,!0),b&&q&&(g(d,i),h(d,i)&&"PartialStatement"===k.type&&(k.indent=/([ \t]+$)/.exec(d[i-1].original)[1])),b&&o&&(g((k.program||k.inverse).body),h(d,i)),b&&p&&(g(d,i),h((k.inverse||k.program).body))}}return a},d.prototype.BlockStatement=d.prototype.DecoratorBlock=d.prototype.PartialBlockStatement=function(a){this.accept(a.program),this.accept(a.inverse);var b=a.program||a.inverse,c=a.program&&a.inverse,d=c,i=c;if(c&&c.chained)for(d=c.body[0].program;i.chained;)i=i.body[i.body.length-1].program;var j={open:a.openStrip.open,close:a.closeStrip.close,openStandalone:f(b.body),closeStandalone:e((d||b).body)};if(a.openStrip.close&&g(b.body,null,!0),c){var k=a.inverseStrip;k.open&&h(b.body,null,!0),k.close&&g(d.body,null,!0),a.closeStrip.open&&h(i.body,null,!0),!this.options.ignoreStandalone&&e(b.body)&&f(d.body)&&(h(b.body),g(d.body))}else a.closeStrip.open&&h(b.body,null,!0);return j},d.prototype.Decorator=d.prototype.MustacheStatement=function(a){return a.strip},d.prototype.PartialStatement=d.prototype.CommentStatement=function(a){var b=a.strip||{};return{inlineStandalone:!0,open:b.open,close:b.close}},b["default"]=d,a.exports=b["default"]},function(a,b,c){"use strict";function d(){this.parents=[]}function e(a){this.acceptRequired(a,"path"),this.acceptArray(a.params),this.acceptKey(a,"hash")}function f(a){e.call(this,a),this.acceptKey(a,"program"),this.acceptKey(a,"inverse")}function g(a){this.acceptRequired(a,"name"),this.acceptArray(a.params),this.acceptKey(a,"hash")}var h=c(1)["default"];b.__esModule=!0;var i=c(6),j=h(i);d.prototype={constructor:d,mutating:!1,acceptKey:function(a,b){var c=this.accept(a[b]);if(this.mutating){if(c&&!d.prototype[c.type])throw new j["default"]('Unexpected node type "'+c.type+'" found when accepting '+b+" on "+a.type);a[b]=c}},acceptRequired:function(a,b){if(this.acceptKey(a,b),!a[b])throw new j["default"](a.type+" requires "+b)},acceptArray:function(a){for(var b=0,c=a.length;b<c;b++)this.acceptKey(a,b),a[b]||(a.splice(b,1),b--,c--)},accept:function(a){if(a){if(!this[a.type])throw new j["default"]("Unknown type: "+a.type,a);this.current&&this.parents.unshift(this.current),this.current=a;var b=this[a.type](a);return this.current=this.parents.shift(),!this.mutating||b?b:b!==!1?a:void 0}},Program:function(a){this.acceptArray(a.body)},MustacheStatement:e,Decorator:e,BlockStatement:f,DecoratorBlock:f,PartialStatement:g,PartialBlockStatement:function(a){g.call(this,a),this.acceptKey(a,"program")},ContentStatement:function(){},CommentStatement:function(){},SubExpression:e,PathExpression:function(){},StringLiteral:function(){},NumberLiteral:function(){},BooleanLiteral:function(){},UndefinedLiteral:function(){},NullLiteral:function(){},Hash:function(a){this.acceptArray(a.pairs)},HashPair:function(a){this.acceptRequired(a,"value")}},b["default"]=d,a.exports=b["default"]},function(a,b,c){"use strict";function d(a,b){if(b=b.path?b.path.original:b,a.path.original!==b){var c={loc:a.path.loc};throw new q["default"](a.path.original+" doesn't match "+b,c)}}function e(a,b){this.source=a,this.start={line:b.first_line,column:b.first_column},this.end={line:b.last_line,column:b.last_column}}function f(a){return/^\[.*\]$/.test(a)?a.substring(1,a.length-1):a}function g(a,b){return{open:"~"===a.charAt(2),close:"~"===b.charAt(b.length-3)}}function h(a){return a.replace(/^\{\{~?!-?-?/,"").replace(/-?-?~?\}\}$/,"")}function i(a,b,c){c=this.locInfo(c);for(var d=a?"@":"",e=[],f=0,g=0,h=b.length;g<h;g++){var i=b[g].part,j=b[g].original!==i;if(d+=(b[g].separator||"")+i,j||".."!==i&&"."!==i&&"this"!==i)e.push(i);else{if(e.length>0)throw new q["default"]("Invalid path: "+d,{loc:c});".."===i&&f++}}return{type:"PathExpression",data:a,depth:f,parts:e,original:d,loc:c}}function j(a,b,c,d,e,f){var g=d.charAt(3)||d.charAt(2),h="{"!==g&&"&"!==g,i=/\*/.test(d);return{type:i?"Decorator":"MustacheStatement",path:a,params:b,hash:c,escaped:h,strip:e,loc:this.locInfo(f)}}function k(a,b,c,e){d(a,c),e=this.locInfo(e);var f={type:"Program",body:b,strip:{},loc:e};return{type:"BlockStatement",path:a.path,params:a.params,hash:a.hash,program:f,openStrip:{},inverseStrip:{},closeStrip:{},loc:e}}function l(a,b,c,e,f,g){e&&e.path&&d(a,e);var h=/\*/.test(a.open);b.blockParams=a.blockParams;var i=void 0,j=void 0;if(c){if(h)throw new q["default"]("Unexpected inverse block on decorator",c);c.chain&&(c.program.body[0].closeStrip=e.strip),j=c.strip,i=c.program}return f&&(f=i,i=b,b=f),{type:h?"DecoratorBlock":"BlockStatement",path:a.path,params:a.params,hash:a.hash,program:b,inverse:i,openStrip:a.strip,inverseStrip:j,closeStrip:e&&e.strip,loc:this.locInfo(g)}}function m(a,b){if(!b&&a.length){var c=a[0].loc,d=a[a.length-1].loc;c&&d&&(b={source:c.source,start:{line:c.start.line,column:c.start.column},end:{line:d.end.line,column:d.end.column}})}return{type:"Program",body:a,strip:{},loc:b}}function n(a,b,c,e){return d(a,c),{type:"PartialBlockStatement",name:a.path,params:a.params,hash:a.hash,program:b,openStrip:a.strip,closeStrip:c&&c.strip,loc:this.locInfo(e)}}var o=c(1)["default"];b.__esModule=!0,b.SourceLocation=e,b.id=f,b.stripFlags=g,b.stripComment=h,b.preparePath=i,b.prepareMustache=j,b.prepareRawBlock=k,b.prepareBlock=l,b.prepareProgram=m,b.preparePartialBlock=n;var p=c(6),q=o(p)},function(a,b,c){"use strict";function d(){}function e(a,b,c){if(null==a||"string"!=typeof a&&"Program"!==a.type)throw new l["default"]("You must pass a string or Handlebars AST to Handlebars.precompile. You passed "+a);b=b||{},"data"in b||(b.data=!0),b.compat&&(b.useDepths=!0);var d=c.parse(a,b),e=(new c.Compiler).compile(d,b);return(new c.JavaScriptCompiler).compile(e,b)}function f(a,b,c){function d(){var d=c.parse(a,b),e=(new c.Compiler).compile(d,b),f=(new c.JavaScriptCompiler).compile(e,b,void 0,!0);return c.template(f)}function e(a,b){return f||(f=d()),f.call(this,a,b)}if(void 0===b&&(b={}),null==a||"string"!=typeof a&&"Program"!==a.type)throw new l["default"]("You must pass a string or Handlebars AST to Handlebars.compile. You passed "+a);b=m.extend({},b),"data"in b||(b.data=!0),b.compat&&(b.useDepths=!0);var f=void 0;return e._setup=function(a){return f||(f=d()),f._setup(a)},e._child=function(a,b,c,e){return f||(f=d()),
vendor: 11,617 bytes, lines 43-44
43f._child(a,b,c,e)},e}function g(a,b){if(a===b)return!0;if(m.isArray(a)&&m.isArray(b)&&a.length===b.length){for(var c=0;c<a.length;c++)if(!g(a[c],b[c]))return!1;return!0}}function h(a){if(!a.path.parts){var b=a.path;a.path={type:"PathExpression",data:!1,depth:0,parts:[b.original+""],original:b.original+"",loc:b.loc}}}var i=c(34)["default"],j=c(1)["default"];b.__esModule=!0,b.Compiler=d,b.precompile=e,b.compile=f;var k=c(6),l=j(k),m=c(5),n=c(45),o=j(n),p=[].slice;d.prototype={compiler:d,equals:function(a){var b=this.opcodes.length;if(a.opcodes.length!==b)return!1;for(var c=0;c<b;c++){var d=this.opcodes[c],e=a.opcodes[c];if(d.opcode!==e.opcode||!g(d.args,e.args))return!1}b=this.children.length;for(var c=0;c<b;c++)if(!this.children[c].equals(a.children[c]))return!1;return!0},guid:0,compile:function(a,b){return this.sourceNode=[],this.opcodes=[],this.children=[],this.options=b,this.stringParams=b.stringParams,this.trackIds=b.trackIds,b.blockParams=b.blockParams||[],b.knownHelpers=m.extend(i(null),{helperMissing:!0,blockHelperMissing:!0,each:!0,"if":!0,unless:!0,"with":!0,log:!0,lookup:!0},b.knownHelpers),this.accept(a)},compileProgram:function(a){var b=new this.compiler,c=b.compile(a,this.options),d=this.guid++;return this.usePartial=this.usePartial||c.usePartial,this.children[d]=c,this.useDepths=this.useDepths||c.useDepths,d},accept:function(a){if(!this[a.type])throw new l["default"]("Unknown type: "+a.type,a);this.sourceNode.unshift(a);var b=this[a.type](a);return this.sourceNode.shift(),b},Program:function(a){this.options.blockParams.unshift(a.blockParams);for(var b=a.body,c=b.length,d=0;d<c;d++)this.accept(b[d]);return this.options.blockParams.shift(),this.isSimple=1===c,this.blockParams=a.blockParams?a.blockParams.length:0,this},BlockStatement:function(a){h(a);var b=a.program,c=a.inverse;b=b&&this.compileProgram(b),c=c&&this.compileProgram(c);var d=this.classifySexpr(a);"helper"===d?this.helperSexpr(a,b,c):"simple"===d?(this.simpleSexpr(a),this.opcode("pushProgram",b),this.opcode("pushProgram",c),this.opcode("emptyHash"),this.opcode("blockValue",a.path.original)):(this.ambiguousSexpr(a,b,c),this.opcode("pushProgram",b),this.opcode("pushProgram",c),this.opcode("emptyHash"),this.opcode("ambiguousBlockValue")),this.opcode("append")},DecoratorBlock:function(a){var b=a.program&&this.compileProgram(a.program),c=this.setupFullMustacheParams(a,b,void 0),d=a.path;this.useDecorators=!0,this.opcode("registerDecorator",c.length,d.original)},PartialStatement:function(a){this.usePartial=!0;var b=a.program;b&&(b=this.compileProgram(a.program));var c=a.params;if(c.length>1)throw new l["default"]("Unsupported number of partial arguments: "+c.length,a);c.length||(this.options.explicitPartialContext?this.opcode("pushLiteral","undefined"):c.push({type:"PathExpression",parts:[],depth:0}));var d=a.name.original,e="SubExpression"===a.name.type;e&&this.accept(a.name),this.setupFullMustacheParams(a,b,void 0,!0);var f=a.indent||"";this.options.preventIndent&&f&&(this.opcode("appendContent",f),f=""),this.opcode("invokePartial",e,d,f),this.opcode("append")},PartialBlockStatement:function(a){this.PartialStatement(a)},MustacheStatement:function(a){this.SubExpression(a),a.escaped&&!this.options.noEscape?this.opcode("appendEscaped"):this.opcode("append")},Decorator:function(a){this.DecoratorBlock(a)},ContentStatement:function(a){a.value&&this.opcode("appendContent",a.value)},CommentStatement:function(){},SubExpression:function(a){h(a);var b=this.classifySexpr(a);"simple"===b?this.simpleSexpr(a):"helper"===b?this.helperSexpr(a):this.ambiguousSexpr(a)},ambiguousSexpr:function(a,b,c){var d=a.path,e=d.parts[0],f=null!=b||null!=c;this.opcode("getContext",d.depth),this.opcode("pushProgram",b),this.opcode("pushProgram",c),d.strict=!0,this.accept(d),this.opcode("invokeAmbiguous",e,f)},simpleSexpr:function(a){var b=a.path;b.strict=!0,this.accept(b),this.opcode("resolvePossibleLambda")},helperSexpr:function(a,b,c){var d=this.setupFullMustacheParams(a,b,c),e=a.path,f=e.parts[0];if(this.options.knownHelpers[f])this.opcode("invokeKnownHelper",d.length,f);else{if(this.options.knownHelpersOnly)throw new l["default"]("You specified knownHelpersOnly, but used the unknown helper "+f,a);e.strict=!0,e.falsy=!0,this.accept(e),this.opcode("invokeHelper",d.length,e.original,o["default"].helpers.simpleId(e))}},PathExpression:function(a){this.addDepth(a.depth),this.opcode("getContext",a.depth);var b=a.parts[0],c=o["default"].helpers.scopedId(a),d=!a.depth&&!c&&this.blockParamIndex(b);d?this.opcode("lookupBlockParam",d,a.parts):b?a.data?(this.options.data=!0,this.opcode("lookupData",a.depth,a.parts,a.strict)):this.opcode("lookupOnContext",a.parts,a.falsy,a.strict,c):this.opcode("pushContext")},StringLiteral:function(a){this.opcode("pushString",a.value)},NumberLiteral:function(a){this.opcode("pushLiteral",a.value)},BooleanLiteral:function(a){this.opcode("pushLiteral",a.value)},UndefinedLiteral:function(){this.opcode("pushLiteral","undefined")},NullLiteral:function(){this.opcode("pushLiteral","null")},Hash:function(a){var b=a.pairs,c=0,d=b.length;for(this.opcode("pushHash");c<d;c++)this.pushParam(b[c].value);for(;c--;)this.opcode("assignToHash",b[c].key);this.opcode("popHash")},opcode:function(a){this.opcodes.push({opcode:a,args:p.call(arguments,1),loc:this.sourceNode[0].loc})},addDepth:function(a){a&&(this.useDepths=!0)},classifySexpr:function(a){var b=o["default"].helpers.simpleId(a.path),c=b&&!!this.blockParamIndex(a.path.parts[0]),d=!c&&o["default"].helpers.helperExpression(a),e=!c&&(d||b);if(e&&!d){var f=a.path.parts[0],g=this.options;g.knownHelpers[f]?d=!0:g.knownHelpersOnly&&(e=!1)}return d?"helper":e?"ambiguous":"simple"},pushParams:function(a){for(var b=0,c=a.length;b<c;b++)this.pushParam(a[b])},pushParam:function(a){var b=null!=a.value?a.value:a.original||"";if(this.stringParams)b.replace&&(b=b.replace(/^(\.?\.\/)*/g,"").replace(/\//g,".")),a.depth&&this.addDepth(a.depth),this.opcode("getContext",a.depth||0),this.opcode("pushStringParam",b,a.type),"SubExpression"===a.type&&this.accept(a);else{if(this.trackIds){var c=void 0;if(!a.parts||o["default"].helpers.scopedId(a)||a.depth||(c=this.blockParamIndex(a.parts[0])),c){var d=a.parts.slice(1).join(".");this.opcode("pushId","BlockParam",c,d)}else b=a.original||b,b.replace&&(b=b.replace(/^this(?:\.|$)/,"").replace(/^\.\//,"").replace(/^\.$/,"")),this.opcode("pushId",a.type,b)}this.accept(a)}},setupFullMustacheParams:function(a,b,c,d){var e=a.params;return this.pushParams(e),this.opcode("pushProgram",b),this.opcode("pushProgram",c),a.hash?this.accept(a.hash):this.opcode("emptyHash",d),e},blockParamIndex:function(a){for(var b=0,c=this.options.blockParams.length;b<c;b++){var d=this.options.blockParams[b],e=d&&m.indexOf(d,a);if(d&&e>=0)return[b,e]}}}},function(a,b,c){"use strict";function d(a){this.value=a}function e(){}function f(a,b,c,d){var e=b.popStack(),f=0,g=c.length;for(a&&g--;f<g;f++)e=b.nameLookup(e,c[f],d);return a?[b.aliasable("container.strict"),"(",e,", ",b.quotedString(c[f]),", ",JSON.stringify(b.source.currentLocation)," )"]:e}var g=c(13)["default"],h=c(1)["default"];b.__esModule=!0;var i=c(4),j=c(6),k=h(j),l=c(5),m=c(53),n=h(m);e.prototype={nameLookup:function(a,b){return this.internalNameLookup(a,b)},depthedLookup:function(a){return[this.aliasable("container.lookup"),'(depths, "',a,'")']},compilerInfo:function(){var a=i.COMPILER_REVISION,b=i.REVISION_CHANGES[a];return[a,b]},appendToBuffer:function(a,b,c){return l.isArray(a)||(a=[a]),a=this.source.wrap(a,b),this.environment.isSimple?["return ",a,";"]:c?["buffer += ",a,";"]:(a.appendToBuffer=!0,a)},initializeBuffer:function(){return this.quotedString("")},internalNameLookup:function(a,b){return this.lookupPropertyFunctionIsUsed=!0,["lookupProperty(",a,",",JSON.stringify(b),")"]},lookupPropertyFunctionIsUsed:!1,compile:function(a,b,c,d){this.environment=a,this.options=b,this.stringParams=this.options.stringParams,this.trackIds=this.options.trackIds,this.precompile=!d,this.name=this.environment.name,this.isChild=!!c,this.context=c||{decorators:[],programs:[],environments:[]},this.preamble(),this.stackSlot=0,this.stackVars=[],this.aliases={},this.registers={list:[]},this.hashes=[],this.compileStack=[],this.inlineStack=[],this.blockParams=[],this.compileChildren(a,b),this.useDepths=this.useDepths||a.useDepths||a.useDecorators||this.options.compat,this.useBlockParams=this.useBlockParams||a.useBlockParams;var e=a.opcodes,f=void 0,g=void 0,h=void 0,i=void 0;for(h=0,i=e.length;h<i;h++)f=e[h],this.source.currentLocation=f.loc,g=g||f.loc,this[f.opcode].apply(this,f.args);if(this.source.currentLocation=g,this.pushSource(""),this.stackSlot||this.inlineStack.length||this.compileStack.length)throw new k["default"]("Compile completed with content left on stack");this.decorators.isEmpty()?this.decorators=void 0:(this.useDecorators=!0,this.decorators.prepend(["var decorators = container.decorators, ",this.lookupPropertyFunctionVarDeclaration(),";\n"]),
44this.decorators.push("return fn;"),d?this.decorators=Function.apply(this,["fn","props","container","depth0","data","blockParams","depths",this.decorators.merge()]):(this.decorators.prepend("function(fn, props, container, depth0, data, blockParams, depths) {\n"),this.decorators.push("}\n"),this.decorators=this.decorators.merge()));var j=this.createFunctionContext(d);if(this.isChild)return j;var l={compiler:this.compilerInfo(),main:j};this.decorators&&(l.main_d=this.decorators,l.useDecorators=!0);var m=this.context,n=m.programs,o=m.decorators;for(h=0,i=n.length;h<i;h++)n[h]&&(l[h]=n[h],o[h]&&(l[h+"_d"]=o[h],l.useDecorators=!0));return this.environment.usePartial&&(l.usePartial=!0),this.options.data&&(l.useData=!0),this.useDepths&&(l.useDepths=!0),this.useBlockParams&&(l.useBlockParams=!0),this.options.compat&&(l.compat=!0),d?l.compilerOptions=this.options:(l.compiler=JSON.stringify(l.compiler),this.source.currentLocation={start:{line:1,column:0}},l=this.objectLiteral(l),b.srcName?(l=l.toStringWithSourceMap({file:b.destName}),l.map=l.map&&l.map.toString()):l=l.toString()),l},preamble:function(){this.lastContext=0,this.source=new n["default"](this.options.srcName),this.decorators=new n["default"](this.options.srcName)},createFunctionContext:function(a){var b=this,c="",d=this.stackVars.concat(this.registers.list);d.length>0&&(c+=", "+d.join(", "));var e=0;g(this.aliases).forEach(function(a){var d=b.aliases[a];d.children&&d.referenceCount>1&&(c+=", alias"+ ++e+"="+a,d.children[0]="alias"+e)}),this.lookupPropertyFunctionIsUsed&&(c+=", "+this.lookupPropertyFunctionVarDeclaration());var f=["container","depth0","helpers","partials","data"];(this.useBlockParams||this.useDepths)&&f.push("blockParams"),this.useDepths&&f.push("depths");var h=this.mergeSource(c);return a?(f.push(h),Function.apply(this,f)):this.source.wrap(["function(",f.join(","),") {\n  ",h,"}"])},mergeSource:function(a){var b=this.environment.isSimple,c=!this.forceBuffer,d=void 0,e=void 0,f=void 0,g=void 0;return this.source.each(function(a){a.appendToBuffer?(f?a.prepend("  + "):f=a,g=a):(f&&(e?f.prepend("buffer += "):d=!0,g.add(";"),f=g=void 0),e=!0,b||(c=!1))}),c?f?(f.prepend("return "),g.add(";")):e||this.source.push('return "";'):(a+=", buffer = "+(d?"":this.initializeBuffer()),f?(f.prepend("return buffer + "),g.add(";")):this.source.push("return buffer;")),a&&this.source.prepend("var "+a.substring(2)+(d?"":";\n")),this.source.merge()},lookupPropertyFunctionVarDeclaration:function(){return"\n      lookupProperty = container.lookupProperty || function(parent, propertyName) {\n        if (Object.prototype.hasOwnProperty.call(parent, propertyName)) {\
44n          return parent[propertyName];\n        }\n        return undefined\n    }\n    ".trim()},blockValue:function(a){var b=this.aliasable("container.hooks.blockHelperMissing"),c=[this.contextName(0)];this.setupHelperArgs(a,0,c);var d=this.popStack();c.splice(1,0,d),this.push(this.source.functionCall(b,"call",c))},ambiguousBlockValue:function(){var a=this.aliasable("container.hooks.blockHelperMissing"),b=[this.contextName(0)];this.setupHelperArgs("",0,b,!0),this.flushInline();var c=this.topStack();b.splice(1,0,c),this.pushSource(["if (!",this.lastHelper,") { ",c," = ",this.source.functionCall(a,"call",b),"}"])},appendContent:function(a){this.pendingContent?a=this.pendingContent+a:this.pendingLocation=this.source.currentLocation,this.pendingContent=a},append:function(){if(this.isInline())this.replaceStack(function(a){return[" != null ? ",a,' : ""']}),this.pushSource(this.appendToBuffer(this.popStack()));else{var a=this.popStack();this.pushSource(["if (",a," != null) { ",this.appendToBuffer(a,void 0,!0)," }"]),this.environment.isSimple&&this.pushSource(["else { ",this.appendToBuffer("''",void 0,!0)," }"])}},appendEscaped:function(){this.pushSource(this.appendToBuffer([this.aliasable("container.escapeExpression"),"(",this.popStack(),")"]))},getContext:function(a){this.lastContext=a},pushContext:function(){this.pushStackLiteral(this.contextName(this.lastContext))},lookupOnContext:function(a,b,c,d){var e=0;d||!this.options.compat||this.lastContext?this.pushContext():this.push(this.depthedLookup(a[e++])),this.resolvePath("context",a,e,b,c)},lookupBlockParam:function(a,b){this.useBlockParams=!0,this.push(["blockParams[",a[0],"][",a[1],"]"]),this.resolvePath("context",b,1)},lookupData:function(a,b,c){a?this.pushStackLiteral("container.data(data, "+a+")"):this.pushStackLiteral("data"),this.resolvePath("data",b,0,!0,c)},resolvePath:function(a,b,c,d,e){var g=this;if(this.options.strict||this.options.assumeObjects)return void this.push(f(this.options.strict&&e,this,b,a));for(var h=b.length;c<h;c++)this.replaceStack(function(e){var f=g.nameLookup(e,b[c],a);return d?[" && ",f]:[" != null ? ",f," : ",e]})},resolvePossibleLambda:function(){this.push([this.aliasable("container.lambda"),"(",this.popStack(),", ",this.contextName(0),")"])},pushStringParam:function(a,b){this.pushContext(),this.pushString(b),"SubExpression"!==b&&("string"==typeof a?this.pushString(a):this.pushStackLiteral(a))},emptyHash:function(a){this.trackIds&&this.push("{}"),this.stringParams&&(this.push("{}"),this.push("{}")),this.pushStackLiteral(a?"undefined":"{}")},pushHash:function(){this.hash&&this.hashes.push(this.hash),this.hash={values:{},types:[],contexts:[],ids:[]}},popHash:function(){var a=this.hash;this.hash=this.hashes.pop(),this.trackIds&&this.push(this.objectLiteral(a.ids)),this.stringParams&&(this.push(this.objectLiteral(a.contexts)),this.push(this.objectLiteral(a.types))),this.push(this.objectLiteral(a.values))},pushString:function(a){this.pushStackLiteral(this.quotedString(a))},pushLiteral:function(a){this.pushStackLiteral(a)},pushProgram:function(a){null!=a?this.pushStackLiteral(this.programExpression(a)):this.pushStackLiteral(null)},registerDecorator:function(a,b){var c=this.nameLookup("decorators",b,"decorator"),d=this.setupHelperArgs(b,a);this.decorators.push(["fn = ",this.decorators.functionCall(c,"",["fn","props","container",d])," || fn;"])},invokeHelper:function(a,b,c){var d=this.popStack(),e=this.setupHelper(a,b),f=[];c&&f.push(e.name),f.push(d),this.options.strict||f.push(this.aliasable("container.hooks.helperMissing"));var g=["(",this.itemsSeparatedBy(f,"||"),")"],h=this.source.functionCall(g,"call",e.callParams);this.push(h)},itemsSeparatedBy:function(a,b){var c=[];c.push(a[0]);for(var d=1;d<a.length;d++)c.push(b,a[d]);return c},invokeKnownHelper:function(a,b){var c=this.setupHelper(a,b);this.push(this.source.functionCall(c.name,"call",c.callParams))},invokeAmbiguous:function(a,b){this.useRegister("helper");var c=this.popStack();this.emptyHash();var d=this.setupHelper(0,a,b),e=this.lastHelper=this.nameLookup("helpers",a,"helper"),f=["(","(helper = ",e," || ",c,")"];this.options.strict||(f[0]="(helper = ",f.push(" != null ? helper : ",this.aliasable("container.hooks.helperMissing"))),this.push(["(",f,d.paramsInit?["),(",d.paramsInit]:[],"),","(typeof helper === ",this.aliasable('"function"')," ? ",this.source.functionCall("helper","call",d.callParams)," : helper))"])},invokePartial:function(a,b,c){var d=[],e=this.setupParams(b,1,d);a&&(b=this.popStack(),delete e.name),c&&(e.indent=JSON.stringify(c)),e.helpers="helpers",e.partials="partials",e.decorators="container.decorators",a?d.unshift(b):d.unshift(this.nameLookup("partials",b,"partial")),this.options.compat&&(e.depths="depths"),e=this.objectLiteral(e),d.push(e),this.push(this.source.functionCall("container.invokePartial","",d))},assignToHash:function(a){var b=this.popStack(),c=void 0,d=void 0,e=void 0;this.trackIds&&(e=this.popStack()),this.stringParams&&(d=this.popStack(),c=this.popStack());var f=this.hash;c&&(f.contexts[a]=c),d&&(f.types[a]=d),e&&(f.ids[a]=e),f.values[a]=b},pushId:function(a,b,c){"BlockParam"===a?this.pushStackLiteral("blockParams["+b[0]+"].path["+b[1]+"]"+(c?" + "+JSON.stringify("."+c):"")):"PathExpression"===a?this.pushString(b):"Sub
44Expression"===a?this.pushStackLiteral("true"):this.pushStackLiteral("null")},compiler:e,compileChildren:function(a,b){for(var c=a.children,d=void 0,e=void 0,f=0,g=c.length;f<g;f++){d=c[f],e=new this.compiler;var h=this.matchExistingProgram(d);if(null==h){this.context.programs.push("");var i=this.context.programs.length;d.index=i,d.name="program"+i,this.context.programs[i]=e.compile(d,b,this.context,!this.precompile),this.context.decorators[i]=e.decorators,this.context.environments[i]=d,this.useDepths=this.useDepths||e.useDepths,this.useBlockParams=this.useBlockParams||e.useBlockParams,d.useDepths=this.useDepths,d.useBlockParams=this.useBlockParams}else d.index=h.index,d.name="program"+h.index,this.useDepths=this.useDepths||h.useDepths,this.useBlockParams=this.useBlockParams||h.useBlockParams}},matchExistingProgram:function(a){for(var b=0,c=this.context.environments.length;b<c;b++){var d=this.context.environments[b];if(d&&d.equals(a))return d}},programExpression:function(a){var b=this.environment.children[a],c=[b.index,"data",b.blockParams];return(this.useBlockParams||this.useDepths)&&c.push("blockParams"),this.useDepths&&c.push("depths"),"container.program("+c.join(", ")+")"},useRegister:function(a){this.registers[a]||(this.registers[a]=!0,this.registers.list.push(a))},push:function(a){return a instanceof d||(a=this.source.wrap(a)),this.inlineStack.push(a),a},pushStackLiteral:function(a){this.push(new d(a))},pushSource:function(a){this.pendingContent&&(this.source.push(this.appendToBuffer(this.source.quotedString(this.pendingContent),this.pendingLocation)),this.pendingContent=void 0),a&&this.source.push(a)},replaceStack:function(a){var b=["("],c=void 0,e=void 0,f=void 0;if(!this.isInline())throw new k["default"]("replaceStack on non-inline");var g=this.popStack(!0);if(g instanceof d)c=[g.value],b=["(",c],f=!0;else{e=!0;var h=this.incrStack();b=["((",this.push(h)," = ",g,")"],c=this.topStack()}var i=a.call(this,c);f||this.popStack(),e&&this.stackSlot--,this.push(b.concat(i,")"))},incrStack:function(){return this.stackSlot++,this.stackSlot>this.stackVars.length&&this.stackVars.push("stack"+this.stackSlot),this.topStackName()},topStackName:function(){return"stack"+this.stackSlot},flushInline:function(){var a=this.inlineStack;this.inlineStack=[];for(var b=0,c=a.length;b<c;b++){var e=a[b];if(e instanceof d)this.compileStack.push(e);else{var f=this.incrStack();this.pushSource([f," = ",e,";"]),this.compileStack.push(f)}}},isInline:function(){return this.inlineStack.length},popStack:function(a){var b=this.isInline(),c=(b?this.inlineStack:this.compileStack).pop();if(!a&&c instanceof d)return c.value;if(!b){if(!this.stackSlot)throw new k["default"]("Invalid stack pop");this.stackSlot--}return c},topStack:function(){var a=this.isInline()?this.inlineStack:this.compileStack,b=a[a.length-1];return b instanceof d?b.value:b},contextName:function(a){return this.useDepths&&a?"depths["+a+"]":"depth"+a},quotedString:function(a){return this.source.quotedString(a)},objectLiteral:function(a){return this.source.objectLiteral(a)},aliasable:function(a){var b=this.aliases[a];return b?(b.referenceCount++,b):(b=this.aliases[a]=this.source.wrap(a),b.aliasable=!0,b.referenceCount=1,b)},setupHelper:function(a,b,c){var d=[],e=this.setupHelperArgs(b,a,d,c),f=this.nameLookup("helpers",b,"helper"),g=this.aliasable(this.contextName(0)+" != null ? "+this.contextName(0)+" : (container.nullContext || {})");return{params:d,paramsInit:e,name:f,callParams:[g].concat(d)}},setupParams:function(a,b,c){var d={},e=[],f=[],g=[],h=!c,i=void 0;h&&(c=[]),d.name=this.quotedString(a),d.hash=this.popStack(),this.trackIds&&(d.hashIds=this.popStack()),this.stringParams&&(d.hashTypes=this.popStack(),d.hashContexts=this.popStack());var j=this.popStack(),k=this.popStack();(k||j)&&(d.fn=k||"container.noop",d.inverse=j||"container.noop");for(var l=b;l--;)i=this.popStack(),c[l]=i,this.trackIds&&(g[l]=this.popStack()),this.stringParams&&(f[l]=this.popStack(),e[l]=this.popStack());return h&&(d.args=this.source.generateArray(c)),this.trackIds&&(d.ids=this.source.generateArray(g)),this.stringParams&&(d.types=this.source.generateArray(f),d.contexts=this.source.generateArray(e)),this.options.data&&(d.data="data"),this.useBlockParams&&(d.blockParams="blockParams"),d},setupHelperArgs:function(a,b,c,d){var e=this.setupParams(a,b,c);return e.loc=JSON.stringify(this.source.currentLocation),e=this.objectLiteral(e),d?(this.useRegister("options"),c.push("options"),["o
44ptions=",e]):c?(c.push(e),""):e}},function(){for(var a="break else new var case finally return void catch for switch while continue function this with default if throw delete in try do instanceof typeof abstract enum int short boolean export interface static byte extends long super char final native synchronized class float package throws const goto private transient debugger implements protected volatile double import public let yield await null true false".split(" "),b=e.RESERVED_WORDS={},c=0,d=a.length;c<d;c++)b[a[c]]=!0}(),e.isValidJavaScriptVariableName=function(a){return!e.RESERVED_WORDS[a]&&/^[a-zA-Z_$][0-9a-zA-Z_$]*$/.test(a)},b["default"]=e,a.exports=b["default"]},function(a,b,c){"use strict";function d(a,b,c){if(g.isArray(a)){for(var d=[],e=0,f=a.length;e<f;e++)d.push(b.wrap(a[e],c));return d}return"boolean"==typeof a||"number"==typeof a?a+"":a}function e(a){this.srcFile=a,this.source=[]}var f=c(13)["default"];b.__esModule=!0;var g=c(5),h=void 0;try{}catch(i){}h||(h=function(a,b,c,d){this.src="",d&&this.add(d)},h.prototype={add:function(a){g.isArray(a)&&(a=a.join("")),this.src+=a},prepend:function(a){g.isArray(a)&&(a=a.join("")),this.src=a+this.src},toStringWithSourceMap:function(){return{code:this.toString()}},toString:function(){return this.src}}),e.prototype={isEmpty:function(){return!this.source.length},prepend:function(a,b){this.source.unshift(this.wrap(a,b))},push:function(a,b){this.source.push(this.wrap(a,b))},merge:function(){var a=this.empty();return this.each(function(b){a.add(["  ",b,"\n"])}),a},each:function(a){for(var b=0,c=this.source.length;b<c;b++)a(this.source[b])},empty:function(){var a=this.currentLocation||{start:{}};return new h(a.start.line,a.start.column,this.srcFile)},wrap:function(a){var b=arguments.length<=1||void 0===arguments[1]?this.currentLocation||{start:{}}:arguments[1];return a instanceof h?a:(a=d(a,this,b),new h(b.start.line,b.start.column,this.srcFile,a))},functionCall:function(a,b,c){return c=this.generateList(c),this.wrap([a,b?"."+b+"(":"(",c,")"])},quotedString:function(a){return'"'+(a+"").replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")+'"'},objectLiteral:function(a){var b=this,c=[];f(a).forEach(function(e){var f=d(a[e],b);"undefined"!==f&&c.push([b.quotedString(e),":",f])});var e=this.generateList(c);
44return e.prepend("{"),e.add("}"),e},generateList:function(a){for(var b=this.empty(),c=0,e=a.length;c<e;c++)c&&b.add(","),b.add(d(a[c],this));return b},generateArray:function(a){var b=this.generateList(a);return b.prepend("["),b.add("]"),b}},b["default"]=e,a.exports=b["default"]}])});
45/*!
46 * jQuery Transit - CSS3 transitions and transformations
47 * (c) 2011-2012 Rico Sta. Cruz <[email protected]>
48 * MIT Licensed.
49 *
50 * http://ricostacruz.com/jquery.transit
51 * http://github.com/rstacruz/jquery.transit
52 */
53(function(k){k.transit={version:"0.9.9",propertyMap:{marginLeft:"margin",marginRight:"margin",marginBottom:"margin",marginTop:"margin",paddingLeft:"padding",paddingRight:"padding",paddingBottom:"padding",paddingTop:"padding"},enabled:true,useTransitionEnd:false};var d=document.createElement("div");var q={};function b(v){if(v in d.style){return v}var u=["Moz","Webkit","O","ms"];var r=v.charAt(0).toUpperCase()+v.substr(1);if(v in d.style){return v}for(var t=0;t<u.length;++t){var s=u[t]+r;if(s in d.style){return s}}}function e(){d.style[q.transform]="";d.style[q.transform]="rotateY(90deg)";return d.style[q.transform]!==""}var a=navigator.userAgent.toLowerCase().indexOf("chrome")>-1;q.transition=b("transition");q.transitionDelay=b("transitionDelay");q.transform=b("transform");q.transformOrigin=b("transformOrigin");q.transform3d=e();var i={transition:"transitionEnd",MozTransition:"transitionend",OTransition:"oTransitionEnd",WebkitTransition:"webkitTransitionEnd",msTransition:"MSTransitionEnd"};var f=q.transitionEnd=i[q.transition]||null;for(var p in q){if(q.hasOwnProperty(p)&&typeof k.support[p]==="undefined"){k.support[p]=q[p]}}d=null;k.cssEase={_default:"ease","in":"ease-in",out:"ease-out","in-out":"ease-in-out",snap:"cubic-bezier(0,1,.5,1)",easeOutCubic:"cubic-bezier(.215,.61,.355,1)",easeInOutCubic:"cubic-bezier(.645,.045,.355,1)",easeInCirc:"cubic-bezier(.6,.04,.98,.335)",easeOutCirc:"cubic-bezier(.075,.82,.165,1)",easeInOutCirc:"cubic-bezier(.785,.135,.15,.86)",easeInExpo:"cubic-bezier(.95,.05,.795,.035)",easeOutExpo:"cubic-bezier(.19,1,.22,1)",easeInOutExpo:"cubic-bezier(1,0,0,1)",easeInQuad:"cubic-bezier(.55,.085,.68,.53)",easeOutQuad:"cubic-bezier(.25,.46,.45,.94)",easeInOutQuad:"cubic-bezier(.455,.03,.515,.955)",easeInQuart:"cubic-bezier(.895,.03,.685,.22)",easeOutQuart:"cubic-bezier(.165,.84,.44,1)",easeInOutQuart:"cubic-bezier(.77,0,.175,1)",easeInQuint:"cubic-bezier(.755,.05,.855,.06)",easeOutQuint:"cubic-bezier(.23,1,.32,1)",easeInOutQuint:"cubic-bezier(.86,0,.07,1)",easeInSine:"cubic-bezier(.47,0,.745,.715)",easeOutSine:"cubic-bezier(.39,.575,.565,1)",easeInOutSine:"cubic-bezier(.445,.05,.55,.95)",easeInBack:"cubic-bezier(.6,-.28,.735,.045)",easeOutBack:"cubic-bezier(.175, .885,.32,1.275)",easeInOutBack:"cubic-bezier(.68,-.55,.265,1.55)"};k.cssHooks["transit:transform"]={get:function(r){return k(r).data("transform")||new j()},set:function(s,r){var t=r;if(!(t instanceof j)){t=new j(t)}if(q.transform==="WebkitTransform"&&!a){s.style[q.transform]=t.toString(true)}else{s.style[q.transform]=t.toString()}k(s).data("transform",t)}};k.cssHooks.transform={set:k.cssHooks["transit:transform"].set};if(k.fn.jquery<"1.8"){k.cssHooks.transformOrigin={get:function(r){return r.style[q.transformOrigin]},set:function(r,s){r.style[q.transformOrigin]=s}};
53k.cssHooks.transition={get:function(r){return r.style[q.transition]},set:function(r,s){r.style[q.transition]=s}}}n("scale");n("translate");n("rotate");n("rotateX");n("rotateY");n("rotate3d");n("perspective");n("skewX");n("skewY");n("x",true);n("y",true);function j(r){if(typeof r==="string"){this.parse(r)}return this}j.prototype={setFromString:function(t,s){var r=(typeof s==="string")?s.split(","):(s.constructor===Array)?s:[s];r.unshift(t);j.prototype.set.apply(this,r)},set:function(s){var r=Array.prototype.slice.apply(arguments,[1]);if(this.setter[s]){this.setter[s].apply(this,r)}else{this[s]=r.join(",")}},get:function(r){if(this.getter[r]){return this.getter[r].apply(this)}else{return this[r]||0}},setter:{rotate:function(r){this.rotate=o(r,"deg")},rotateX:function(r){this.rotateX=o(r,"deg")},rotateY:function(r){this.rotateY=o(r,"deg")},scale:function(r,s){if(s===undefined){s=r}this.scale=r+","+s},skewX:function(r){this.skewX=o(r,"deg")},skewY:function(r){this.skewY=o(r,"deg")},perspective:function(r){this.perspective=o(r,"px")},x:function(r){this.set("translate",r,null)},y:function(r){this.set("translate",null,r)},translate:function(r,s){if(this._translateX===undefined){this._translateX=0}if(this._translateY===undefined){this._translateY=0}if(r!==null&&r!==undefined){this._translateX=o(r,"px")}if(s!==null&&s!==undefined){this._translateY=o(s,"px")}
53this.translate=this._translateX+","+this._translateY}},getter:{x:function(){return this._translateX||0},y:function(){return this._translateY||0},scale:function(){var r=(this.scale||"1,1").split(",");if(r[0]){r[0]=parseFloat(r[0])}if(r[1]){r[1]=parseFloat(r[1])}return(r[0]===r[1])?r[0]:r},rotate3d:function(){var t=(this.rotate3d||"0,0,0,0deg").split(",");for(var r=0;r<=3;++r){if(t[r]){t[r]=parseFloat(t[r])}}if(t[3]){t[3]=o(t[3],"deg")}return t}},parse:function(s){var r=this;s.replace(/([a-zA-Z0-9]+)\((.*?)\)/g,function(t,v,u){r.setFromString(v,u)})},toString:function(t){var s=[];for(var r in this){if(this.hasOwnProperty(r)){if((!q.transform3d)&&((r==="rotateX")||(r==="rotateY")||(r==="perspective")||(r==="transformOrigin"))){continue}if(r[0]!=="_"){if(t&&(r==="scale")){s.push(r+"3d("+this[r]+",1)")}else{if(t&&(r==="translate")){s.push(r+"3d("+this[r]+",0)")}else{s.push(r+"("+this[r]+")")}}}}}return s.join(" ")}};function m(s,r,t){if(r===true){s.queue(t)}else{if(r){s.queue(r,t)}else{t()}}}function h(s){var r=[];k.each(s,function(t){t=k.camelCase(t);t=k.transit.propertyMap[t]||k.cssProps[t]||t;t=c(t);if(k.inArray(t,r)===-1){r.push(t)}});return r}function g(s,v,x,r){var t=h(s);if(k.cssEase[x]){x=k.cssEase[x]}var w=""+l(v)+" "+x;if(parseInt(r,10)>0){w+=" "+l(r)}var u=[];k.each(t,function(z,y){u.push(y+" "+w)});return u.join(", ")}k.fn.transition=k.fn.transit=function(z,s,y,C){var D=this;var u=0;var w=true;if(typeof s==="function"){C=s;s=undefined}if(typeof y==="function"){C=y;y=undefined}if(typeof z.easing!=="undefined"){y=z.easing;delete z.easing}if(typeof z.duration!=="undefined"){s=z.duration;delete z.duration}if(typeof z.complete!=="undefined"){C=z.complete;delete z.complete}if(typeof z.queue!=="undefined"){w=z.queue;delete z.queue}if(typeof z.delay!=="undefined"){u=z.delay;delete z.delay}if(typeof s==="undefined"){s=k.fx.speeds._default}if(typeof y==="undefined"){y=k.cssEase._default}s=l(s);var E=g(z,s,y,u);var B=k.transit.enabled&&q.transition;var t=B?(parseInt(s,10)+parseInt(u,10)):0;if(t===0){var A=function(F){D.css(z);if(C){C.apply(D)}if(F){F()}};m(D,w,A);return D}var x={};var r=function(H){var G=false;var F=function(){if(G){D.unbind(f,F)}if(t>0){D.each(function(){this.style[q.transition]=(x[this]||null)})}if(typeof C==="function"){C.apply(D)}if(typeof H==="function"){H()}};if((t>0)&&(f)&&(k.transit.useTransitionEnd)){G=true;D.bind(f,F)}else{window.setTimeout(F,t)}D.each(function(){if(t>0){this.style[q.transition]=E}k(this).css(z)})};var v=function(F){this.offsetWidth;r(F)};m(D,w,v);return this};function n(s,r){if(!r){k.cssNumber[s]=true}k.transit.propertyMap[s]=q.transform;k.cssHooks[s]={get:function(v){var u=k(v).css("transit:transform");return u.get(s)},set:function(v,w){var u=k(v).css("transit:transform");u.setFromString(s,w);k(v).css({"transit:transform":u})}}}function c(r){return r.replace(/([A-Z])/g,function(s){return"-"+s.toLowerCase()})}function o(s,r){if((typeof s==="string")&&(!s.match(/^[\-0-9\.]+$/))){return s}else{return""+s+r}}function l(s){var r=s;if(k.fx.speeds[r]){r=k.fx.speeds[r]}return o(r,"ms")}k.transit.getTransitionValue=g})(jQuery);
54/*!
55 * jQuery.ScrollTo
56 * Copyright (c) 2007-2014 Ariel Flesler - aflesler<a>gmail<d>com | http://flesler.blogspot.com
57 * Licensed under MIT
58 * http://flesler.blogspot.com/2007/10/jqueryscrollto.html
59 * @projectDescription Easy element scrolling using jQuery.
60 * @author Ariel Flesler
61 * @version 1.4.11
62 */
63
64;(function(plugin) {
65    // AMD Support
66    if (typeof define === 'function' && define.amd) {
67        define(['jquery'], plugin);
68    } else {
69        plugin(jQuery);
70    }
71}(function($) {
72
73	var $scrollTo = $.scrollTo = function( target, duration, settings ) {
74		return $(window).scrollTo( target, duration, settings );
75	};
76
77	$scrollTo.defaults = {
78		axis:'xy',
79		duration: parseFloat($.fn.jquery) >= 1.3 ? 0 : 1,
80		limit:true
81	};
82
83	// Returns the element that needs to be animated to scroll the window.
84	// Kept for backwards compatibility (specially for localScroll & serialScroll)
85	$scrollTo.window = function( scope ) {
86		return $(window)._scrollable();
87	};
88
89	// Hack, hack, hack :)
90	// Returns the real elements to scroll (supports window/iframes, documents and regular nodes)
91	$.fn._scrollable = function() {
92		return this.map(function() {
93			var elem = this,
94				isWin = !elem.nodeName || $.inArray( elem.nodeName.toLowerCase(), ['iframe','#document','html','body'] ) != -1;
95
96				if (!isWin)
97					return elem;
98
99			var doc = (elem.contentWindow || elem).document || elem.ownerDocument || elem;
100
101			return /webkit/i.test(navigator.userAgent) || doc.compatMode == 'BackCompat' ?
102				doc.body :
103				doc.documentElement;
104		});
105	};
106
107	$.fn.scrollTo = function( target, duration, settings ) {
108		if (typeof duration == 'object') {
109			settings = duration;
110			duration = 0;
111		}
112		if (typeof settings == 'function')
113			settings = { onAfter:settings };
114
115		if (target == 'max')
116			target = 9e9;
117
118		settings = $.extend( {}, $scrollTo.defaults, settings );
119		// Speed is still recognized for backwards compatibility
120		duration = duration || settings.duration;
121		// Make sure the settings are given right
122		settings.queue = settings.queue && settings.axis.length > 1;
123
124		if (settings.queue)
125			// Let's keep the overall duration
126			duration /= 2;
127		settings.offset = both( settings.offset );
128		settings.over = both( settings.over );
129
130		return this._scrollable().each(function() {
131			// Null target yields nothing, just like jQuery does
132			if (target == null) return;
133
134			var elem = this,
135				$elem = $(elem),
136				targ = target, toff, attr = {},
137				win = $elem.is('html,body');
138
139			switch (typeof targ) {
140				// A number will pass the regex
141				case 'number':
142				case 'string':
143					if (/^([+-]=?)?\d+(\.\d+)?(px|%)?$/.test(targ)) {
144						targ = both( targ );
145						// We are done
146						break;
147					}
148					// Relative selector, no break!
149					targ = $(targ,this);
150					if (!targ.length) return;
151				case 'object':
152					// DOMElement / jQuery
153					if (targ.is || targ.style)
154						// Get the real position of the target
155						toff = (targ = $(targ)).offset();
156			}
157			
158			var offset = $.isFunction(settings.offset) && settings.offset(elem, targ) || settings.offset;
159			
160			$.each( settings.axis.split(''), function( i, axis ) {
161				var Pos	= axis == 'x' ? 'Left' : 'Top',
162					pos = Pos.toLowerCase(),
163					key = 'scroll' + Pos,
164					old = elem[key],
165					max = $scrollTo.max(elem, axis);
166
167				if (toff) {// jQuery / DOMElement
168					attr[key] = toff[pos] + ( win ? 0 : old - $elem.offset()[pos] );
169
170					// If it's a dom element, reduce the margin
171					if (settings.margin) {
172						attr[key] -= parseInt(targ.css('margin'+Pos)) || 0;
173						attr[key] -= parseInt(targ.css('border'+Pos+'Width')) || 0;
174					}
175
176					attr[key] += offset[pos] || 0;
177
178					if(settings.over[pos])
179						// Scroll to a fraction of its width/height
180						attr[key] += targ[axis=='x'?'width':'height']() * settings.over[pos];
181				} else {
182					var val = targ[pos];
183					// Handle percentage values
184					attr[key] = val.slice && val.slice(-1) == '%' ?
185						parseFloat(val) / 100 * max
186						: val;
187				}
188
189				// Number or 'number'
190				if (settings.limit && /^\d+$/.test(attr[key]))
191					// Check the limits
192					attr[key] = attr[key] <= 0 ? 0 : Math.min( attr[key], max );
193
194				// Queueing axes
195				if (!i && settings.queue) {
196					// Don't waste time animating, if there's no need.
197					if (old != attr[key])
198						// Intermediate animation
199						animate( settings.onAfterFirst );
200					// Don't animate this axis again in the next iteration.
201					delete attr[key];
202				}
203			});
204
205			animate( settings.onAfter );
206
207			function animate( callback ) {
208				$elem.animate( attr, duration, settings.easing, callback && function() {
209					callback.call(this, targ, settings);
210				});
211			};
212
213		}).end();
214	};
215
216	// Max scrolling position, works on quirks mode
217	// It only fails (not too badly) on IE, quirks mode.
218	$scrollTo.max = function( elem, axis ) {
219		var Dim = axis == 'x' ? 'Width' : 'Height',
220			scroll = 'scroll'+Dim;
221
222		if (!$(elem).is('html,body'))
223			return elem[scroll] - $(elem)[Dim.toLowerCase()]();
224
225		var size = 'client' + Dim,
226			html = elem.ownerDocument.documentElement,
227			body = elem.ownerDocument.body;
228
229		return Math.max( html[scroll], body[scroll] )
230			 - Math.min( html[size]  , body[size]   );
231	};
232
233	function both( val ) {
234		return $.isFunction(val) || typeof val == 'object' ? val : { top:val, left:val };
235	};
236
237    // AMD requirement
238    return $scrollTo;
239}));
240
241(function($) {
242
243  // Matches trailing non-space characters.
244  var chop = /(\s*\S+|\s)$/;
245
246  // Return a truncated html string.  Delegates to $.fn.truncate.
247  $.truncate = function(html, options) {
248    return $('<div></div>').append(html).truncate(options).html();
249  };
250
251  // Truncate the contents of an element in place.
252  $.fn.truncate = function(options) {
253    if ($.isNumeric(options)) options = {length: options};
254    var o = $.extend({}, $.truncate.defaults, options);
255
256    return this.each(function() {
257      var self = $(this);
258
259      if (o.noBreaks) self.find('br').replaceWith(' ');
260
261      var text = self.text();
262      var excess = text.length - o.length;
263
264      if (o.stripTags) self.text(text);
265
266      // Chop off any partial words if appropriate.
267      if (o.words && excess > 0) {
268        excess = text.length - text.slice(0, o.length).replace(chop, '').length - 1;
269      }
270
271      if (excess < 0 || !excess && !o.truncated) return;
272
273      // Iterate over each child node in reverse, removing excess text.
274      $.each(self.contents().get().reverse(), function(i, el) {
275        var $el = $(el);
276        var text = $el.text();
277        var length = text.length;
278
279        // If the text is longer than the excess, remove the node and continue.
280        if (length <= excess) {
281          o.truncated = true;
282          excess -= length;
283          $el.remove();
284          return;
285        }
286
287        // Remove the excess text and append the ellipsis.
288        if (el.nodeType === 3) {
289          $(el.splitText(length - excess - 1)).replaceWith(o.ellipsis);
290          return false;
291        }
292
293        // Recursively truncate child nodes.
294        $el.truncate($.extend(o, {length: length - excess}));
295        return false;
296      });
297    });
298  };
299
300  $.truncate.defaults = {
301
302    // Strip all html elements, leaving only plain text.
303    stripTags: false,
304
305    // Only truncate at word boundaries.
306    words: false,
307
308    // Replace instances of <br> with a single space.
309    noBreaks: false,
310
311    // The maximum length of the truncated html.
312    length: Infinity,
313
314    // The character to use as the ellipsis.  The word joiner (U+2060) can be
315    // used to prevent a hanging ellipsis, but displays incorrectly in Chrome
316    // on Windows 7.
317    // http://code.google.com/p/chromium/issues/detail?id=68323
318    ellipsis: '\u2026' // '\u2060\u2026'
319
320  };
321
322})(jQuery);
323
324/*
325 *	jQuery dotdotdot 1.6.16
326 *
327 *	Copyright (c) Fred Heusschen
328 *	www.frebsite.nl
329 *
330 *	Plugin website:
331 *	dotdotdot.frebsite.nl
332 *
333 *	Dual licensed under the MIT and GPL licenses.
334 *	http://en.wikipedia.org/wiki/MIT_License
335 *	http://en.wikipedia.org/wiki/GNU_General_Public_License
336 */
337
338(function( $, undef )
339{
340	if ( $.fn.dotdotdot )
341	{
342		return;
343	}
344
345	$.fn.dotdotdot = function( o )
346	{
347		if ( this.length == 0 )
348		{
349			$.fn.dotdotdot.debug( 'No element found for "' + this.selector + '".' );
350			return this;
351		}
352		if ( this.length > 1 )
353		{
354			return this.each(
355				function()
356				{
357					$(this).dotdotdot( o );
358				}
359			);
360		}
361
362
363		var $dot = this;
364
365		if ( $dot.data( 'dotdotdot' ) )
366		{
367			$dot.trigger( 'destroy.dot' );
368		}
369
370		$dot.data( 'dotdotdot-style', $dot.attr( 'style' ) || '' );
371		$dot.css( 'word-wrap', 'break-word' );
372		if ($dot.css( 'white-space' ) === 'nowrap')
373		{
374			$dot.css( 'white-space', 'normal' );
375		}
376
377		$dot.bind_events = function()
378		{
379			$dot.bind(
380				'update.dot',
381				function( e, c )
382				{
383					e.preventDefault();
384					e.stopPropagation();
385
386					opts.maxHeight = ( typeof opts.height == 'number' )
387						? opts.height
388						: getTrueInnerHeight( $dot );
389
390					opts.maxHeight += opts.tolerance;
391
392					if ( typeof c != 'undefined' )
393					{
394						if ( typeof c == 'string' || c instanceof HTMLElement )
395						{
396					 		c = $('<div />').append( c ).contents();
397						}
398						if ( c instanceof $ )
399						{
400							orgContent = c;
401						}
402					}
403
404					$inr = $dot.wrapInner( '<div class="dotdotdot" />' ).children();
405					$inr.contents()
406						.detach()
407						.end()
408						.append( orgContent.clone( true ) )
409						.find( 'br' )
410						.replaceWith( '  <br />  ' )
411						.end()
412						.css({
413							'height'	: 'auto',
414							'width'		: 'auto',
415							'border'	: 'none',
416							'padding'	: 0,
417							'margin'	: 0
418						});
419
420					var after = false,
421						trunc = false;
422
423					if ( conf.afterElement )
424					{
425						after = conf.afterElement.clone( true );
426					    after.show();
427						conf.afterElement.detach();
428					}
429
430					if ( test( $inr, opts ) )
431					{
432						if ( opts.wrap == 'children' )
433						{
434							trunc = children( $inr, opts, after );
435						}
436						else
437						{
438							trunc = ellipsis( $inr, $dot, $inr, opts, after );
439						}
440					}
441					$inr.replaceWith( $inr.contents() );
442					$inr = null;
443
444					if ( $.isFunction( opts.callback ) )
445					{
446						opts.callback.call( $dot[ 0 ], trunc, orgContent );
447					}
448
449					conf.isTruncated = trunc;
450					return trunc;
451				}
452
453			).bind(
454				'isTruncated.dot',
455				function( e, fn )
456				{
457					e.preventDefault();
458					e.stopPropagation();
459
460					if ( typeof fn == 'function' )
461					{
462						fn.call( $dot[ 0 ], conf.isTruncated );
463					}
464					return conf.isTruncated;
465				}
466
467			).bind(
468				'originalContent.dot',
469				function( e, fn )
470				{
471					e.preventDefault();
472					e.stopPropagation();
473
474					if ( typeof fn == 'function' )
475					{
476						fn.call( $dot[ 0 ], orgContent );
477					}
478					return orgContent;
479				}
480
481			).bind(
482				'destroy.dot',
483				function( e )
484				{
485					e.preventDefault();
486					e.stopPropagation();
487
488					$dot.unwatch()
489						.unbind_events()
490						.contents()
491						.detach()
492						.end()
493						.append( orgContent )
494						.attr( 'style', $dot.data( 'dotdotdot-style' ) || '' )
495						.data( 'dotdotdot', false );
496				}
497			);
498			return $dot;
499		};	//	/bind_events
500
501		$dot.unbind_events = function()
502		{
503			$dot.unbind('.dot');
504			return $dot;
505		};	//	/unbind_events
506
507		$dot.watch = function()
508		{
509			$dot.unwatch();
510			if ( opts.watch == 'window' )
511			{
512				var $window = $(window),
513					_wWidth = $window.width(),
514					_wHeight = $window.height();
515
516				$window.bind(
517					'resize.dot' + conf.dotId,
518					function()
519					{
520						if ( _wWidth != $window.width() || _wHeight != $window.height() || !opts.windowResizeFix )
521						{
522							_wWidth = $window.width();
523							_wHeight = $window.height();
524
525							if ( watchInt )
526							{
527								clearInterval( watchInt );
528							}
529							watchInt = setTimeout(
530								function()
531								{
532									$dot.trigger( 'update.dot' );
533								}, 100
534							);
535						}
536					}
537				);
538			}
539			else
540			{
541				watchOrg = getSizes( $dot );
542				watchInt = setInterval(
543					function()
544					{
545						if ( $dot.is( ':visible' ) )
546						{
547							var watchNew = getSizes( $dot );
548							if ( watchOrg.width  != watchNew.width ||
549								 watchOrg.height != watchNew.height )
550							{
551								$dot.trigger( 'update.dot' );
552								watchOrg = watchNew;
553							}
554						}
555					}, 500
556				);
557			}
558			return $dot;
559		};
560		$dot.unwatch = function()
561		{
562			$(window).unbind( 'resize.dot' + conf.dotId );
563			if ( watchInt )
564			{
565				clearInterval( watchInt );
566			}
567			return $dot;
568		};
569
570		var	orgContent	= $dot.contents(),
571			opts 		= $.extend( true, {}, $.fn.dotdotdot.defaults, o ),
572			conf		= {},
573			watchOrg	= {},
574			watchInt	= null,
575			$inr		= null;
576
577
578		if ( !( opts.lastCharacter.remove instanceof Array ) )
579		{
580			opts.lastCharacter.remove = $.fn.dotdotdot.defaultArrays.lastCharacter.remove;
581		}
582		if ( !( opts.lastCharacter.noEllipsis instanceof Array ) )
583		{
584			opts.lastCharacter.noEllipsis = $.fn.dotdotdot.defaultArrays.lastCharacter.noEllipsis;
585		}
586
587
588		conf.afterElement	= getElement( opts.after, $dot );
589		conf.isTruncated	= false;
590		conf.dotId			= dotId++;
591
592
593		$dot.data( 'dotdotdot', true )
594			.bind_events()
595			.trigger( 'update.dot' );
596
597		if ( opts.watch )
598		{
599			$dot.watch();
600		}
601
602		return $dot;
603	};
604
605
606	//	public
607	$.fn.dotdotdot.defaults = {
608		'ellipsis'			: '... ',
609		'wrap'				: 'word',
610		'fallbackToLetter'	: true,
611		'lastCharacter'		: {},
612		'tolerance'			: 0,
613		'callback'			: null,
614		'after'				: null,
615		'height'			: null,
616		'watch'				: false,
617		'windowResizeFix'	: true
618	};
619	$.fn.dotdotdot.defaultArrays = {
620		'lastCharacter'		: {
621			'remove'			: [ ' ', '\u3000', ',', ';', '.', '!', '?' ],
622			'noEllipsis'		: []
623		}
624	};
625	$.fn.dotdotdot.debug = function( msg ) {};
626
627
628	//	private
629	var dotId = 1;
630
631	function children( $elem, o, after )
632	{
633		var $elements 	= $elem.children(),
634			isTruncated	= false;
635
636		$elem.empty();
637
638		for ( var a = 0, l = $elements.length; a < l; a++ )
639		{
640			var $e = $elements.eq( a );
641			$elem.append( $e );
642			if ( after )
643			{
644				$elem.append( after );
645			}
646			if ( test( $elem, o ) )
647			{
648				$e.remove();
649				isTruncated = true;
650				break;
651			}
652			else
653			{
654				if ( after )
655				{
656					after.detach();
657				}
658			}
659		}
660		return isTruncated;
661	}
662	function ellipsis( $elem, $d, $i, o, after )
663	{
664		var isTruncated	= false;
665
666		//	Don't put the ellipsis directly inside these elements
667		var notx = 'table, thead, tbody, tfoot, tr, col, colgroup, object, embed, param, ol, ul, dl, blockquote, select, optgroup, option, textarea, script, style';
668
669		//	Don't remove these elements even if they are after the ellipsis
670		var noty = 'script, .dotdotdot-keep';
671
672		$elem
673			.contents()
674			.detach()
675			.each(
676				function()
677				{
678
679					var e	= this,
680						$e	= $(e);
681
682					if ( typeof e == 'undefined' || ( e.nodeType == 3 && $.trim( e.data ).length == 0 ) )
683					{
684						return true;
685					}
686					else if ( $e.is( noty ) )
687					{
688						$elem.append( $e );
689					}
690					else if ( isTruncated )
691					{
692						return true;
693					}
694					else
695					{
696						$elem.append( $e );
697						if ( after )
698						{
699							$elem[ $elem.is( notx ) ? 'after' : 'append' ]( after );
700						}
701						if ( test( $i, o ) )
702						{
703							if ( e.nodeType == 3 ) // node is TEXT
704							{
705								isTruncated = ellipsisElement( $e, $d, $i, o, after );
706							}
707							else
708							{
709								isTruncated = ellipsis( $e, $d, $i, o, after );
710							}
711
712							if ( !isTruncated )
713							{
714								$e.detach();
715								isTruncated = true;
716							}
717						}
718
719						if ( !isTruncated )
720						{
721							if ( after )
722							{
723								after.detach();
724							}
725						}
726					}
727				}
728			);
729
730		return isTruncated;
731	}
732	function ellipsisElement( $e, $d, $i, o, after )
733	{
734		var e = $e[ 0 ];
735
736		if ( !e )
737		{
738			return false;
739		}
740
741		var txt			= getTextContent( e ),
742			space		= ( txt.indexOf(' ') !== -1 ) ? ' ' : '\u3000',
743			separator	= ( o.wrap == 'letter' ) ? '' : space,
744			textArr		= txt.split( separator ),
745			position 	= -1,
746			midPos		= -1,
747			startPos	= 0,
748			endPos		= textArr.length - 1;
749
750
751		//	Only one word
752		if ( o.fallbackToLetter && startPos == 0 && endPos == 0 )
753		{
754			separator	= '';
755			textArr		= txt.split( separator );
756			endPos		= textArr.length - 1;
757		}
758
759		while ( startPos <= endPos && !( startPos == 0 && endPos == 0 ) )
760		{
761			var m = Math.floor( ( startPos + endPos ) / 2 );
762			if ( m == midPos )
763			{
764				break;
765			}
766			midPos = m;
767
768			setTextContent( e, textArr.slice( 0, midPos + 1 ).join( separator ) + o.ellipsis );
769
770			if ( !test( $i, o ) )
771			{
772				position = midPos;
773				startPos = midPos;
774			}
775			else
776			{
777				endPos = midPos;
778
779				//	Fallback to letter
780				if (o.fallbackToLetter && startPos == 0 && endPos == 0 )
781				{
782					separator	= '';
783					textArr		= textArr[ 0 ].split( separator );
784					position	= -1;
785					midPos		= -1;
786					startPos	= 0;
787					endPos		= textArr.length - 1;
788				}
789			}
790		}
791
792		if ( position != -1 && !( textArr.length == 1 && textArr[ 0 ].length == 0 ) )
793		{
794			txt = addEllipsis( textArr.slice( 0, position + 1 ).join( separator ), o );
795			setTextContent( e, txt );
796		}
797		else
798		{
799			var $w = $e.parent();
800			$e.detach();
801
802			var afterLength = ( after && after.closest($w).length ) ? after.length : 0;
803
804			if ( $w.contents().length > afterLength )
805			{
806				e = findLastTextNode( $w.contents().eq( -1 - afterLength ), $d );
807			}
808			else
809			{
810				e = findLastTextNode( $w, $d, true );
811				if ( !afterLength )
812				{
813					$w.detach();
814				}
815			}
816			if ( e )
817			{
818				txt = addEllipsis( getTextContent( e ), o );
819				setTextContent( e, txt );
820				if ( afterLength && after )
821				{
822					$(e).parent().append( after );
823				}
824			}
825		}
826
827		return true;
828	}
829	function test( $i, o )
830	{
831		return $i.innerHeight() > o.maxHeight;
832	}
833	function addEllipsis( txt, o )
834	{
835		while( $.inArray( txt.slice( -1 ), o.lastCharacter.remove ) > -1 )
836		{
837			txt = txt.slice( 0, -1 );
838		}
839		if ( $.inArray( txt.slice( -1 ), o.lastCharacter.noEllipsis ) < 0 )
840		{
841			txt += o.ellipsis;
842		}
843		return txt;
844	}
845	function getSizes( $d )
846	{
847		return {
848			'width'	: $d.innerWidth(),
849			'height': $d.innerHeight()
850		};
851	}
852	function setTextContent( e, content )
853	{
854		if ( e.innerText )
855		{
856			e.innerText = content;
857		}
858		else if ( e.nodeValue )
859		{
860			e.nodeValue = content;
861		}
862		else if (e.textContent)
863		{
864			e.textContent = content;
865		}
866
867	}
868	function getTextContent( e )
869	{
870		if ( e.innerText )
871		{
872			return e.innerText;
873		}
874		else if ( e.nodeValue )
875		{
876			return e.nodeValue;
877		}
878		else if ( e.textContent )
879		{
880			return e.textContent;
881		}
882		else
883		{
884			return "";
885		}
886	}
887	function getPrevNode( n )
888	{
889		do
890		{
891			n = n.previousSibling;
892		}
893		while ( n && n.nodeType !== 1 && n.nodeType !== 3 );
894
895		return n;
896	}
897	function findLastTextNode( $el, $top, excludeCurrent )
898	{
899		var e = $el && $el[ 0 ], p;
900		if ( e )
901		{
902			if ( !excludeCurrent )
903			{
904				if ( e.nodeType === 3 )
905				{
906					return e;
907				}
908				if ( $.trim( $el.text() ) )
909				{
910					return findLastTextNode( $el.contents().last(), $top );
911				}
912			}
913			p = getPrevNode( e );
914			while ( !p )
915			{
916				$el = $el.parent();
917				if ( $el.is( $top ) || !$el.length )
918				{
919					return false;
920				}
921				p = getPrevNode( $el[0] );
922			}
923			if ( p )
924			{
925				return findLastTextNode( $(p), $top );
926			}
927		}
928		return false;
929	}
930	function getElement( e, $i )
931	{
932		if ( !e )
933		{
934			return false;
935		}
936		if ( typeof e === 'string' )
937		{
938			e = $(e, $i);
939			return ( e.length )
940				? e
941				: false;
942		}
943		return !e.jquery
944			? false
945			: e;
946	}
947	function getTrueInnerHeight( $el )
948	{
949		var h = $el.innerHeight(),
950			a = [ 'paddingTop', 'paddingBottom' ];
951
952		for ( var z = 0, l = a.length; z < l; z++ )
953		{
954			var m = parseInt( $el.css( a[ z ] ), 10 );
955			if ( isNaN( m ) )
956			{
957				m = 0;
958			}
959			h -= m;
960		}
961		return h;
962	}
963
964
965	//	override jQuery.html
966	var _orgHtml = $.fn.html;
967	$.fn.html = function( str )
968	{
969		if ( str != undef && !$.isFunction( str ) && this.data( 'dotdotdot' ) )
970		{
971			return this.trigger( 'update', [ str ] );
972		}
973		return _orgHtml.apply( this, arguments );
974	};
975
976
977	//	override jQuery.text
978	var _orgText = $.fn.text;
979	$.fn.text = function( str )
980	{
981		if ( str != undef && !$.isFunction( str ) && this.data( 'dotdotdot' ) )
982		{
983			str = $( '<div />' ).text( str ).html();
984			return this.trigger( 'update', [ str ] );
985		}
986		return _orgText.apply( this, arguments );
987	};
988
989
990})( jQuery );
991
992/* ========================================================================
993 * Bootstrap: carousel.js v3.0.0
994 * http://twbs.github.com/bootstrap/javascript.html#carousel
995 * ========================================================================
996 * Copyright 2012 Twitter, Inc.
997 *
998 * Licensed under the Apache License, Version 2.0 (the "License");
999 * you may not use this file except in compliance with the License.
1000 * You may obtain a copy of the License at
1001 *
1002 * http://www.apache.org/licenses/LICENSE-2.0
1003 *
1004 * Unless required by applicable law or agreed to in writing, software
1005 * distributed under the License is distributed on an "AS IS" BASIS,
1006 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1007 * See the License for the specific language governing permissions and
1008 * limitations under the License.
1009 * ======================================================================== */
1010
1011
1012+function ($) { "use strict";
1013
1014  // CAROUSEL CLASS DEFINITION
1015  // =========================
1016
1017  var Carousel = function (element, options) {
1018    this.$element    = $(element)
1019    this.$indicators = this.$element.find('.carousel-indicators')
1020    this.options     = options
1021    this.paused      =
1022    this.sliding     =
1023    this.interval    =
1024    this.$active     =
1025    this.$items      = null
1026
1027    this.options.pause == 'hover' && this.$element
1028      .on('mouseenter', $.proxy(this.pause, this))
1029      .on('mouseleave', $.proxy(this.cycle, this))
1030  }
1031
1032  Carousel.DEFAULTS = {
1033    interval: 5000
1034  , pause: 'hover'
1035  , wrap: true
1036  }
1037
1038  Carousel.prototype.cycle =  function (e) {
1039    e || (this.paused = false)
1040
1041    this.interval && clearInterval(this.interval)
1042
1043    this.options.interval
1044      && !this.paused
1045      && (this.interval = setInterval($.proxy(this.next, this), this.options.interval))
1046
1047    return this
1048  }
1049
1050  Carousel.prototype.getActiveIndex = function () {
1051    this.$active = this.$element.find('.item.active')
1052    this.$items  = this.$active.parent().children()
1053
1054    return this.$items.index(this.$active)
1055  }
1056
1057  Carousel.prototype.to = function (pos) {
1058    var that        = this
1059    var activeIndex = this.getActiveIndex()
1060
1061    if (pos > (this.$items.length - 1) || pos < 0) return
1062
1063    if (this.sliding)       return this.$element.one('slid', function () { that.to(pos) })
1064    if (activeIndex == pos) return this.pause().cycle()
1065
1066    return this.slide(pos > activeIndex ? 'next' : 'prev', $(this.$items[pos]))
1067  }
1068
1069  Carousel.prototype.pause = function (e) {
1070    e || (this.paused = true)
1071
1072    if (this.$element.find('.next, .prev').length && $.support.transition.end) {
1073      this.$element.trigger($.support.transition.end)
1074      this.cycle(true)
1075    }
1076
1077    this.interval = clearInterval(this.interval)
1078
1079    return this
1080  }
1081
1082  Carousel.prototype.next = function () {
1083    if (this.sliding) return
1084    return this.slide('next')
1085  }
1086
1087  Carousel.prototype.prev = function () {
1088    if (this.sliding) return
1089    return this.slide('prev')
1090  }
1091
1092  Carousel.prototype.slide = function (type, next) {
1093    var $active   = this.$element.find('.item.active')
1094    var $next     = next || $active[type]()
1095    var isCycling = this.interval
1096    var direction = type == 'next' ? 'left' : 'right'
1097    var fallback  = type == 'next' ? 'first' : 'last'
1098    var that      = this
1099    
1100    if (!$next.length) {
1101      if (!this.options.wrap) return
1102      $next = this.$element.find('.item')[fallback]()
1103    }
1104
1105    this.sliding = true
1106
1107    isCycling && this.pause()
1108
1109    var e = $.Event('slide.bs.carousel', { relatedTarget: $next[0], direction: direction })
1110
1111    if ($next.hasClass('active')) return
1112
1113    if (this.$indicators.length) {
1114      this.$indicators.find('.active').removeClass('active')
1115      this.$element.one('slid', function () {
1116        var $nextIndicator = $(that.$indicators.children()[that.getActiveIndex()])
1117        $nextIndicator && $nextIndicator.addClass('active')
1118      })
1119    }
1120
1121    if ($.support.transition && this.$element.hasClass('slide')) {
1122      this.$element.trigger(e)
1123      if (e.isDefaultPrevented()) return
1124      $next.addClass(type)
1125      $next[0].offsetWidth // force reflow
1126      $active.addClass(direction)
1127      $next.addClass(direction)
1128      $active
1129        .one($.support.transition.end, function () {
1130          $next.removeClass([type, direction].join(' ')).addClass('active')
1131          $active.removeClass(['active', direction].join(' '))
1132          that.sliding = false
1133          setTimeout(function () { that.$element.trigger('slid') }, 0)
1134        })
1135        .emulateTransitionEnd(600)
1136    } else if(this.$element.hasClass('slide')) {
1137        this.$element.trigger(e)
1138        if (e.isDefaultPrevented()) return
1139        $active.animate({left: (direction == 'right' ? '100%' : '-100%')}, 600, function(){
1140            $active.removeClass('active')
1141            that.sliding = false
1142            setTimeout(function () { that.$element.trigger('slid') }, 0)
1143        })
1144        $next.addClass(type).css({left: (direction == 'right' ? '-100%' : '100%')}).animate({left: 0}, 600,  function(){
1145            $next.removeClass(type).addClass('active')
1146        })
1147    } else {
1148      this.$element.trigger(e)
1149      if (e.isDefaultPrevented()) return
1150      $active.removeClass('active')
1151      $next.addClass('active')
1152      this.sliding = false
1153      this.$element.trigger('slid')
1154    }
1155
1156    isCycling && this.cycle()
1157
1158    return this
1159  }
1160
1161
1162  // CAROUSEL PLUGIN DEFINITION
1163  // ==========================
1164
1165  var old = $.fn.carousel
1166
1167  $.fn.carousel = function (option) {
1168    return this.each(function () {
1169      var $this   = $(this)
1170      var data    = $this.data('bs.carousel')
1171      var options = $.extend({}, Carousel.DEFAULTS, $this.data(), typeof option == 'object' && option)
1172      var action  = typeof option == 'string' ? option : options.slide
1173
1174      if (!data) $this.data('bs.carousel', (data = new Carousel(this, options)))
1175      if (typeof option == 'number') data.to(option)
1176      else if (action) data[action]()
1177      else if (options.interval) data.pause().cycle()
1178    })
1179  }
1180
1181  $.fn.carousel.Constructor = Carousel
1182
1183
1184  // CAROUSEL NO CONFLICT
1185  // ====================
1186
1187  $.fn.carousel.noConflict = function () {
1188    $.fn.carousel = old
1189    return this
1190  }
1191
1192
1193  // CAROUSEL DATA-API
1194  // =================
1195
1196  $(document).on('click.bs.carousel.data-api', '[data-slide], [data-slide-to]', function (e) {
1197    var $this   = $(this), href
1198    var $target = $($this.attr('data-target') || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '')) //strip for ie7
1199    var options = $.extend({}, $target.data(), $this.data())
1200    var slideIndex = $this.attr('data-slide-to')
1201    if (slideIndex) options.interval = false
1202
1203    $target.carousel(options)
1204
1205    if (slideIndex = $this.attr('data-slide-to')) {
1206      $target.data('bs.carousel').to(slideIndex)
1207    }
1208
1209    e.preventDefault()
1210  })
1211
1212  $(window).on('load', function () {
1213    $('[data-ride="carousel"]').each(function () {
1214      var $carousel = $(this)
1215      $carousel.carousel($carousel.data())
1216    })
1217  })
1218
1219}(window.jQuery);
1220
vendor: 253,669 bytes, lines 1221-1233
1221/*! jQuery UI - v1.12.1 - 2016-09-14
1222* http://jqueryui.com
1223* Includes: widget.js, position.js, data.js, disable-selection.js, effect.js, effects/effect-blind.js, effects/effect-bounce.js, effects/effect-clip.js, effects/effect-drop.js, effects/effect-explode.js, effects/effect-fade.js, effects/effect-fold.js, effects/effect-highlight.js, effects/effect-puff.js, effects/effect-pulsate.js, effects/effect-scale.js, effects/effect-shake.js, effects/effect-size.js, effects/effect-slide.js, effects/effect-transfer.js, focusable.js, form-reset-mixin.js, jquery-1-7.js, keycode.js, labels.js, scroll-parent.js, tabbable.js, unique-id.js, widgets/accordion.js, widgets/autocomplete.js, widgets/button.js, widgets/checkboxradio.js, widgets/controlgroup.js, widgets/datepicker.js, widgets/dialog.js, widgets/draggable.js, widgets/droppable.js, widgets/menu.js, widgets/mouse.js, widgets/progressbar.js, widgets/resizable.js, widgets/selectable.js, widgets/selectmenu.js, widgets/slider.js, widgets/sortable.js, widgets/spinner.js, widgets/tabs.js, widgets/tooltip.js
1224* Copyright jQuery Foundation and other contributors; Licensed MIT */
1225
1226(function(t){"function"==typeof define&&define.amd?define(["jquery"],t):t(jQuery)})(function(t){function e(t){for(var e=t.css("visibility");"inherit"===e;)t=t.parent(),e=t.css("visibility");return"hidden"!==e}function i(t){for(var e,i;t.length&&t[0]!==document;){if(e=t.css("position"),("absolute"===e||"relative"===e||"fixed"===e)&&(i=parseInt(t.css("zIndex"),10),!isNaN(i)&&0!==i))return i;t=t.parent()}return 0}function s(){this._curInst=null,this._keyEvent=!1,this._disabledInputs=[],this._datepickerShowing=!1,this._inDialog=!1,this._mainDivId="ui-datepicker-div",this._inlineClass="ui-datepicker-inline",this._appendClass="ui-datepicker-append",this._triggerClass="ui-datepicker-trigger",this._dialogClass="ui-datepicker-dialog",this._disableClass="ui-datepicker-disabled",this._unselectableClass="ui-datepicker-unselectable",this._currentClass="ui-datepicker-current-day",this._dayOverClass="ui-datepicker-days-cell-over",this.regional=[],this.regional[""]={closeText:"Done",prevText:"Prev",nextText:"Next",currentText:"Today",monthNames:["January","February","March","April","May","June","July","August","September","October","November","December"],monthNamesShort:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],dayNames:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],dayNamesShort:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],dayNamesMin:["Su","Mo","Tu","We","Th","Fr","Sa"],weekHeader:"Wk",dateFormat:"mm/dd/yy",firstDay:0,isRTL:!1,showMonthAfterYear:!1,yearSuffix:""},this._defaults={showOn:"focus",showAnim:"fadeIn",showOptions:{},defaultDate:null,appendText:"",buttonText:"...",buttonImage:"",buttonImageOnly:!1,hideIfNoPrevNext:!1,navigationAsDateFormat:!1,gotoCurrent:!1,changeMonth:!1,changeYear:!1,yearRange:"c-10:c+10",showOtherMonths:!1,selectOtherMonths:!1,showWeek:!1,calculateWeek:this.iso8601Week,shortYearCutoff:"+10",minDate:null,maxDate:null,duration:"fast",beforeShowDay:null,beforeShow:null,onSelect:null,onChangeMonthYear:null,onClose:null,numberOfMonths:1,showCurrentAtPos:0,stepMonths:1,stepBigMonths:12,altField:"",altFormat:"",constrainInput:!0,showButtonPanel:!1,autoSize:!1,disabled:!1},t.extend(this._defaults,this.regional[""]),this.regional.en=t.extend(!0,{},this.regional[""]),this.regional["en-US"]=t.extend(!0,{},this.regional.en),this.dpDiv=n(t("<div id='"+this._mainDivId+"' class='ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all'></div>"))}function n(e){var i="button, .ui-datepicker-prev, .ui-datepicker-next, .ui-datepicker-calendar td a";return e.on("mouseout",i,function(){t(this).removeClass("ui-state-hover"),-1!==this.className.indexOf("ui-datepicker-prev")&&t(this).removeClass("ui-datepicker-prev-hover"),-1!==this.className.indexOf("ui-datepicker-next")&&t(this).removeClass("ui-datepicker-next-hover")}).on("mouseover",i,o)}function o(){t.datepicker._isDisabledDatepicker(m.inline?m.dpDiv.parent()[0]:m.input[0])||(t(this).parents(".ui-datepicker-calendar").find("a").removeClass("ui-state-hover"),t(this).addClass("ui-state-hover"),-1!==this.className.indexOf("ui-datepicker-prev")&&t(this).addClass("ui-datepicker-prev-hover"),-1!==this.className.indexOf("ui-datepicker-next")&&t(this).addClass("ui-datepicker-next-hover"))}function a(e,i){t.extend(e,i);for(var s in i)null==i[s]&&(e[s]=i[s]);return e}function r(t){return function(){var e=this.element.val();t.apply(this,arguments),this._refresh(),e!==this.element.val()&&this._trigger("change")}}t.ui=t.ui||{},t.ui.version="1.12.1";var h=0,l=Array.prototype.slice;t.cleanData=function(e){return function(i){var s,n,o;for(o=0;null!=(n=i[o]);o++)try{s=t._data(n,"events"),s&&s.remove&&t(n).triggerHandler("remove")}catch(a){}e(i)}}(t.cleanData),t.widget=function(e,i,s){var n,o,a,r={},h=e.split(".")[0];e=e.split(".")[1];var l=h+"-"+e;return s||(s=i,i=t.Widget),t.isArray(s)&&(s=t.extend.apply(null,[{}].concat(s))),t.expr[":"][l.toLowerCase()]=function(e){return!!t.data(e,l)},t[h]=t[h]||{},n=t[h][e],o=t[h][e]=function(t,e){return this._createWidget?(arguments.length&&this._createWidget(t,e),void 0):new o(t,e)},t.extend(o,n,{version:s.version,_proto:t.extend({},s),_childConstructors:[]}),a=new i,a.options=t.widget.extend({},a.options),t.each(s,function(e,s){return t.isFunction(s)?(r[e]=function(){function t(){return i.prototype[e].apply(this,arguments)}function n(t){return i.prototype[e].apply(this,t)}return function(){var e,i=this._super,o=this._superApply;return this._super=t,this._superApply=n,e=s.apply(this,arguments),this._super=i,this._superApply=o,e}}(),void 0):(r[e]=s,void 0)}),o.prototype=t.widget.extend(a,{widgetEventPrefix:n?a.widgetEventPrefix||e:e},r,{constructor:o,namespace:h,widgetName:e,widgetFullName:l}),n?(t.each(n._childConstructors,function(e,i){var s=i.prototype;t.widget(s.namespace+"."+s.widgetName,o,i._proto)}),delete n._childConstructors):i._childConstructors.push(o),t.widget.bridge(e,o),o},t.widget.extend=function(e){for(var i,s,n=l.call(arguments,1),o=0,a=n.length;a>o;o++)for(i in n[o])s=n[o][i],n[o].hasOwnProperty(i)&&void 0!==s&&(e[i]=t.isPlainObject(s)?t.isPlainObject(e[i])?t.widget.extend({},e[i],s):t.widget.extend({},s):s);return e},t.widget.bridge=function(e,i){var s=i.prototype.widgetFullName||e;t.fn[e]=function(n){var o="string"==typeof n,a=l.call(arguments,1),r=this;return o?this.length||"instance"!==n?this.each(function(){var i,o=t.data(this,s);return"instance"===n?(r=o,!1):o?t.isFunction(o[n])&&"_"!==n.charAt(0)?(i=o[n].apply(o,a),i!==o&&void 0!==i?(r=i&&i.jquery?r.pushStack(i.get()):i,!1):void 0):t.error("no such method '"+n+"' for "+e+" widget instance"):t.error("cannot call methods on "+e+" prior to initialization; "+"attempted to call method '"+n+"'")}):r=void 0:(a.length&&(n=t.widget.extend.apply(null,[n].concat(a))),this.each(function(){var e=t.data(this,s);e?(e.option(n||{}),e._init&&e._init()):t.data(this,s,new i(n,this))})),r}},t.Widget=function(){},t.Widget._childConstructors=[],t.Widget.prototype={widgetName:"widget",widgetEventPrefix:"",defaultElement:"<div>",options:{classes:{},disabled:!1,create:null},_createWidget:function(e,i){i=t(i||this.defaultElement||this)[0],this.element=t(i),this.uuid=h++,this.eventNamespace="."+this.widgetName+this.uuid,this.bindings=t(),this.hoverable=t(),this.focusable=t(),this.classesElementLookup={},i!==this&&(t.data(i,this.widgetFullName,this),this._on(!0,this.element,{remove:function(t){t.target===i&&this.destroy()}}),this.document=t(i.style?i.ownerDocument:i.document||i),this.window=t(this.document[0].defaultView||this.document[0].parentWindow)),this.options=t.widget.extend({},this.options,this._getCreateOptions(),e),this._create(),this.options.disabled&&this._setOptionDisabled(this.options.disabled),this._trigger("create",null,this._getCreateEventData()),this._init()},_getCreateOptions:function(){return{}},_getCreateEventData:t.noop,_create:t.noop,_init:t.noop,destroy:function(){var e=this;this._destroy(),t.each(this.classesElementLookup,function(t,i){e._removeClass(i,t)}),this.element.off(this.eventNamespace).removeData(this.widgetFullName),this.widget().off(this.eventNamespace).removeAttr("aria-disabled"),this.bindings.off(this.eventNamespace)},_destroy:t.noop,widget:function(){return this.element},option:function(e,i){var s,n,o,a=e;if(0===arguments.length)return t.widget.extend({},this.options);if("string"==typeof e)if(a={},s=e.split("."),e=s.shift(),s.length){for(n=a[e]=t.widget.extend({},this.options[e]),o=0;s.length-1>o;o++)n[s[o]]=n[s[o]]||{},n=n[s[o]];if(e=s.pop(),1===arguments.length)return void 0===n[e]?null:n[e];n[e]=i}else{if(1===arguments.length)return void 0===this.options[e]?null:this.options[e];a[e]=i}return this._setOptions(a),this},_setOptions:function(t){var e;for(e in t)this._setOption(e,t[e]);return this},_setOption:function(t,e){return"classes"===t&&this._setOptionClasses(e),this.options[t]=e,"disabled"===t&&this._setOptionDisabled(e),this},_setOptionClasses:function(e){var i,s,n;for(i in e)n=this.classesElementLookup[i],e[i]!==this.options.classes[i]&&n&&n.length&&(s=t(n.get()),this._removeClass(n,i),s.addClass(this._classes({element:s,keys:i,classes:e,add:!0})))},_setOptionDisabled:function(t){this._toggleClass(this.widget(),this.widgetFullName+"-disabled",null,!!t),t&&(this._removeClass(this.hoverable,null,"ui-state-hover"),this._removeClass(this.focusable,null,"ui-state-focus"))},enable:function(){return this._setOptions({disabled:!1})},disable:function(){return this._setOptions({disabled:!0})},_classes:function(e){function i(i,o){var a,r;for(r=0;i.length>r;r++)a=n.classesElementLookup[i[r]]||t(),a=e.add?t(t.unique(a.get().concat(e.element.get()))):t(a.not(e.element).get()),n.classesElementLookup[i[r]]=a,s.push(i[r]),o&&e.classes[i[r]]&&s.push(e.classes[i[r]])}var s=[],n=this;return e=t.extend({element:this.element,classes:this.options.classes||{}},e),this._on(e.element,{remove:"_untrackClassesElement"}),e.keys&&i(e.keys.match(/\S+/g)||[],!0),e.extra&&i(e.extra.match(/\S+/g)||[]),s.join(" ")},_untrackClassesElement:function(e){var i=this;t.each(i.classesElementLookup,function(s,n){-1!==t.inArray(e.target,n)&&(i.classesElementLookup[s]=t(n.not(e.target).get()))})},_removeClass:function(t,e,i){return this._toggleClass(t,e,i,!1)},_addClass:function(t,e,i){return this._toggleClass(t,e,i,!0)},_toggleClass:function(t,e,i,s){s="boolean"==typeof s?s:i;var n="string"==typeof t||null===t,o={extra:n?e:i,keys:n?t:e,element:n?this.element:t,add:s};return o.element.toggleClass(this._classes(o),s),this},_on:function(e,i,s){var n,o=this;"boolean"!=typeof e&&(s=i,i=e,e=!1),s?(i=n=t(i),this.bindings=this.bindings.add(i)):(s=i,i=this.element,n=this.widget()),t.each(s,function(s,a){function r(){return e||o.options.disabled!==!0&&!t(this).hasClass("ui-state-disabled")?("string"==typeof a?o[a]:a).apply(o,arguments):void 0}"string"!=typeof a&&(r.guid=a.guid=a.guid||r.guid||t.guid++);var h=s.match(/^([\w:-]*)\s*(.*)$/),l=h[1]+o.eventNamespace,c=h[2];c?n.on(l,c,r):i.on(l,r)})},_off:function(e,i){i=(i||"").split(" ").join(this.eventNamespace+" ")+this.eventNamespace,e.off(i).off(i),this.bindings=t(this.bindings.not(e).get()),this.focusable=t(this.focusable.not(e).get()),this.hoverable=t(this.hoverable.not(e).get())},_delay:function(t,e){function i(){return("string"==typeof t?s[t]:t).apply(s,arguments)}var s=this;return setTimeout(i,e||0)},_hoverable:function(e){this.hoverable=this.hoverable.add(e),this._on(e,{mouseenter:function(e){this._addClass(t(e.currentTarget),null,"ui-state-hover")},mouseleave:function(e){this._removeClass(t(e.currentTarget),null,"ui-state-hover")}})},_focusable:function(e){this.focusable=this.focusable.add(e),this._on(e,{focusin:function(e){this._addClass(t(e.currentTarget),null,"ui-state-focus")},focusout:function(e){this._removeClass(t(e.currentTarget),null,"ui-state-focus")}})},_trigger:function(e,i,s){var n,o,a=this.options[e];if(s=s||{},i=t.Event(i),i.type=(e===this.widgetEventPrefix?e:this.widgetEventPrefix+e).toLowerCase(),i.target=this.element[0],o=i.originalEvent)for(n in o)n in i||(i[n]=o[n]);return this.element.trigger(i,s),!(t.isFunction(a)&&a.apply(this.element[0],[i].concat(s))===!1||i.isDefaultPrevented())}},t.each({show:"fadeIn",hide:"fadeOut"},function(e,i){t.Widget.prototype["_"+e]=function(s,n,o){"string"==typeof n&&(n={effect:n});var a,r=n?n===!0||"number"==typeof n?i:n.effect||i:e;n=n||{},"number"==typeof n&&(n={duration:n}),a=!t.isEmptyObject(n),n.complete=o,n.delay&&s.delay(n.delay),a&&t.effects&&t.effects.effect[r]?s[e](n):r!==e&&s[r]?s[r](n.duration,n.easing,o):s.queue(function(i){t(this)[e](),o&&o.call(s[0]),i()})}}),t.widget,function(){function e(t,e,i){return[parseFloat(t[0])*(u.test(t[0])?e/100:1),parseFloat(t[1])*(u.test(t[1])?i/100:1)]}function i(e,i){return parseInt(t.css(e,i),10)||0}function s(e){var i=e[0];return 9===i.nodeType?{width:e.width(),height:e.height(),offset:{top:0,left:0}}:t.isWindow(i)?{width:e.width(),height:e.height(),offset:{top:e.scrollTop(),left:e.scrollLeft()}}:i.preventDefault?{width:0,height:0,offset:{top:i.pageY,left:i.pageX}}:{width:e.outerWidth(),height:e.outerHeight(),offset:e.offset()}}var n,o=Math.max,a=Math.abs,r=/left|center|right/,h=/top|center|bottom/,l=/[\+\-]\d+(\.[\d]+)?%?/,c=/^\w+/,u=/%$/,d=t.fn.position;t.position={scrollbarWidth:function(){if(void 0!==n)return n;var e,i,s=t("<div style='display:block;position:absolute;width:50px;height:50px;overflow:hidden;'><div style='height:100px;width:auto;'></div></div>"),o=s.children()[0];return t("body").append(s),e=o.offsetWidth,s.css("overflow","scroll"),i=o.offsetWidth,e===i&&(i=s[0].clientWidth),s.remove(),n=e-i},getScrollInfo:function(e){var i=e.isWindow||e.isDocument?"":e.element.css("overflow-x"),s=e.isWindow||e.isDocument?"":e.element.css("overflow-y"),n="scroll"===i||"auto"===i&&e.width<e.element[0].scrollWidth,o="scroll"===s||"auto"===s&&e.height<e.element[0].scrollHeight;return{width:o?t.position.scrollbarWidth():0,height:n?t.position.scrollbarWidth():0}},getWithinInfo:function(e){var i=t(e||window),s=t.isWindow(i[0]),n=!!i[0]&&9===i[0].nodeType,o=!s&&!n;return{element:i,isWindow:s,isDocument:n,offset:o?t(e).offset():{left:0,top:0},scrollLeft:i.scrollLeft(),scrollTop:i.scrollTop(),width:i.outerWidth(),height:i.outerHeight()}}},t.fn.position=function(n){if(!n||!n.of)return d.apply(this,arguments);n=t.extend({},n);var u,p,f,g,m,_,v=t(n.of),b=t.position.getWithinInfo(n.within),y=t.position.getScrollInfo(b),w=(n.collision||"flip").split(" "),k={};return _=s(v),v[0].preventDefault&&(n.at="left top"),p=_.width,f=_.height,g=_.offset,m=t.extend({},g),t.each(["my","at"],function(){var t,e,i=(n[this]||"").split(" ");1===i.length&&(i=r.test(i[0])?i.concat(["center"]):h.test(i[0])?["center"].concat(i):["center","center"]),i[0]=r.test(i[0])?i[0]:"center",i[1]=h.test(i[1])?i[1]:"center",t=l.exec(i[0]),e=l.exec(i[1]),k[this]=[t?t[0]:0,e?e[0]:0],n[this]=[c.exec(i[0])[0],c.exec(i[1])[0]]}),1===w.length&&(w[1]=w[0]),"right"===n.at[0]?m.left+=p:"center"===n.at[0]&&(m.left+=p/2),"bottom"===n.at[1]?m.top+=f:"center"===n.at[1]&&(m.top+=f/2),u=e(k.at,p,f),m.left+=u[0],m.top+=u[1],this.each(function(){var s,r,h=t(this),l=h.outerWidth(),c=h.outerHeight(),d=i(this,"marginLeft"),_=i(this,"marginTop"),x=l+d+i(this,"marginRight")+y.width,C=c+_+i(this,"marginBottom")+y.height,D=t.extend({},m),I=e(k.my,h.outerWidth(),h.outerHeight());"right"===n.my[0]?D.left-=l:"center"===n.my[0]&&(D.left-=l/2),"bottom"===n.my[1]?D.top-=c:"center"===n.my[1]&&(D.top-=c/2),D.left+=I[0],D.top+=I[1],s={marginLeft:d,marginTop:_},t.each(["left","top"],function(e,i){t.ui.position[w[e]]&&t.ui.position[w[e]][i](D,{targetWidth:p,targetHeight:f,elemWidth:l,elemHeight:c,collisionPosition:s,collisionWidth:x,collisionHeight:C,offset:[u[0]+I[0],u[1]+I[1]],my:n.my,at:n.at,within:b,elem:h})}),n.using&&(r=function(t){var e=g.left-D.left,i=e+p-l,s=g.top-D.top,r=s+f-c,u={target:{element:v,left:g.left,top:g.top,width:p,height:f},element:{element:h,left:D.left,top:D.top,width:l,height:c},horizontal:0>i?"left":e>0?"right":"center",vertical:0>r?"top":s>0?"bottom":"middle"};l>p&&p>a(e+i)&&(u.horizontal="center"),c>f&&f>a(s+r)&&(u.vertical="middle"),u.important=o(a(e),a(i))>o(a(s),a(r))?"horizontal":"vertical",n.using.call(this,t,u)}),h.offset(t.extend(D,{using:r}))})},t.ui.position={fit:{left:function(t,e){var i,s=e.within,n=s.isWindow?s.scrollLeft:s.offset.left,a=s.width,r=t.left-e.collisionPosition.marginLeft,h=n-r,l=r+e.collisionWidth-a-n;e.collisionWidth>a?h>0&&0>=l?(i=t.left+h+e.collisionWidth-a-n,t.left+=h-i):t.left=l>0&&0>=h?n:h>l?n+a-e.collisionWidth:n:h>0?t.left+=h:l>0?t.left-=l:t.left=o(t.left-r,t.left)},top:function(t,e){var i,s=e.within,n=s.isWindow?s.scrollTop:s.offset.top,a=e.within.height,r=t.top-e.collisionPosition.marginTop,h=n-r,l=r+e.collisionHeight-a-n;e.collisionHeight>a?h>0&&0>=l?(i=t.top+h+e.collisionHeight-a-n,t.top+=h-i):t.top=l>0&&0>=h?n:h>l?n+a-e.collisionHeight:n:h>0?t.top+=h:l>0?t.top-=l:t.top=o(t.top-r,t.top)}},flip:{left:function(t,e){var i,s,n=e.within,o=n.offset.left+n.scrollLeft,r=n.width,h=n.isWindow?n.scrollLeft:n.offset.left,l=t.left-e.collisionPosition.marginLeft,c=l-h,u=l+e.collisionWidth-r-h,d="left"===e.my[0]?-e.elemWidth:"right"===e.my[0]?e.elemWidth:0,p="left"===e.at[0]?e.targetWidth:"right"===e.at[0]?-e.targetWidth:0,f=-2*e.offset[0];0>c?(i=t.left+d+p+f+e.collisionWidth-r-o,(0>i||a(c)>i)&&(t.left+=d+p+f)):u>0&&(s=t.left-e.collisionPosition.marginLeft+d+p+f-h,(s>0||u>a(s))&&(t.left+=d+p+f))},top:function(t,e){var i,s,n=e.within,o=n.offset.top+n.scrollTop,r=n.height,h=n.isWindow?n.scrollTop:n.offset.top,l=t.top-e.collisionPosition.marginTop,c=l-h,u=l+e.collisionHeight-r-h,d="top"===e.my[1],p=d?-e.elemHeight:"bottom"===e.my[1]?e.elemHeight:0,f="top"===e.at[1]?e.targetHeight:"bottom"===e.at[1]?-e.targetHeight:0,g=-2*e.offset[1];0>c?(s=t.top+p+f+g+e.collisionHeight-r-o,(0>s||a(c)>s)&&(t.top+=p+f+g)):u>0&&(i=t.top-e.collisionPosition.marginTop+p+f+g-h,(i>0||u>a(i))&&(t.top+=p+f+g))}},flipfit:{left:function(){t.ui.position.flip.left.apply(this,arguments),t.ui.position.fit.left.apply(this,arguments)},top:function(){t.ui.position.flip.top.apply(this,arguments),t.ui.position.fit.top.apply(this,arguments)}}}}(),t.ui.position,t.extend(t.expr[":"],{data:t.expr.createPseudo?t.expr.createPseudo(function(e){return function(i){return!!t.data(i,e)}}):function(e,i,s){return!!t.data(e,s[3])}}),t.fn.extend({disableSelection:function(){var t="onselectstart"in document.createElement("div")?"selectstart":"mousedown";return function(){return this.on(t+".ui-disableSelection",function(t){t.preventDefault()})}}(),enableSelection:function(){return this.off(".ui-disableSelection")}});var c="ui-effects-",u="ui-effects-style",d="ui-effects-animated",p=t;t.effects={effect:{}},function(t,e){function i(t,e,i){var s=u[e.type]||{};return null==t?i||!e.def?null:e.def:(t=s.floor?~~t:parseFloat(t),isNaN(t)?e.def:s.mod?(t+s.mod)%s.mod:0>t?0:t>s.max?s.max:t)}function s(i){var s=l(),n=s._rgba=[];return i=i.toLowerCase(),f(h,function(t,o){var a,r=o.re.exec(i),h=r&&o.parse(r),l=o.space||"rgba";return h?(a=s[l](h),s[c[l].cache]=a[c[l].cache],n=s._rgba=a._rgba,!1):e}),n.length?("0,0,0,0"===n.join()&&t.extend(n,o.transparent),s):o[i]}function n(t,e,i){return i=(i+1)%1,1>6*i?t+6*(e-t)*i:1>2*i?e:2>3*i?t+6*(e-t)*(2/3-i):t}var o,a="backgroundColor borderBottomColor borderLeftColor borderRightColor borderTopColor color columnRuleColor outlineColor textDecorationColor textEmphasisColor",r=/^([\-+])=\s*(\d+\.?\d*)/,h=[{re:/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/,parse:function(t){return[t[1],t[2],t[3],t[4]]}},{re:/rgba?\(\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/,parse:function(t){return[2.55*t[1],2.55*t[2],2.55*t[3],t[4]]}},{re:/#([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})/,parse:function(t){return[parseInt(t[1],16),parseInt(t[2],16),parseInt(t[3],16)]}},{re:/#([a-f0-9])([a-f0-9])([a-f0-9])/,parse:function(t){return[parseInt(t[1]+t[1],16),parseInt(t[2]+t[2],16),parseInt(t[3]+t[3],16)]}},{re:/hsla?\(\s*(\d+(?:\.\d+)?)\s*,\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/,space:"hsla",parse:function(t){return[t[1],t[2]/100,t[3]/100,t[4]]}}],l=t.Color=function(e,i,s,n){return new t.Color.fn.parse(e,i,s,n)},c={rgba:{props:{red:{idx:0,type:"byte"},green:{idx:1,type:"byte"},blue:{idx:2,type:"byte"}}},hsla:{props:{hue:{idx:0,type:"degrees"},saturation:{idx:1,type:"percent"},lightness:{idx:2,type:"percent"}}}},u={"byte":{floor:!0,max:255},percent:{max:1},degrees:{mod:360,floor:!0}},d=l.support={},p=t("<p>")[0],f=t.each;p.style.cssText="background-color:rgba(1,1,1,.5)",d.rgba=p.style.backgroundColor.indexOf("rgba")>-1,f(c,function(t,e){e.cache="_"+t,e.props.alpha={idx:3,type:"percent",def:1}}),l.fn=t.extend(l.prototype,{parse:function(n,a,r,h){if(n===e)return this._rgba=[null,null,null,null],this;(n.jquery||n.nodeType)&&(n=t(n).css(a),a=e);var u=this,d=t.type(n),p=this._rgba=[];return a!==e&&(n=[n,a,r,h],d="array"),"string"===d?this.parse(s(n)||o._default):"array"===d?(f(c.rgba.props,function(t,e){p[e.idx]=i(n[e.idx],e)}),this):"object"===d?(n instanceof l?f(c,function(t,e){n[e.cache]&&(u[e.cache]=n[e.cache].slice())}):f(c,function(e,s){var o=s.cache;f(s.props,function(t,e){if(!u[o]&&s.to){if("alpha"===t||null==n[t])return;u[o]=s.to(u._rgba)}u[o][e.idx]=i(n[t],e,!0)}),u[o]&&0>t.inArray(null,u[o].slice(0,3))&&(u[o][3]=1,s.from&&(u._rgba=s.from(u[o])))}),this):e},is:function(t){var i=l(t),s=!0,n=this;return f(c,function(t,o){var a,r=i[o.cache];return r&&(a=n[o.cache]||o.to&&o.to(n._rgba)||[],f(o.props,function(t,i){return null!=r[i.idx]?s=r[i.idx]===a[i.idx]:e})),s}),s},_space:function(){var t=[],e=this;return f(c,function(i,s){e[s.cache]&&t.push(i)}),t.pop()},transition:function(t,e){var s=l(t),n=s._space(),o=c[n],a=0===this.alpha()?l("transparent"):this,r=a[o.cache]||o.to(a._rgba),h=r.slice();return s=s[o.cache],f(o.props,function(t,n){var o=n.idx,a=r[o],l=s[o],c=u[n.type]||{};null!==l&&(null===a?h[o]=l:(c.mod&&(l-a>c.mod/2?a+=c.mod:a-l>c.mod/2&&(a-=c.mod)),h[o]=i((l-a)*e+a,n)))}),this[n](h)},blend:function(e){if(1===this._rgba[3])return this;var i=this._rgba.slice(),s=i.pop(),n=l(e)._rgba;return l(t.map(i,function(t,e){return(1-s)*n[e]+s*t}))},toRgbaString:function(){var e="rgba(",i=t.map(this._rgba,function(t,e){return null==t?e>2?1:0:t});return 1===i[3]&&(i.pop(),e="rgb("),e+i.join()+")"},toHslaString:function(){var e="hsla(",i=t.map(this.hsla(),function(t,e){return null==t&&(t=e>2?1:0),e&&3>e&&(t=Math.round(100*t)+"%"),t});return 1===i[3]&&(i.pop(),e="hsl("),e+i.join()+")"},toHexString:function(e){var i=this._rgba.slice(),s=i.pop();return e&&i.push(~~(255*s)),"#"+t.map(i,function(t){return t=(t||0).toString(16),1===t.length?"0"+t:t}).join("")},toString:function(){return 0===this._rgba[3]?"transparent":this.toRgbaString()}}),l.fn.parse.prototype=l.fn,c.hsla.to=function(t){if(null==t[0]||null==t[1]||null==t[2])return[null,null,null,t[3]];var e,i,s=t[0]/255,n=t[1]/255,o=t[2]/255,a=t[3],r=Math.max(s,n,o),h=Math.min(s,n,o),l=r-h,c=r+h,u=.5*c;return e=h===r?0:s===r?60*(n-o)/l+360:n===r?60*(o-s)/l+120:60*(s-n)/l+240,i=0===l?0:.5>=u?l/c:l/(2-c),[Math.round(e)%360,i,u,null==a?1:a]},c.hsla.from=function(t){if(null==t[0]||null==t[1]||null==t[2])return[null,null,null,t[3]];var e=t[0]/360,i=t[1],s=t[2],o=t[3],a=.5>=s?s*(1+i):s+i-s*i,r=2*s-a;return[Math.round(255*n(r,a,e+1/3)),Math.round(255*n(r,a,e)),Math.round(255*n(r,a,e-1/3)),o]},f(c,function(s,n){var o=n.props,a=n.cache,h=n.to,c=n.from;l.fn[s]=function(s){if(h&&!this[a]&&(this[a]=h(this._rgba)),s===e)return this[a].slice();var n,r=t.type(s),u="array"===r||"object"===r?s:arguments,d=this[a].slice();return f(o,function(t,e){var s=u["object"===r?t:e.idx];null==s&&(s=d[e.idx]),d[e.idx]=i(s,e)}),c?(n=l(c(d)),n[a]=d,n):l(d)},f(o,function(e,i){l.fn[e]||(l.fn[e]=function(n){var o,a=t.type(n),h="alpha"===e?this._hsla?"hsla":"rgba":s,l=this[h](),c=l[i.idx];return"undefined"===a?c:("function"===a&&(n=n.call(this,c),a=t.type(n)),null==n&&i.empty?this:("string"===a&&(o=r.exec(n),o&&(n=c+parseFloat(o[2])*("+"===o[1]?1:-1))),l[i.idx]=n,this[h](l)))})})}),l.hook=function(e){var i=e.split(" ");f(i,function(e,i){t.cssHooks[i]={set:function(e,n){var o,a,r="";if("transparent"!==n&&("string"!==t.type(n)||(o=s(n)))){if(n=l(o||n),!d.rgba&&1!==n._rgba[3]){for(a="backgroundColor"===i?e.parentNode:e;(""===r||"transparent"===r)&&a&&a.style;)try{r=t.css(a,"backgroundColor"),a=a.parentNode}catch(h){}n=n.blend(r&&"transparent"!==r?r:"_default")}n=n.toRgbaString()}try{e.style[i]=n}catch(h){}}},t.fx.step[i]=function(e){e.colorInit||(e.start=l(e.elem,i),e.end=l(e.end),e.colorInit=!0),t.cssHooks[i].set(e.elem,e.start.transition(e.end,e.pos))}})},l.hook(a),t.cssHooks.borderColor={expand:function(t){var e={};return f(["Top","Right","Bottom","Left"],function(i,s){e["border"+s+"Color"]=t}),e}},o=t.Color.names={aqua:"#00ffff",black:"#000000",blue:"#0000ff",fuchsia:"#ff00ff",gray:"#808080",green:"#008000",lime:"#00ff00",maroon:"#800000",navy:"#000080",olive:"#808000",purple:"#800080",red:"#ff0000",silver:"#c0c0c0",teal:"#008080",white:"#ffffff",yellow:"#ffff00",transparent:[null,null,null,0],_default:"#ffffff"}}(p),function(){function e(e){var i,s,n=e.ownerDocument.defaultView?e.ownerDocument.defaultView.getComputedStyle(e,null):e.currentStyle,o={};if(n&&n.length&&n[0]&&n[n[0]])for(s=n.length;s--;)i=n[s],"string"==typeof n[i]&&(o[t.camelCase(i)]=n[i]);else for(i in n)"string"==typeof n[i]&&(o[i]=n[i]);return o}function i(e,i){var s,o,a={};for(s in i)o=i[s],e[s]!==o&&(n[s]||(t.fx.step[s]||!isNaN(parseFloat(o)))&&(a[s]=o));return a}var s=["add","remove","toggle"],n={border:1,borderBottom:1,borderColor:1,borderLeft:1,borderRight:1,borderTop:1,borderWidth:1,margin:1,padding:1};t.each(["borderLeftStyle","borderRightStyle","borderBottomStyle","borderTopStyle"],function(e,i){t.fx.step[i]=function(t){("none"!==t.end&&!t.setAttr||1===t.pos&&!t.setAttr)&&(p.style(t.elem,i,t.end),t.setAttr=!0)}}),t.fn.addBack||(t.fn.addBack=function(t){return this.add(null==t?this.prevObject:this.prevObject.filter(t))}),t.effects.animateClass=function(n,o,a,r){var h=t.speed(o,a,r);return this.queue(function(){var o,a=t(this),r=a.attr("class")||"",l=h.children?a.find("*").addBack():a;l=l.map(function(){var i=t(this);return{el:i,start:e(this)}}),o=function(){t.each(s,function(t,e){n[e]&&a[e+"Class"](n[e])})},o(),l=l.map(function(){return this.end=e(this.el[0]),this.diff=i(this.start,this.end),this}),a.attr("class",r),l=l.map(function(){var e=this,i=t.Deferred(),s=t.extend({},h,{queue:!1,complete:function(){i.resolve(e)}});return this.el.animate(this.diff,s),i.promise()}),t.when.apply(t,l.get()).done(function(){o(),t.each(arguments,function(){var e=this.el;t.each(this.diff,function(t){e.css(t,"")})}),h.complete.call(a[0])})})},t.fn.extend({addClass:function(e){return function(i,s,n,o){return s?t.effects.animateClass.call(this,{add:i},s,n,o):e.apply(this,arguments)}}(t.fn.addClass),removeClass:function(e){return function(i,s,n,o){return arguments.length>1?t.effects.animateClass.call(this,{remove:i},s,n,o):e.apply(this,arguments)}}(t.fn.removeClass),toggleClass:function(e){return function(i,s,n,o,a){return"boolean"==typeof s||void 0===s?n?t.effects.animateClass.call(this,s?{add:i}:{remove:i},n,o,a):e.apply(this,arguments):t.effects.animateClass.call(this,{toggle:i},s,n,o)}}(t.fn.toggleClass),switchClass:function(e,i,s,n,o){return t.effects.animateClass.call(this,{add:i,remove:e},s,n,o)}})}(),function(){function e(e,i,s,n){return t.isPlainObject(e)&&(i=e,e=e.effect),e={effect:e},null==i&&(i={}),t.isFunction(i)&&(n=i,s=null,i={}),("number"==typeof i||t.fx.speeds[i])&&(n=s,s=i,i={}),t.isFunction(s)&&(n=s,s=null),i&&t.extend(e,i),s=s||i.duration,e.duration=t.fx.off?0:"number"==typeof s?s:s in t.fx.speeds?t.fx.speeds[s]:t.fx.speeds._default,e.complete=n||i.complete,e}function i(e){return!e||"number"==typeof e||t.fx.speeds[e]?!0:"string"!=typeof e||t.effects.effect[e]?t.isFunction(e)?!0:"object"!=typeof e||e.effect?!1:!0:!0}function s(t,e){var i=e.outerWidth(),s=e.outerHeight(),n=/^rect\((-?\d*\.?\d*px|-?\d+%|auto),?\s*(-?\d*\.?\d*px|-?\d+%|auto),?\s*(-?\d*\.?\d*px|-?\d+%|auto),?\s*(-?\d*\.?\d*px|-?\d+%|auto)\)$/,o=n.exec(t)||["",0,i,s,0];return{top:parseFloat(o[1])||0,right:"auto"===o[2]?i:parseFloat(o[2]),bottom:"auto"===o[3]?s:parseFloat(o[3]),left:parseFloat(o[4])||0}}t.expr&&t.expr.filters&&t.expr.filters.animated&&(t.expr.filters.animated=function(e){return function(i){return!!t(i).data(d)||e(i)}}(t.expr.filters.animated)),t.uiBackCompat!==!1&&t.extend(t.effects,{save:function(t,e){for(var i=0,s=e.length;s>i;i++)null!==e[i]&&t.data(c+e[i],t[0].style[e[i]])},restore:function(t,e){for(var i,s=0,n=e.length;n>s;s++)null!==e[s]&&(i=t.data(c+e[s]),t.css(e[s],i))},setMode:function(t,e){return"toggle"===e&&(e=t.is(":hidden")?"show":"hide"),e},createWrapper:function(e){if(e.parent().is(".ui-effects-wrapper"))return e.parent();var i={width:e.outerWidth(!0),height:e.outerHeight(!0),"float":e.css("float")},s=t("<div></div>").addClass("ui-effects-wrapper").css({fontSize:"100%",background:"transparent",border:"none",margin:0,padding:0}),n={width:e.width(),height:e.height()},o=document.activeElement;try{o.id}catch(a){o=document.body}return e.wrap(s),(e[0]===o||t.contains(e[0],o))&&t(o).trigger("focus"),s=e.parent(),"static"===e.css("position")?(s.css({position:"relative"}),e.css({position:"relative"})):(t.extend(i,{position:e.css("position"),zIndex:e.css("z-index")}),t.each(["top","left","bottom","right"],function(t,s){i[s]=e.css(s),isNaN(parseInt(i[s],10))&&(i[s]="auto")}),e.css({position:"relative",top:0,left:0,right:"auto",bottom:"auto"})),e.css(n),s.css(i).show()},removeWrapper:function(e){var i=document.activeElement;return e.parent().is(".ui-effects-wrapper")&&(e.parent().replaceWith(e),(e[0]===i||t.contains(e[0],i))&&t(i).trigger("focus")),e}}),t.extend(t.effects,{version:"1.12.1",define:function(e,i,s){return s||(s=i,i="effect"),t.effects.effect[e]=s,t.effects.effect[e].mode=i,s},scaledDimensions:function(t,e,i){if(0===e)return{height:0,width:0,outerHeight:0,outerWidth:0};var s="horizontal"!==i?(e||100)/100:1,n="vertical"!==i?(e||100)/100:1;return{height:t.height()*n,width:t.width()*s,outerHeight:t.outerHeight()*n,outerWidth:t.outerWidth()*s}},clipToBox:function(t){return{width:t.clip.right-t.clip.left,height:t.clip.bottom-t.clip.top,left:t.clip.left,top:t.clip.top}},unshift:function(t,e,i){var s=t.queue();e>1&&s.splice.apply(s,[1,0].concat(s.splice(e,i))),t.dequeue()},saveStyle:function(t){t.data(u,t[0].style.cssText)},restoreStyle:function(t){t[0].style.cssText=t.data(u)||"",t.removeData(u)},mode:function(t,e){var i=t.is(":hidden");return"toggle"===e&&(e=i?"show":"hide"),(i?"hide"===e:"show"===e)&&(e="none"),e},getBaseline:function(t,e){var i,s;switch(t[0]){case"top":i=0;break;case"middle":i=.5;break;case"bottom":i=1;break;default:i=t[0]/e.height}switch(t[1]){case"left":s=0;break;case"center":s=.5;break;case"right":s=1;break;default:s=t[1]/e.width}return{x:s,y:i}},createPlaceholder:function(e){var i,s=e.css("position"),n=e.position();return e.css({marginTop:e.css("marginTop"),marginBottom:e.css("marginBottom"),marginLeft:e.css("marginLeft"),marginRight:e.css("marginRight")}).outerWidth(e.outerWidth()).outerHeight(e.outerHeight()),/^(static|relative)/.test(s)&&(s="absolute",i=t("<"+e[0].nodeName+">").insertAfter(e).css({display:/^(inline|ruby)/.test(e.css("display"))?"inline-block":"block",visibility:"hidden",marginTop:e.css("marginTop"),marginBottom:e.css("marginBottom"),marginLeft:e.css("marginLeft"),marginRight:e.css("marginRight"),"float":e.css("float")}).outerWidth(e.outerWidth()).outerHeight(e.outerHeight()).addClass("ui-effects-placeholder"),e.data(c+"placeholder",i)),e.css({position:s,left:n.left,top:n.top}),i},removePlaceholder:function(t){var e=c+"placeholder",i=t.data(e);i&&(i.remove(),t.removeData(e))},cleanUp:function(e){t.effects.restoreStyle(e),t.effects.removePlaceholder(e)},setTransition:function(e,i,s,n){return n=n||{},t.each(i,function(t,i){var o=e.cssUnit(i);o[0]>0&&(n[i]=o[0]*s+o[1])}),n}}),t.fn.extend({effect:function(){function i(e){function i(){r.removeData(d),t.effects.cleanUp(r),"hide"===s.mode&&r.hide(),a()}function a(){t.isFunction(h)&&h.call(r[0]),t.isFunction(e)&&e()}var r=t(this);s.mode=c.shift(),t.uiBackCompat===!1||o?"none"===s.mode?(r[l](),a()):n.call(r[0],s,i):(r.is(":hidden")?"hide"===l:"show"===l)?(r[l](),a()):n.call(r[0],s,a)}var s=e.apply(this,arguments),n=t.effects.effect[s.effect],o=n.mode,a=s.queue,r=a||"fx",h=s.complete,l=s.mode,c=[],u=function(e){var i=t(this),s=t.effects.mode(i,l)||o;i.data(d,!0),c.push(s),o&&("show"===s||s===o&&"hide"===s)&&i.show(),o&&"none"===s||t.effects.saveStyle(i),t.isFunction(e)&&e()};return t.fx.off||!n?l?this[l](s.duration,h):this.each(function(){h&&h.call(this)}):a===!1?this.each(u).each(i):this.queue(r,u).queue(r,i)},show:function(t){return function(s){if(i(s))return t.apply(this,arguments);var n=e.apply(this,arguments);return n.mode="show",this.effect.call(this,n)
1227}}(t.fn.show),hide:function(t){return function(s){if(i(s))return t.apply(this,arguments);var n=e.apply(this,arguments);return n.mode="hide",this.effect.call(this,n)}}(t.fn.hide),toggle:function(t){return function(s){if(i(s)||"boolean"==typeof s)return t.apply(this,arguments);var n=e.apply(this,arguments);return n.mode="toggle",this.effect.call(this,n)}}(t.fn.toggle),cssUnit:function(e){var i=this.css(e),s=[];return t.each(["em","px","%","pt"],function(t,e){i.indexOf(e)>0&&(s=[parseFloat(i),e])}),s},cssClip:function(t){return t?this.css("clip","rect("+t.top+"px "+t.right+"px "+t.bottom+"px "+t.left+"px)"):s(this.css("clip"),this)},transfer:function(e,i){var s=t(this),n=t(e.to),o="fixed"===n.css("position"),a=t("body"),r=o?a.scrollTop():0,h=o?a.scrollLeft():0,l=n.offset(),c={top:l.top-r,left:l.left-h,height:n.innerHeight(),width:n.innerWidth()},u=s.offset(),d=t("<div class='ui-effects-transfer'></div>").appendTo("body").addClass(e.className).css({top:u.top-r,left:u.left-h,height:s.innerHeight(),width:s.innerWidth(),position:o?"fixed":"absolute"}).animate(c,e.duration,e.easing,function(){d.remove(),t.isFunction(i)&&i()})}}),t.fx.step.clip=function(e){e.clipInit||(e.start=t(e.elem).cssClip(),"string"==typeof e.end&&(e.end=s(e.end,e.elem)),e.clipInit=!0),t(e.elem).cssClip({top:e.pos*(e.end.top-e.start.top)+e.start.top,right:e.pos*(e.end.right-e.start.right)+e.start.right,bottom:e.pos*(e.end.bottom-e.start.bottom)+e.start.bottom,left:e.pos*(e.end.left-e.start.left)+e.start.left})}}(),function(){var e={};t.each(["Quad","Cubic","Quart","Quint","Expo"],function(t,i){e[i]=function(e){return Math.pow(e,t+2)}}),t.extend(e,{Sine:function(t){return 1-Math.cos(t*Math.PI/2)},Circ:function(t){return 1-Math.sqrt(1-t*t)},Elastic:function(t){return 0===t||1===t?t:-Math.pow(2,8*(t-1))*Math.sin((80*(t-1)-7.5)*Math.PI/15)},Back:function(t){return t*t*(3*t-2)},Bounce:function(t){for(var e,i=4;((e=Math.pow(2,--i))-1)/11>t;);return 1/Math.pow(4,3-i)-7.5625*Math.pow((3*e-2)/22-t,2)}}),t.each(e,function(e,i){t.easing["easeIn"+e]=i,t.easing["easeOut"+e]=function(t){return 1-i(1-t)},t.easing["easeInOut"+e]=function(t){return.5>t?i(2*t)/2:1-i(-2*t+2)/2}})}();var f=t.effects;t.effects.define("blind","hide",function(e,i){var s={up:["bottom","top"],vertical:["bottom","top"],down:["top","bottom"],left:["right","left"],horizontal:["right","left"],right:["left","right"]},n=t(this),o=e.direction||"up",a=n.cssClip(),r={clip:t.extend({},a)},h=t.effects.createPlaceholder(n);r.clip[s[o][0]]=r.clip[s[o][1]],"show"===e.mode&&(n.cssClip(r.clip),h&&h.css(t.effects.clipToBox(r)),r.clip=a),h&&h.animate(t.effects.clipToBox(r),e.duration,e.easing),n.animate(r,{queue:!1,duration:e.duration,easing:e.easing,complete:i})}),t.effects.define("bounce",function(e,i){var s,n,o,a=t(this),r=e.mode,h="hide"===r,l="show"===r,c=e.direction||"up",u=e.distance,d=e.times||5,p=2*d+(l||h?1:0),f=e.duration/p,g=e.easing,m="up"===c||"down"===c?"top":"left",_="up"===c||"left"===c,v=0,b=a.queue().length;for(t.effects.createPlaceholder(a),o=a.css(m),u||(u=a["top"===m?"outerHeight":"outerWidth"]()/3),l&&(n={opacity:1},n[m]=o,a.css("opacity",0).css(m,_?2*-u:2*u).animate(n,f,g)),h&&(u/=Math.pow(2,d-1)),n={},n[m]=o;d>v;v++)s={},s[m]=(_?"-=":"+=")+u,a.animate(s,f,g).animate(n,f,g),u=h?2*u:u/2;h&&(s={opacity:0},s[m]=(_?"-=":"+=")+u,a.animate(s,f,g)),a.queue(i),t.effects.unshift(a,b,p+1)}),t.effects.define("clip","hide",function(e,i){var s,n={},o=t(this),a=e.direction||"vertical",r="both"===a,h=r||"horizontal"===a,l=r||"vertical"===a;s=o.cssClip(),n.clip={top:l?(s.bottom-s.top)/2:s.top,right:h?(s.right-s.left)/2:s.right,bottom:l?(s.bottom-s.top)/2:s.bottom,left:h?(s.right-s.left)/2:s.left},t.effects.createPlaceholder(o),"show"===e.mode&&(o.cssClip(n.clip),n.clip=s),o.animate(n,{queue:!1,duration:e.duration,easing:e.easing,complete:i})}),t.effects.define("drop","hide",function(e,i){var s,n=t(this),o=e.mode,a="show"===o,r=e.direction||"left",h="up"===r||"down"===r?"top":"left",l="up"===r||"left"===r?"-=":"+=",c="+="===l?"-=":"+=",u={opacity:0};t.effects.createPlaceholder(n),s=e.distance||n["top"===h?"outerHeight":"outerWidth"](!0)/2,u[h]=l+s,a&&(n.css(u),u[h]=c+s,u.opacity=1),n.animate(u,{queue:!1,duration:e.duration,easing:e.easing,complete:i})}),t.effects.define("explode","hide",function(e,i){function s(){b.push(this),b.length===u*d&&n()}function n(){p.css({visibility:"visible"}),t(b).remove(),i()}var o,a,r,h,l,c,u=e.pieces?Math.round(Math.sqrt(e.pieces)):3,d=u,p=t(this),f=e.mode,g="show"===f,m=p.show().css("visibility","hidden").offset(),_=Math.ceil(p.outerWidth()/d),v=Math.ceil(p.outerHeight()/u),b=[];for(o=0;u>o;o++)for(h=m.top+o*v,c=o-(u-1)/2,a=0;d>a;a++)r=m.left+a*_,l=a-(d-1)/2,p.clone().appendTo("body").wrap("<div></div>").css({position:"absolute",visibility:"visible",left:-a*_,top:-o*v}).parent().addClass("ui-effects-explode").css({position:"absolute",overflow:"hidden",width:_,height:v,left:r+(g?l*_:0),top:h+(g?c*v:0),opacity:g?0:1}).animate({left:r+(g?0:l*_),top:h+(g?0:c*v),opacity:g?1:0},e.duration||500,e.easing,s)}),t.effects.define("fade","toggle",function(e,i){var s="show"===e.mode;t(this).css("opacity",s?0:1).animate({opacity:s?1:0},{queue:!1,duration:e.duration,easing:e.easing,complete:i})}),t.effects.define("fold","hide",function(e,i){var s=t(this),n=e.mode,o="show"===n,a="hide"===n,r=e.size||15,h=/([0-9]+)%/.exec(r),l=!!e.horizFirst,c=l?["right","bottom"]:["bottom","right"],u=e.duration/2,d=t.effects.createPlaceholder(s),p=s.cssClip(),f={clip:t.extend({},p)},g={clip:t.extend({},p)},m=[p[c[0]],p[c[1]]],_=s.queue().length;h&&(r=parseInt(h[1],10)/100*m[a?0:1]),f.clip[c[0]]=r,g.clip[c[0]]=r,g.clip[c[1]]=0,o&&(s.cssClip(g.clip),d&&d.css(t.effects.clipToBox(g)),g.clip=p),s.queue(function(i){d&&d.animate(t.effects.clipToBox(f),u,e.easing).animate(t.effects.clipToBox(g),u,e.easing),i()}).animate(f,u,e.easing).animate(g,u,e.easing).queue(i),t.effects.unshift(s,_,4)}),t.effects.define("highlight","show",function(e,i){var s=t(this),n={backgroundColor:s.css("backgroundColor")};"hide"===e.mode&&(n.opacity=0),t.effects.saveStyle(s),s.css({backgroundImage:"none",backgroundColor:e.color||"#ffff99"}).animate(n,{queue:!1,duration:e.duration,easing:e.easing,complete:i})}),t.effects.define("size",function(e,i){var s,n,o,a=t(this),r=["fontSize"],h=["borderTopWidth","borderBottomWidth","paddingTop","paddingBottom"],l=["borderLeftWidth","borderRightWidth","paddingLeft","paddingRight"],c=e.mode,u="effect"!==c,d=e.scale||"both",p=e.origin||["middle","center"],f=a.css("position"),g=a.position(),m=t.effects.scaledDimensions(a),_=e.from||m,v=e.to||t.effects.scaledDimensions(a,0);t.effects.createPlaceholder(a),"show"===c&&(o=_,_=v,v=o),n={from:{y:_.height/m.height,x:_.width/m.width},to:{y:v.height/m.height,x:v.width/m.width}},("box"===d||"both"===d)&&(n.from.y!==n.to.y&&(_=t.effects.setTransition(a,h,n.from.y,_),v=t.effects.setTransition(a,h,n.to.y,v)),n.from.x!==n.to.x&&(_=t.effects.setTransition(a,l,n.from.x,_),v=t.effects.setTransition(a,l,n.to.x,v))),("content"===d||"both"===d)&&n.from.y!==n.to.y&&(_=t.effects.setTransition(a,r,n.from.y,_),v=t.effects.setTransition(a,r,n.to.y,v)),p&&(s=t.effects.getBaseline(p,m),_.top=(m.outerHeight-_.outerHeight)*s.y+g.top,_.left=(m.outerWidth-_.outerWidth)*s.x+g.left,v.top=(m.outerHeight-v.outerHeight)*s.y+g.top,v.left=(m.outerWidth-v.outerWidth)*s.x+g.left),a.css(_),("content"===d||"both"===d)&&(h=h.concat(["marginTop","marginBottom"]).concat(r),l=l.concat(["marginLeft","marginRight"]),a.find("*[width]").each(function(){var i=t(this),s=t.effects.scaledDimensions(i),o={height:s.height*n.from.y,width:s.width*n.from.x,outerHeight:s.outerHeight*n.from.y,outerWidth:s.outerWidth*n.from.x},a={height:s.height*n.to.y,width:s.width*n.to.x,outerHeight:s.height*n.to.y,outerWidth:s.width*n.to.x};n.from.y!==n.to.y&&(o=t.effects.setTransition(i,h,n.from.y,o),a=t.effects.setTransition(i,h,n.to.y,a)),n.from.x!==n.to.x&&(o=t.effects.setTransition(i,l,n.from.x,o),a=t.effects.setTransition(i,l,n.to.x,a)),u&&t.effects.saveStyle(i),i.css(o),i.animate(a,e.duration,e.easing,function(){u&&t.effects.restoreStyle(i)})})),a.animate(v,{queue:!1,duration:e.duration,easing:e.easing,complete:function(){var e=a.offset();0===v.opacity&&a.css("opacity",_.opacity),u||(a.css("position","static"===f?"relative":f).offset(e),t.effects.saveStyle(a)),i()}})}),t.effects.define("scale",function(e,i){var s=t(this),n=e.mode,o=parseInt(e.percent,10)||(0===parseInt(e.percent,10)?0:"effect"!==n?0:100),a=t.extend(!0,{from:t.effects.scaledDimensions(s),to:t.effects.scaledDimensions(s,o,e.direction||"both"),origin:e.origin||["middle","center"]},e);e.fade&&(a.from.opacity=1,a.to.opacity=0),t.effects.effect.size.call(this,a,i)}),t.effects.define("puff","hide",function(e,i){var s=t.extend(!0,{},e,{fade:!0,percent:parseInt(e.percent,10)||150});t.effects.effect.scale.call(this,s,i)}),t.effects.define("pulsate","show",function(e,i){var s=t(this),n=e.mode,o="show"===n,a="hide"===n,r=o||a,h=2*(e.times||5)+(r?1:0),l=e.duration/h,c=0,u=1,d=s.queue().length;for((o||!s.is(":visible"))&&(s.css("opacity",0).show(),c=1);h>u;u++)s.animate({opacity:c},l,e.easing),c=1-c;s.animate({opacity:c},l,e.easing),s.queue(i),t.effects.unshift(s,d,h+1)}),t.effects.define("shake",function(e,i){var s=1,n=t(this),o=e.direction||"left",a=e.distance||20,r=e.times||3,h=2*r+1,l=Math.round(e.duration/h),c="up"===o||"down"===o?"top":"left",u="up"===o||"left"===o,d={},p={},f={},g=n.queue().length;for(t.effects.createPlaceholder(n),d[c]=(u?"-=":"+=")+a,p[c]=(u?"+=":"-=")+2*a,f[c]=(u?"-=":"+=")+2*a,n.animate(d,l,e.easing);r>s;s++)n.animate(p,l,e.easing).animate(f,l,e.easing);n.animate(p,l,e.easing).animate(d,l/2,e.easing).queue(i),t.effects.unshift(n,g,h+1)}),t.effects.define("slide","show",function(e,i){var s,n,o=t(this),a={up:["bottom","top"],down:["top","bottom"],left:["right","left"],right:["left","right"]},r=e.mode,h=e.direction||"left",l="up"===h||"down"===h?"top":"left",c="up"===h||"left"===h,u=e.distance||o["top"===l?"outerHeight":"outerWidth"](!0),d={};t.effects.createPlaceholder(o),s=o.cssClip(),n=o.position()[l],d[l]=(c?-1:1)*u+n,d.clip=o.cssClip(),d.clip[a[h][1]]=d.clip[a[h][0]],"show"===r&&(o.cssClip(d.clip),o.css(l,d[l]),d.clip=s,d[l]=n),o.animate(d,{queue:!1,duration:e.duration,easing:e.easing,complete:i})});var f;t.uiBackCompat!==!1&&(f=t.effects.define("transfer",function(e,i){t(this).transfer(e,i)})),t.ui.focusable=function(i,s){var n,o,a,r,h,l=i.nodeName.toLowerCase();return"area"===l?(n=i.parentNode,o=n.name,i.href&&o&&"map"===n.nodeName.toLowerCase()?(a=t("img[usemap='#"+o+"']"),a.length>0&&a.is(":visible")):!1):(/^(input|select|textarea|button|object)$/.test(l)?(r=!i.disabled,r&&(h=t(i).closest("fieldset")[0],h&&(r=!h.disabled))):r="a"===l?i.href||s:s,r&&t(i).is(":visible")&&e(t(i)))},t.extend(t.expr[":"],{focusable:function(e){return t.ui.focusable(e,null!=t.attr(e,"tabindex"))}}),t.ui.focusable,t.fn.form=function(){return"string"==typeof this[0].form?this.closest("form"):t(this[0].form)},t.ui.formResetMixin={_formResetHandler:function(){var e=t(this);setTimeout(function(){var i=e.data("ui-form-reset-instances");t.each(i,function(){this.refresh()})})},_bindFormResetHandler:function(){if(this.form=this.element.form(),this.form.length){var t=this.form.data("ui-form-reset-instances")||[];t.length||this.form.on("reset.ui-form-reset",this._formResetHandler),t.push(this),this.form.data("ui-form-reset-instances",t)}},_unbindFormResetHandler:function(){if(this.form.length){var e=this.form.data("ui-form-reset-instances");e.splice(t.inArray(this,e),1),e.length?this.form.data("ui-form-reset-instances",e):this.form.removeData("ui-form-reset-instances").off("reset.ui-form-reset")}}},"1.7"===t.fn.jquery.substring(0,3)&&(t.each(["Width","Height"],function(e,i){function s(e,i,s,o){return t.each(n,function(){i-=parseFloat(t.css(e,"padding"+this))||0,s&&(i-=parseFloat(t.css(e,"border"+this+"Width"))||0),o&&(i-=parseFloat(t.css(e,"margin"+this))||0)}),i}var n="Width"===i?["Left","Right"]:["Top","Bottom"],o=i.toLowerCase(),a={innerWidth:t.fn.innerWidth,innerHeight:t.fn.innerHeight,outerWidth:t.fn.outerWidth,outerHeight:t.fn.outerHeight};t.fn["inner"+i]=function(e){return void 0===e?a["inner"+i].call(this):this.each(function(){t(this).css(o,s(this,e)+"px")})},t.fn["outer"+i]=function(e,n){return"number"!=typeof e?a["outer"+i].call(this,e):this.each(function(){t(this).css(o,s(this,e,!0,n)+"px")})}}),t.fn.addBack=function(t){return this.add(null==t?this.prevObject:this.prevObject.filter(t))}),t.ui.keyCode={BACKSPACE:8,COMMA:188,DELETE:46,DOWN:40,END:35,ENTER:13,ESCAPE:27,HOME:36,LEFT:37,PAGE_DOWN:34,PAGE_UP:33,PERIOD:190,RIGHT:39,SPACE:32,TAB:9,UP:38},t.ui.escapeSelector=function(){var t=/([!"#$%&'()*+,.\/:;<=>?@[\]^`{|}~])/g;return function(e){return e.replace(t,"\\$1")}}(),t.fn.labels=function(){var e,i,s,n,o;return this[0].labels&&this[0].labels.length?this.pushStack(this[0].labels):(n=this.eq(0).parents("label"),s=this.attr("id"),s&&(e=this.eq(0).parents().last(),o=e.add(e.length?e.siblings():this.siblings()),i="label[for='"+t.ui.escapeSelector(s)+"']",n=n.add(o.find(i).addBack(i))),this.pushStack(n))},t.fn.scrollParent=function(e){var i=this.css("position"),s="absolute"===i,n=e?/(auto|scroll|hidden)/:/(auto|scroll)/,o=this.parents().filter(function(){var e=t(this);return s&&"static"===e.css("position")?!1:n.test(e.css("overflow")+e.css("overflow-y")+e.css("overflow-x"))}).eq(0);return"fixed"!==i&&o.length?o:t(this[0].ownerDocument||document)},t.extend(t.expr[":"],{tabbable:function(e){var i=t.attr(e,"tabindex"),s=null!=i;return(!s||i>=0)&&t.ui.focusable(e,s)}}),t.fn.extend({uniqueId:function(){var t=0;return function(){return this.each(function(){this.id||(this.id="ui-id-"+ ++t)})}}(),removeUniqueId:function(){return this.each(function(){/^ui-id-\d+$/.test(this.id)&&t(this).removeAttr("id")})}}),t.widget("ui.accordion",{version:"1.12.1",options:{active:0,animate:{},classes:{"ui-accordion-header":"ui-corner-top","ui-accordion-header-collapsed":"ui-corner-all","ui-accordion-content":"ui-corner-bottom"},collapsible:!1,event:"click",header:"> li > :first-child, > :not(li):even",heightStyle:"auto",icons:{activeHeader:"ui-icon-triangle-1-s",header:"ui-icon-triangle-1-e"},activate:null,beforeActivate:null},hideProps:{borderTopWidth:"hide",borderBottomWidth:"hide",paddingTop:"hide",paddingBottom:"hide",height:"hide"},showProps:{borderTopWidth:"show",borderBottomWidth:"show",paddingTop:"show",paddingBottom:"show",height:"show"},_create:function(){var e=this.options;this.prevShow=this.prevHide=t(),this._addClass("ui-accordion","ui-widget ui-helper-reset"),this.element.attr("role","tablist"),e.collapsible||e.active!==!1&&null!=e.active||(e.active=0),this._processPanels(),0>e.active&&(e.active+=this.headers.length),this._refresh()},_getCreateEventData:function(){return{header:this.active,panel:this.active.length?this.active.next():t()}},_createIcons:function(){var e,i,s=this.options.icons;s&&(e=t("<span>"),this._addClass(e,"ui-accordion-header-icon","ui-icon "+s.header),e.prependTo(this.headers),i=this.active.children(".ui-accordion-header-icon"),this._removeClass(i,s.header)._addClass(i,null,s.activeHeader)._addClass(this.headers,"ui-accordion-icons"))},_destroyIcons:function(){this._removeClass(this.headers,"ui-accordion-icons"),this.headers.children(".ui-accordion-header-icon").remove()},_destroy:function(){var t;this.element.removeAttr("role"),this.headers.removeAttr("role aria-expanded aria-selected aria-controls tabIndex").removeUniqueId(),this._destroyIcons(),t=this.headers.next().css("display","").removeAttr("role aria-hidden aria-labelledby").removeUniqueId(),"content"!==this.options.heightStyle&&t.css("height","")},_setOption:function(t,e){return"active"===t?(this._activate(e),void 0):("event"===t&&(this.options.event&&this._off(this.headers,this.options.event),this._setupEvents(e)),this._super(t,e),"collapsible"!==t||e||this.options.active!==!1||this._activate(0),"icons"===t&&(this._destroyIcons(),e&&this._createIcons()),void 0)},_setOptionDisabled:function(t){this._super(t),this.element.attr("aria-disabled",t),this._toggleClass(null,"ui-state-disabled",!!t),this._toggleClass(this.headers.add(this.headers.next()),null,"ui-state-disabled",!!t)},_keydown:function(e){if(!e.altKey&&!e.ctrlKey){var i=t.ui.keyCode,s=this.headers.length,n=this.headers.index(e.target),o=!1;switch(e.keyCode){case i.RIGHT:case i.DOWN:o=this.headers[(n+1)%s];break;case i.LEFT:case i.UP:o=this.headers[(n-1+s)%s];break;case i.SPACE:case i.ENTER:this._eventHandler(e);break;case i.HOME:o=this.headers[0];break;case i.END:o=this.headers[s-1]}o&&(t(e.target).attr("tabIndex",-1),t(o).attr("tabIndex",0),t(o).trigger("focus"),e.preventDefault())}},_panelKeyDown:function(e){e.keyCode===t.ui.keyCode.UP&&e.ctrlKey&&t(e.currentTarget).prev().trigger("focus")},refresh:function(){var e=this.options;this._processPanels(),e.active===!1&&e.collapsible===!0||!this.headers.length?(e.active=!1,this.active=t()):e.active===!1?this._activate(0):this.active.length&&!t.contains(this.element[0],this.active[0])?this.headers.length===this.headers.find(".ui-state-disabled").length?(e.active=!1,this.active=t()):this._activate(Math.max(0,e.active-1)):e.active=this.headers.index(this.active),this._destroyIcons(),this._refresh()},_processPanels:function(){var t=this.headers,e=this.panels;this.headers=this.element.find(this.options.header),this._addClass(this.headers,"ui-accordion-header ui-accordion-header-collapsed","ui-state-default"),this.panels=this.headers.next().filter(":not(.ui-accordion-content-active)").hide(),this._addClass(this.panels,"ui-accordion-content","ui-helper-reset ui-widget-content"),e&&(this._off(t.not(this.headers)),this._off(e.not(this.panels)))},_refresh:function(){var e,i=this.options,s=i.heightStyle,n=this.element.parent();this.active=this._findActive(i.active),this._addClass(this.active,"ui-accordion-header-active","ui-state-active")._removeClass(this.active,"ui-accordion-header-collapsed"),this._addClass(this.active.next(),"ui-accordion-content-active"),this.active.next().show(),this.headers.attr("role","tab").each(function(){var e=t(this),i=e.uniqueId().attr("id"),s=e.next(),n=s.uniqueId().attr("id");e.attr("aria-controls",n),s.attr("aria-labelledby",i)}).next().attr("role","tabpanel"),this.headers.not(this.active).attr({"aria-selected":"false","aria-expanded":"false",tabIndex:-1}).next().attr({"aria-hidden":"true"}).hide(),this.active.length?this.active.attr({"aria-selected":"true","aria-expanded":"true",tabIndex:0}).next().attr({"aria-hidden":"false"}):this.headers.eq(0).attr("tabIndex",0),this._createIcons(),this._setupEvents(i.event),"fill"===s?(e=n.height(),this.element.siblings(":visible").each(function(){var i=t(this),s=i.css("position");"absolute"!==s&&"fixed"!==s&&(e-=i.outerHeight(!0))}),this.headers.each(function(){e-=t(this).outerHeight(!0)}),this.headers.next().each(function(){t(this).height(Math.max(0,e-t(this).innerHeight()+t(this).height()))}).css("overflow","auto")):"auto"===s&&(e=0,this.headers.next().each(function(){var i=t(this).is(":visible");i||t(this).show(),e=Math.max(e,t(this).css("height","").height()),i||t(this).hide()}).height(e))},_activate:function(e){var i=this._findActive(e)[0];i!==this.active[0]&&(i=i||this.active[0],this._eventHandler({target:i,currentTarget:i,preventDefault:t.noop}))},_findActive:function(e){return"number"==typeof e?this.headers.eq(e):t()},_setupEvents:function(e){var i={keydown:"_keydown"};e&&t.each(e.split(" "),function(t,e){i[e]="_eventHandler"}),this._off(this.headers.add(this.headers.next())),this._on(this.headers,i),this._on(this.headers.next(),{keydown:"_panelKeyDown"}),this._hoverable(this.headers),this._focusable(this.headers)},_eventHandler:function(e){var i,s,n=this.options,o=this.active,a=t(e.currentTarget),r=a[0]===o[0],h=r&&n.collapsible,l=h?t():a.next(),c=o.next(),u={oldHeader:o,oldPanel:c,newHeader:h?t():a,newPanel:l};e.preventDefault(),r&&!n.collapsible||this._trigger("beforeActivate",e,u)===!1||(n.active=h?!1:this.headers.index(a),this.active=r?t():a,this._toggle(u),this._removeClass(o,"ui-accordion-header-active","ui-state-active"),n.icons&&(i=o.children(".ui-accordion-header-icon"),this._removeClass(i,null,n.icons.activeHeader)._addClass(i,null,n.icons.header)),r||(this._removeClass(a,"ui-accordion-header-collapsed")._addClass(a,"ui-accordion-header-active","ui-state-active"),n.icons&&(s=a.children(".ui-accordion-header-icon"),this._removeClass(s,null,n.icons.header)._addClass(s,null,n.icons.activeHeader)),this._addClass(a.next(),"ui-accordion-content-active")))},_toggle:function(e){var i=e.newPanel,s=this.prevShow.length?this.prevShow:e.oldPanel;this.prevShow.add(this.prevHide).stop(!0,!0),this.prevShow=i,this.prevHide=s,this.options.animate?this._animate(i,s,e):(s.hide(),i.show(),this._toggleComplete(e)),s.attr({"aria-hidden":"true"}),s.prev().attr({"aria-selected":"false","aria-expanded":"false"}),i.length&&s.length?s.prev().attr({tabIndex:-1,"aria-expanded":"false"}):i.length&&this.headers.filter(function(){return 0===parseInt(t(this).attr("tabIndex"),10)}).attr("tabIndex",-1),i.attr("aria-hidden","false").prev().attr({"aria-selected":"true","aria-expanded":"true",tabIndex:0})},_animate:function(t,e,i){var s,n,o,a=this,r=0,h=t.css("box-sizing"),l=t.length&&(!e.length||t.index()<e.index()),c=this.options.animate||{},u=l&&c.down||c,d=function(){a._toggleComplete(i)};return"number"==typeof u&&(o=u),"string"==typeof u&&(n=u),n=n||u.easing||c.easing,o=o||u.duration||c.duration,e.length?t.length?(s=t.show().outerHeight(),e.animate(this.hideProps,{duration:o,easing:n,step:function(t,e){e.now=Math.round(t)}}),t.hide().animate(this.showProps,{duration:o,easing:n,complete:d,step:function(t,i){i.now=Math.round(t),"height"!==i.prop?"content-box"===h&&(r+=i.now):"content"!==a.options.heightStyle&&(i.now=Math.round(s-e.outerHeight()-r),r=0)}}),void 0):e.animate(this.hideProps,o,n,d):t.animate(this.showProps,o,n,d)},_toggleComplete:function(t){var e=t.oldPanel,i=e.prev();this._removeClass(e,"ui-accordion-content-active"),this._removeClass(i,"ui-accordion-header-active")._addClass(i,"ui-accordion-header-collapsed"),e.length&&(e.parent()[0].className=e.parent()[0].className),this._trigger("activate",null,t)}}),t.ui.safeActiveElement=function(t){var e;try{e=t.activeElement}catch(i){e=t.body}return e||(e=t.body),e.nodeName||(e=t.body),e},t.widget("ui.menu",{version:"1.12.1",defaultElement:"<ul>",delay:300,options:{icons:{submenu:"ui-icon-caret-1-e"},items:"> *",menus:"ul",position:{my:"left top",at:"right top"},role:"menu",blur:null,focus:null,select:null},_create:function(){this.activeMenu=this.element,this.mouseHandled=!1,this.element.uniqueId().attr({role:this.options.role,tabIndex:0}),this._addClass("ui-menu","ui-widget ui-widget-content"),this._on({"mousedown .ui-menu-item":function(t){t.preventDefault()},"click .ui-menu-item":function(e){var i=t(e.target),s=t(t.ui.safeActiveElement(this.document[0]));!this.mouseHandled&&i.not(".ui-state-disabled").length&&(this.select(e),e.isPropagationStopped()||(this.mouseHandled=!0),i.has(".ui-menu").length?this.expand(e):!this.element.is(":focus")&&s.closest(".ui-menu").length&&(this.element.trigger("focus",[!0]),this.active&&1===this.active.parents(".ui-menu").length&&clearTimeout(this.timer)))},"mouseenter .ui-menu-item":function(e){if(!this.previousFilter){var i=t(e.target).closest(".ui-menu-item"),s=t(e.currentTarget);i[0]===s[0]&&(this._removeClass(s.siblings().children(".ui-state-active"),null,"ui-state-active"),this.focus(e,s))}},mouseleave:"collapseAll","mouseleave .ui-menu":"collapseAll",focus:function(t,e){var i=this.active||this.element.find(this.options.items).eq(0);e||this.focus(t,i)},blur:function(e){this._delay(function(){var i=!t.contains(this.element[0],t.ui.safeActiveElement(this.document[0]));i&&this.collapseAll(e)})},keydown:"_keydown"}),this.refresh(),this._on(this.document,{click:function(t){this._closeOnDocumentClick(t)&&this.collapseAll(t),this.mouseHandled=!1}})},_destroy:function(){var e=this.element.find(".ui-menu-item").removeAttr("role aria-disabled"),i=e.children(".ui-menu-item-wrapper").removeUniqueId().removeAttr("tabIndex role aria-haspopup");this.element.removeAttr("aria-activedescendant").find(".ui-menu").addBack().removeAttr("role aria-labelledby aria-expanded aria-hidden aria-disabled tabIndex").removeUniqueId().show(),i.children().each(function(){var e=t(this);e.data("ui-menu-submenu-caret")&&e.remove()})},_keydown:function(e){var i,s,n,o,a=!0;switch(e.keyCode){case t.ui.keyCode.PAGE_UP:this.previousPage(e);break;case t.ui.keyCode.PAGE_DOWN:this.nextPage(e);break;case t.ui.keyCode.HOME:this._move("first","first",e);break;case t.ui.keyCode.END:this._move("last","last",e);break;case t.ui.keyCode.UP:this.previous(e);break;case t.ui.keyCode.DOWN:this.next(e);break;case t.ui.keyCode.LEFT:this.collapse(e);break;case t.ui.keyCode.RIGHT:this.active&&!this.active.is(".ui-state-disabled")&&this.expand(e);break;case t.ui.keyCode.ENTER:case t.ui.keyCode.SPACE:this._activate(e);break;case t.ui.keyCode.ESCAPE:this.collapse(e);break;default:a=!1,s=this.previousFilter||"",o=!1,n=e.keyCode>=96&&105>=e.keyCode?""+(e.keyCode-96):String.fromCharCode(e.keyCode),clearTimeout(this.filterTimer),n===s?o=!0:n=s+n,i=this._filterMenuItems(n),i=o&&-1!==i.index(this.active.next())?this.active.nextAll(".ui-menu-item"):i,i.length||(n=String.fromCharCode(e.keyCode),i=this._filterMenuItems(n)),i.length?(this.focus(e,i),this.previousFilter=n,this.filterTimer=this._delay(function(){delete this.previousFilter},1e3)):delete this.previousFilter}a&&e.preventDefault()},_activate:function(t){this.active&&!this.active.is(".ui-state-disabled")&&(this.active.children("[aria-haspopup='true']").length?this.expand(t):this.select(t))},refresh:function(){var e,i,s,n,o,a=this,r=this.options.icons.submenu,h=this.element.find(this.options.menus);this._toggleClass("ui-menu-icons",null,!!this.element.find(".ui-icon").length),s=h.filter(":not(.ui-menu)").hide().attr({role:this.options.role,"aria-hidden":"true","aria-expanded":"false"}).each(function(){var e=t(this),i=e.prev(),s=t("<span>").data("ui-menu-submenu-caret",!0);a._addClass(s,"ui-menu-icon","ui-icon "+r),i.attr("aria-haspopup","true").prepend(s),e.attr("aria-labelledby",i.attr("id"))}),this._addClass(s,"ui-menu","ui-widget ui-widget-content ui-front"),e=h.add(this.element),i=e.find(this.options.items),i.not(".ui-menu-item").each(function(){var e=t(this);a._isDivider(e)&&a._addClass(e,"ui-menu-divider","ui-widget-content")}),n=i.not(".ui-menu-item, .ui-menu-divider"),o=n.children().not(".ui-menu").uniqueId().attr({tabIndex:-1,role:this._itemRole()}),this._addClass(n,"ui-menu-item")._addClass(o,"ui-menu-item-wrapper"),i.filter(".ui-state-disabled").attr("aria-disabled","true"),this.active&&!t.contains(this.element[0],this.active[0])&&this.blur()},_itemRole:function(){return{menu:"menuitem",listbox:"option"}[this.options.role]},_setOption:function(t,e){if("icons"===t){var i=this.element.find(".ui-menu-icon");this._removeClass(i,null,this.options.icons.submenu)._addClass(i,null,e.submenu)}this._super(t,e)},_setOptionDisabled:function(t){this._super(t),this.element.attr("aria-disabled",t+""),this._toggleClass(null,"ui-state-disabled",!!t)},focus:function(t,e){var i,s,n;this.blur(t,t&&"focus"===t.type),this._scrollIntoView(e),this.active=e.first(),s=this.active.children(".ui-menu-item-wrapper"),this._addClass(s,null,"ui-state-active"),this.options.role&&this.element.attr("aria-activedescendant",s.attr("id")),n=this.active.parent().closest(".ui-menu-item").children(".ui-menu-item-wrapper"),this._addClass(n,null,"ui-state-active"),t&&"keydown"===t.type?this._close():this.timer=this._delay(function(){this._close()},this.delay),i=e.children(".ui-menu"),i.length&&t&&/^mouse/.test(t.type)&&this._startOpening(i),this.activeMenu=e.parent(),this._trigger("focus",t,{item:e})},_scrollIntoView:function(e){var i,s,n,o,a,r;this._hasScroll()&&(i=parseFloat(t.css(this.activeMenu[0],"borderTopWidth"))||0,s=parseFloat(t.css(this.activeMenu[0],"paddingTop"))||0,n=e.offset().top-this.activeMenu.offset().top-i-s,o=this.activeMenu.scrollTop(),a=this.activeMenu.height(),r=e.outerHeight(),0>n?this.activeMenu.scrollTop(o+n):n+r>a&&this.activeMenu.scrollTop(o+n-a+r))},blur:function(t,e){e||clearTimeout(this.timer),this.active&&(this._removeClass(this.active.children(".ui-menu-item-wrapper"),null,"ui-state-active"),this._trigger("blur",t,{item:this.active}),this.active=null)},_startOpening:function(t){clearTimeout(this.timer),"true"===t.attr("aria-hidden")&&(this.timer=this._delay(function(){this._close(),this._open(t)},this.delay))},_open:function(e){var i=t.extend({of:this.active},this.options.position);clearTimeout(this.timer),this.element.find(".ui-menu").not(e.parents(".ui-menu")).hide().attr("aria-hidden","true"),e.show().removeAttr("aria-hidden").attr("aria-expanded","true").position(i)},collapseAll:function(e,i){clearTimeout(this.timer),this.timer=this._delay(function(){var s=i?this.element:t(e&&e.target).closest(this.element.find(".ui-menu"));s.length||(s=this.element),this._close(s),this.blur(e),this._removeClass(s.find(".ui-state-active"),null,"ui-state-active"),this.activeMenu=s},this.delay)},_close:function(t){t||(t=this.active?this.active.parent():this.element),t.find(".ui-menu").hide().attr("aria-hidden","true").attr("aria-expanded","false")},_closeOnDocumentClick:function(e){return!t(e.target).closest(".ui-menu").length},_isDivider:function(t){return!/[^\-\u2014\u2013\s]/.test(t.text())},collapse:function(t){var e=this.active&&this.active.parent().closest(".ui-menu-item",this.element);e&&e.length&&(this._close(),this.focus(t,e))},expand:function(t){var e=this.active&&this.active.children(".ui-menu ").find(this.options.items).first();e&&e.length&&(this._open(e.parent()),this._delay(function(){this.focus(t,e)}))},next:function(t){this._move("next","first",t)},previous:function(t){this._move("prev","last",t)},isFirstItem:function(){return this.active&&!this.active.prevAll(".ui-menu-item").length},isLastItem:function(){return this.active&&!this.active.nextAll(".ui-menu-item").length},_move:function(t,e,i){var s;this.active&&(s="first"===t||"last"===t?this.active["first"===t?"prevAll":"nextAll"](".ui-menu-item").eq(-1):this.active[t+"All"](".ui-menu-item").eq(0)),s&&s.length&&this.active||(s=this.activeMenu.find(this.options.items)[e]()),this.focus(i,s)},nextPage:function(e){var i,s,n;return this.active?(this.isLastItem()||(this._hasScroll()?(s=this.active.offset().top,n=this.element.height(),this.active.nextAll(".ui-menu-item").each(function(){return i=t(this),0>i.offset().top-s-n}),this.focus(e,i)):this.focus(e,this.activeMenu.find(this.options.items)[this.active?"last":"first"]())),void 0):(this.next(e),void 0)},previousPage:function(e){var i,s,n;return this.active?(this.isFirstItem()||(this._hasScroll()?(s=this.active.offset().top,n=this.element.height(),this.active.prevAll(".ui-menu-item").each(function(){return i=t(this),i.offset().top-s+n>0}),this.focus(e,i)):this.focus(e,this.activeMenu.find(this.options.items).first())),void 0):(this.next(e),void 0)},_hasScroll:function(){return this.element.outerHeight()<this.element.prop("scrollHeight")},select:function(e){this.active=this.active||t(e.target).closest(".ui-menu-item");var i={item:this.active};this.active.has(".ui-menu").length||this.collapseAll(e,!0),this._trigger("select",e,i)},_filterMenuItems:function(e){var i=e.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&"),s=RegExp("^"+i,"i");return this.activeMenu.find(this.options.items).filter(".ui-menu-item").filter(function(){return s.test(t.trim(t(this).children(".ui-menu-item-wrapper").text()))})}}),t.widget("ui.autocomplete",{version:"1.12.1",defaultElement:"<input>",options:{appendTo:null,autoFocus:!1,delay:300,minLength:1,position:{my:"left top",at:"left bottom",collision:"none"},source:null,change:null,close:null,focus:null,open:null,response:null,search:null,select:null},requestIndex:0,pending:0,_create:function(){var e,i,s,n=this.element[0].nodeName.toLowerCase(),o="textarea"===n,a="input"===n;
1228this.isMultiLine=o||!a&&this._isContentEditable(this.element),this.valueMethod=this.element[o||a?"val":"text"],this.isNewMenu=!0,this._addClass("ui-autocomplete-input"),this.element.attr("autocomplete","off"),this._on(this.element,{keydown:function(n){if(this.element.prop("readOnly"))return e=!0,s=!0,i=!0,void 0;e=!1,s=!1,i=!1;var o=t.ui.keyCode;switch(n.keyCode){case o.PAGE_UP:e=!0,this._move("previousPage",n);break;case o.PAGE_DOWN:e=!0,this._move("nextPage",n);break;case o.UP:e=!0,this._keyEvent("previous",n);break;case o.DOWN:e=!0,this._keyEvent("next",n);break;case o.ENTER:this.menu.active&&(e=!0,n.preventDefault(),this.menu.select(n));break;case o.TAB:this.menu.active&&this.menu.select(n);break;case o.ESCAPE:this.menu.element.is(":visible")&&(this.isMultiLine||this._value(this.term),this.close(n),n.preventDefault());break;default:i=!0,this._searchTimeout(n)}},keypress:function(s){if(e)return e=!1,(!this.isMultiLine||this.menu.element.is(":visible"))&&s.preventDefault(),void 0;if(!i){var n=t.ui.keyCode;switch(s.keyCode){case n.PAGE_UP:this._move("previousPage",s);break;case n.PAGE_DOWN:this._move("nextPage",s);break;case n.UP:this._keyEvent("previous",s);break;case n.DOWN:this._keyEvent("next",s)}}},input:function(t){return s?(s=!1,t.preventDefault(),void 0):(this._searchTimeout(t),void 0)},focus:function(){this.selectedItem=null,this.previous=this._value()},blur:function(t){return this.cancelBlur?(delete this.cancelBlur,void 0):(clearTimeout(this.searching),this.close(t),this._change(t),void 0)}}),this._initSource(),this.menu=t("<ul>").appendTo(this._appendTo()).menu({role:null}).hide().menu("instance"),this._addClass(this.menu.element,"ui-autocomplete","ui-front"),this._on(this.menu.element,{mousedown:function(e){e.preventDefault(),this.cancelBlur=!0,this._delay(function(){delete this.cancelBlur,this.element[0]!==t.ui.safeActiveElement(this.document[0])&&this.element.trigger("focus")})},menufocus:function(e,i){var s,n;return this.isNewMenu&&(this.isNewMenu=!1,e.originalEvent&&/^mouse/.test(e.originalEvent.type))?(this.menu.blur(),this.document.one("mousemove",function(){t(e.target).trigger(e.originalEvent)}),void 0):(n=i.item.data("ui-autocomplete-item"),!1!==this._trigger("focus",e,{item:n})&&e.originalEvent&&/^key/.test(e.originalEvent.type)&&this._value(n.value),s=i.item.attr("aria-label")||n.value,s&&t.trim(s).length&&(this.liveRegion.children().hide(),t("<div>").text(s).appendTo(this.liveRegion)),void 0)},menuselect:function(e,i){var s=i.item.data("ui-autocomplete-item"),n=this.previous;this.element[0]!==t.ui.safeActiveElement(this.document[0])&&(this.element.trigger("focus"),this.previous=n,this._delay(function(){this.previous=n,this.selectedItem=s})),!1!==this._trigger("select",e,{item:s})&&this._value(s.value),this.term=this._value(),this.close(e),this.selectedItem=s}}),this.liveRegion=t("<div>",{role:"status","aria-live":"assertive","aria-relevant":"additions"}).appendTo(this.document[0].body),this._addClass(this.liveRegion,null,"ui-helper-hidden-accessible"),this._on(this.window,{beforeunload:function(){this.element.removeAttr("autocomplete")}})},_destroy:function(){clearTimeout(this.searching),this.element.removeAttr("autocomplete"),this.menu.element.remove(),this.liveRegion.remove()},_setOption:function(t,e){this._super(t,e),"source"===t&&this._initSource(),"appendTo"===t&&this.menu.element.appendTo(this._appendTo()),"disabled"===t&&e&&this.xhr&&this.xhr.abort()},_isEventTargetInWidget:function(e){var i=this.menu.element[0];return e.target===this.element[0]||e.target===i||t.contains(i,e.target)},_closeOnClickOutside:function(t){this._isEventTargetInWidget(t)||this.close()},_appendTo:function(){var e=this.options.appendTo;return e&&(e=e.jquery||e.nodeType?t(e):this.document.find(e).eq(0)),e&&e[0]||(e=this.element.closest(".ui-front, dialog")),e.length||(e=this.document[0].body),e},_initSource:function(){var e,i,s=this;t.isArray(this.options.source)?(e=this.options.source,this.source=function(i,s){s(t.ui.autocomplete.filter(e,i.term))}):"string"==typeof this.options.source?(i=this.options.source,this.source=function(e,n){s.xhr&&s.xhr.abort(),s.xhr=t.ajax({url:i,data:e,dataType:"json",success:function(t){n(t)},error:function(){n([])}})}):this.source=this.options.source},_searchTimeout:function(t){clearTimeout(this.searching),this.searching=this._delay(function(){var e=this.term===this._value(),i=this.menu.element.is(":visible"),s=t.altKey||t.ctrlKey||t.metaKey||t.shiftKey;(!e||e&&!i&&!s)&&(this.selectedItem=null,this.search(null,t))},this.options.delay)},search:function(t,e){return t=null!=t?t:this._value(),this.term=this._value(),t.length<this.options.minLength?this.close(e):this._trigger("search",e)!==!1?this._search(t):void 0},_search:function(t){this.pending++,this._addClass("ui-autocomplete-loading"),this.cancelSearch=!1,this.source({term:t},this._response())},_response:function(){var e=++this.requestIndex;return t.proxy(function(t){e===this.requestIndex&&this.__response(t),this.pending--,this.pending||this._removeClass("ui-autocomplete-loading")},this)},__response:function(t){t&&(t=this._normalize(t)),this._trigger("response",null,{content:t}),!this.options.disabled&&t&&t.length&&!this.cancelSearch?(this._suggest(t),this._trigger("open")):this._close()},close:function(t){this.cancelSearch=!0,this._close(t)},_close:function(t){this._off(this.document,"mousedown"),this.menu.element.is(":visible")&&(this.menu.element.hide(),this.menu.blur(),this.isNewMenu=!0,this._trigger("close",t))},_change:function(t){this.previous!==this._value()&&this._trigger("change",t,{item:this.selectedItem})},_normalize:function(e){return e.length&&e[0].label&&e[0].value?e:t.map(e,function(e){return"string"==typeof e?{label:e,value:e}:t.extend({},e,{label:e.label||e.value,value:e.value||e.label})})},_suggest:function(e){var i=this.menu.element.empty();this._renderMenu(i,e),this.isNewMenu=!0,this.menu.refresh(),i.show(),this._resizeMenu(),i.position(t.extend({of:this.element},this.options.position)),this.options.autoFocus&&this.menu.next(),this._on(this.document,{mousedown:"_closeOnClickOutside"})},_resizeMenu:function(){var t=this.menu.element;t.outerWidth(Math.max(t.width("").outerWidth()+1,this.element.outerWidth()))},_renderMenu:function(e,i){var s=this;t.each(i,function(t,i){s._renderItemData(e,i)})},_renderItemData:function(t,e){return this._renderItem(t,e).data("ui-autocomplete-item",e)},_renderItem:function(e,i){return t("<li>").append(t("<div>").text(i.label)).appendTo(e)},_move:function(t,e){return this.menu.element.is(":visible")?this.menu.isFirstItem()&&/^previous/.test(t)||this.menu.isLastItem()&&/^next/.test(t)?(this.isMultiLine||this._value(this.term),this.menu.blur(),void 0):(this.menu[t](e),void 0):(this.search(null,e),void 0)},widget:function(){return this.menu.element},_value:function(){return this.valueMethod.apply(this.element,arguments)},_keyEvent:function(t,e){(!this.isMultiLine||this.menu.element.is(":visible"))&&(this._move(t,e),e.preventDefault())},_isContentEditable:function(t){if(!t.length)return!1;var e=t.prop("contentEditable");return"inherit"===e?this._isContentEditable(t.parent()):"true"===e}}),t.extend(t.ui.autocomplete,{escapeRegex:function(t){return t.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")},filter:function(e,i){var s=RegExp(t.ui.autocomplete.escapeRegex(i),"i");return t.grep(e,function(t){return s.test(t.label||t.value||t)})}}),t.widget("ui.autocomplete",t.ui.autocomplete,{options:{messages:{noResults:"No search results.",results:function(t){return t+(t>1?" results are":" result is")+" available, use up and down arrow keys to navigate."}}},__response:function(e){var i;this._superApply(arguments),this.options.disabled||this.cancelSearch||(i=e&&e.length?this.options.messages.results(e.length):this.options.messages.noResults,this.liveRegion.children().hide(),t("<div>").text(i).appendTo(this.liveRegion))}}),t.ui.autocomplete;var g=/ui-corner-([a-z]){2,6}/g;t.widget("ui.controlgroup",{version:"1.12.1",defaultElement:"<div>",options:{direction:"horizontal",disabled:null,onlyVisible:!0,items:{button:"input[type=button], input[type=submit], input[type=reset], button, a",controlgroupLabel:".ui-controlgroup-label",checkboxradio:"input[type='checkbox'], input[type='radio']",selectmenu:"select",spinner:".ui-spinner-input"}},_create:function(){this._enhance()},_enhance:function(){this.element.attr("role","toolbar"),this.refresh()},_destroy:function(){this._callChildMethod("destroy"),this.childWidgets.removeData("ui-controlgroup-data"),this.element.removeAttr("role"),this.options.items.controlgroupLabel&&this.element.find(this.options.items.controlgroupLabel).find(".ui-controlgroup-label-contents").contents().unwrap()},_initWidgets:function(){var e=this,i=[];t.each(this.options.items,function(s,n){var o,a={};return n?"controlgroupLabel"===s?(o=e.element.find(n),o.each(function(){var e=t(this);e.children(".ui-controlgroup-label-contents").length||e.contents().wrapAll("<span class='ui-controlgroup-label-contents'></span>")}),e._addClass(o,null,"ui-widget ui-widget-content ui-state-default"),i=i.concat(o.get()),void 0):(t.fn[s]&&(a=e["_"+s+"Options"]?e["_"+s+"Options"]("middle"):{classes:{}},e.element.find(n).each(function(){var n=t(this),o=n[s]("instance"),r=t.widget.extend({},a);if("button"!==s||!n.parent(".ui-spinner").length){o||(o=n[s]()[s]("instance")),o&&(r.classes=e._resolveClassesValues(r.classes,o)),n[s](r);var h=n[s]("widget");t.data(h[0],"ui-controlgroup-data",o?o:n[s]("instance")),i.push(h[0])}})),void 0):void 0}),this.childWidgets=t(t.unique(i)),this._addClass(this.childWidgets,"ui-controlgroup-item")},_callChildMethod:function(e){this.childWidgets.each(function(){var i=t(this),s=i.data("ui-controlgroup-data");s&&s[e]&&s[e]()})},_updateCornerClass:function(t,e){var i="ui-corner-top ui-corner-bottom ui-corner-left ui-corner-right ui-corner-all",s=this._buildSimpleOptions(e,"label").classes.label;this._removeClass(t,null,i),this._addClass(t,null,s)},_buildSimpleOptions:function(t,e){var i="vertical"===this.options.direction,s={classes:{}};return s.classes[e]={middle:"",first:"ui-corner-"+(i?"top":"left"),last:"ui-corner-"+(i?"bottom":"right"),only:"ui-corner-all"}[t],s},_spinnerOptions:function(t){var e=this._buildSimpleOptions(t,"ui-spinner");return e.classes["ui-spinner-up"]="",e.classes["ui-spinner-down"]="",e},_buttonOptions:function(t){return this._buildSimpleOptions(t,"ui-button")},_checkboxradioOptions:function(t){return this._buildSimpleOptions(t,"ui-checkboxradio-label")},_selectmenuOptions:function(t){var e="vertical"===this.options.direction;return{width:e?"auto":!1,classes:{middle:{"ui-selectmenu-button-open":"","ui-selectmenu-button-closed":""},first:{"ui-selectmenu-button-open":"ui-corner-"+(e?"top":"tl"),"ui-selectmenu-button-closed":"ui-corner-"+(e?"top":"left")},last:{"ui-selectmenu-button-open":e?"":"ui-corner-tr","ui-selectmenu-button-closed":"ui-corner-"+(e?"bottom":"right")},only:{"ui-selectmenu-button-open":"ui-corner-top","ui-selectmenu-button-closed":"ui-corner-all"}}[t]}},_resolveClassesValues:function(e,i){var s={};return t.each(e,function(n){var o=i.options.classes[n]||"";o=t.trim(o.replace(g,"")),s[n]=(o+" "+e[n]).replace(/\s+/g," ")}),s},_setOption:function(t,e){return"direction"===t&&this._removeClass("ui-controlgroup-"+this.options.direction),this._super(t,e),"disabled"===t?(this._callChildMethod(e?"disable":"enable"),void 0):(this.refresh(),void 0)},refresh:function(){var e,i=this;this._addClass("ui-controlgroup ui-controlgroup-"+this.options.direction),"horizontal"===this.options.direction&&this._addClass(null,"ui-helper-clearfix"),this._initWidgets(),e=this.childWidgets,this.options.onlyVisible&&(e=e.filter(":visible")),e.length&&(t.each(["first","last"],function(t,s){var n=e[s]().data("ui-controlgroup-data");if(n&&i["_"+n.widgetName+"Options"]){var o=i["_"+n.widgetName+"Options"](1===e.length?"only":s);o.classes=i._resolveClassesValues(o.classes,n),n.element[n.widgetName](o)}else i._updateCornerClass(e[s](),s)}),this._callChildMethod("refresh"))}}),t.widget("ui.checkboxradio",[t.ui.formResetMixin,{version:"1.12.1",options:{disabled:null,label:null,icon:!0,classes:{"ui-checkboxradio-label":"ui-corner-all","ui-checkboxradio-icon":"ui-corner-all"}},_getCreateOptions:function(){var e,i,s=this,n=this._super()||{};return this._readType(),i=this.element.labels(),this.label=t(i[i.length-1]),this.label.length||t.error("No label found for checkboxradio widget"),this.originalLabel="",this.label.contents().not(this.element[0]).each(function(){s.originalLabel+=3===this.nodeType?t(this).text():this.outerHTML}),this.originalLabel&&(n.label=this.originalLabel),e=this.element[0].disabled,null!=e&&(n.disabled=e),n},_create:function(){var t=this.element[0].checked;this._bindFormResetHandler(),null==this.options.disabled&&(this.options.disabled=this.element[0].disabled),this._setOption("disabled",this.options.disabled),this._addClass("ui-checkboxradio","ui-helper-hidden-accessible"),this._addClass(this.label,"ui-checkboxradio-label","ui-button ui-widget"),"radio"===this.type&&this._addClass(this.label,"ui-checkboxradio-radio-label"),this.options.label&&this.options.label!==this.originalLabel?this._updateLabel():this.originalLabel&&(this.options.label=this.originalLabel),this._enhance(),t&&(this._addClass(this.label,"ui-checkboxradio-checked","ui-state-active"),this.icon&&this._addClass(this.icon,null,"ui-state-hover")),this._on({change:"_toggleClasses",focus:function(){this._addClass(this.label,null,"ui-state-focus ui-visual-focus")},blur:function(){this._removeClass(this.label,null,"ui-state-focus ui-visual-focus")}})},_readType:function(){var e=this.element[0].nodeName.toLowerCase();this.type=this.element[0].type,"input"===e&&/radio|checkbox/.test(this.type)||t.error("Can't create checkboxradio on element.nodeName="+e+" and element.type="+this.type)},_enhance:function(){this._updateIcon(this.element[0].checked)},widget:function(){return this.label},_getRadioGroup:function(){var e,i=this.element[0].name,s="input[name='"+t.ui.escapeSelector(i)+"']";return i?(e=this.form.length?t(this.form[0].elements).filter(s):t(s).filter(function(){return 0===t(this).form().length}),e.not(this.element)):t([])},_toggleClasses:function(){var e=this.element[0].checked;this._toggleClass(this.label,"ui-checkboxradio-checked","ui-state-active",e),this.options.icon&&"checkbox"===this.type&&this._toggleClass(this.icon,null,"ui-icon-check ui-state-checked",e)._toggleClass(this.icon,null,"ui-icon-blank",!e),"radio"===this.type&&this._getRadioGroup().each(function(){var e=t(this).checkboxradio("instance");e&&e._removeClass(e.label,"ui-checkboxradio-checked","ui-state-active")})},_destroy:function(){this._unbindFormResetHandler(),this.icon&&(this.icon.remove(),this.iconSpace.remove())},_setOption:function(t,e){return"label"!==t||e?(this._super(t,e),"disabled"===t?(this._toggleClass(this.label,null,"ui-state-disabled",e),this.element[0].disabled=e,void 0):(this.refresh(),void 0)):void 0},_updateIcon:function(e){var i="ui-icon ui-icon-background ";this.options.icon?(this.icon||(this.icon=t("<span>"),this.iconSpace=t("<span> </span>"),this._addClass(this.iconSpace,"ui-checkboxradio-icon-space")),"checkbox"===this.type?(i+=e?"ui-icon-check ui-state-checked":"ui-icon-blank",this._removeClass(this.icon,null,e?"ui-icon-blank":"ui-icon-check")):i+="ui-icon-blank",this._addClass(this.icon,"ui-checkboxradio-icon",i),e||this._removeClass(this.icon,null,"ui-icon-check ui-state-checked"),this.icon.prependTo(this.label).after(this.iconSpace)):void 0!==this.icon&&(this.icon.remove(),this.iconSpace.remove(),delete this.icon)},_updateLabel:function(){var t=this.label.contents().not(this.element[0]);this.icon&&(t=t.not(this.icon[0])),this.iconSpace&&(t=t.not(this.iconSpace[0])),t.remove(),this.label.append(this.options.label)},refresh:function(){var t=this.element[0].checked,e=this.element[0].disabled;this._updateIcon(t),this._toggleClass(this.label,"ui-checkboxradio-checked","ui-state-active",t),null!==this.options.label&&this._updateLabel(),e!==this.options.disabled&&this._setOptions({disabled:e})}}]),t.ui.checkboxradio,t.widget("ui.button",{version:"1.12.1",defaultElement:"<button>",options:{classes:{"ui-button":"ui-corner-all"},disabled:null,icon:null,iconPosition:"beginning",label:null,showLabel:!0},_getCreateOptions:function(){var t,e=this._super()||{};return this.isInput=this.element.is("input"),t=this.element[0].disabled,null!=t&&(e.disabled=t),this.originalLabel=this.isInput?this.element.val():this.element.html(),this.originalLabel&&(e.label=this.originalLabel),e},_create:function(){!this.option.showLabel&!this.options.icon&&(this.options.showLabel=!0),null==this.options.disabled&&(this.options.disabled=this.element[0].disabled||!1),this.hasTitle=!!this.element.attr("title"),this.options.label&&this.options.label!==this.originalLabel&&(this.isInput?this.element.val(this.options.label):this.element.html(this.options.label)),this._addClass("ui-button","ui-widget"),this._setOption("disabled",this.options.disabled),this._enhance(),this.element.is("a")&&this._on({keyup:function(e){e.keyCode===t.ui.keyCode.SPACE&&(e.preventDefault(),this.element[0].click?this.element[0].click():this.element.trigger("click"))}})},_enhance:function(){this.element.is("button")||this.element.attr("role","button"),this.options.icon&&(this._updateIcon("icon",this.options.icon),this._updateTooltip())},_updateTooltip:function(){this.title=this.element.attr("title"),this.options.showLabel||this.title||this.element.attr("title",this.options.label)},_updateIcon:function(e,i){var s="iconPosition"!==e,n=s?this.options.iconPosition:i,o="top"===n||"bottom"===n;this.icon?s&&this._removeClass(this.icon,null,this.options.icon):(this.icon=t("<span>"),this._addClass(this.icon,"ui-button-icon","ui-icon"),this.options.showLabel||this._addClass("ui-button-icon-only")),s&&this._addClass(this.icon,null,i),this._attachIcon(n),o?(this._addClass(this.icon,null,"ui-widget-icon-block"),this.iconSpace&&this.iconSpace.remove()):(this.iconSpace||(this.iconSpace=t("<span> </span>"),this._addClass(this.iconSpace,"ui-button-icon-space")),this._removeClass(this.icon,null,"ui-wiget-icon-block"),this._attachIconSpace(n))},_destroy:function(){this.element.removeAttr("role"),this.icon&&this.icon.remove(),this.iconSpace&&this.iconSpace.remove(),this.hasTitle||this.element.removeAttr("title")},_attachIconSpace:function(t){this.icon[/^(?:end|bottom)/.test(t)?"before":"after"](this.iconSpace)},_attachIcon:function(t){this.element[/^(?:end|bottom)/.test(t)?"append":"prepend"](this.icon)},_setOptions:function(t){var e=void 0===t.showLabel?this.options.showLabel:t.showLabel,i=void 0===t.icon?this.options.icon:t.icon;e||i||(t.showLabel=!0),this._super(t)},_setOption:function(t,e){"icon"===t&&(e?this._updateIcon(t,e):this.icon&&(this.icon.remove(),this.iconSpace&&this.iconSpace.remove())),"iconPosition"===t&&this._updateIcon(t,e),"showLabel"===t&&(this._toggleClass("ui-button-icon-only",null,!e),this._updateTooltip()),"label"===t&&(this.isInput?this.element.val(e):(this.element.html(e),this.icon&&(this._attachIcon(this.options.iconPosition),this._attachIconSpace(this.options.iconPosition)))),this._super(t,e),"disabled"===t&&(this._toggleClass(null,"ui-state-disabled",e),this.element[0].disabled=e,e&&this.element.blur())},refresh:function(){var t=this.element.is("input, button")?this.element[0].disabled:this.element.hasClass("ui-button-disabled");t!==this.options.disabled&&this._setOptions({disabled:t}),this._updateTooltip()}}),t.uiBackCompat!==!1&&(t.widget("ui.button",t.ui.button,{options:{text:!0,icons:{primary:null,secondary:null}},_create:function(){this.options.showLabel&&!this.options.text&&(this.options.showLabel=this.options.text),!this.options.showLabel&&this.options.text&&(this.options.text=this.options.showLabel),this.options.icon||!this.options.icons.primary&&!this.options.icons.secondary?this.options.icon&&(this.options.icons.primary=this.options.icon):this.options.icons.primary?this.options.icon=this.options.icons.primary:(this.options.icon=this.options.icons.secondary,this.options.iconPosition="end"),this._super()},_setOption:function(t,e){return"text"===t?(this._super("showLabel",e),void 0):("showLabel"===t&&(this.options.text=e),"icon"===t&&(this.options.icons.primary=e),"icons"===t&&(e.primary?(this._super("icon",e.primary),this._super("iconPosition","beginning")):e.secondary&&(this._super("icon",e.secondary),this._super("iconPosition","end"))),this._superApply(arguments),void 0)}}),t.fn.button=function(e){return function(){return!this.length||this.length&&"INPUT"!==this[0].tagName||this.length&&"INPUT"===this[0].tagName&&"checkbox"!==this.attr("type")&&"radio"!==this.attr("type")?e.apply(this,arguments):(t.ui.checkboxradio||t.error("Checkboxradio widget missing"),0===arguments.length?this.checkboxradio({icon:!1}):this.checkboxradio.apply(this,arguments))}}(t.fn.button),t.fn.buttonset=function(){return t.ui.controlgroup||t.error("Controlgroup widget missing"),"option"===arguments[0]&&"items"===arguments[1]&&arguments[2]?this.controlgroup.apply(this,[arguments[0],"items.button",arguments[2]]):"option"===arguments[0]&&"items"===arguments[1]?this.controlgroup.apply(this,[arguments[0],"items.button"]):("object"==typeof arguments[0]&&arguments[0].items&&(arguments[0].items={button:arguments[0].items}),this.controlgroup.apply(this,arguments))}),t.ui.button,t.extend(t.ui,{datepicker:{version:"1.12.1"}});var m;t.extend(s.prototype,{markerClassName:"hasDatepicker",maxRows:4,_widgetDatepicker:function(){return this.dpDiv},setDefaults:function(t){return a(this._defaults,t||{}),this},_attachDatepicker:function(e,i){var s,n,o;s=e.nodeName.toLowerCase(),n="div"===s||"span"===s,e.id||(this.uuid+=1,e.id="dp"+this.uuid),o=this._newInst(t(e),n),o.settings=t.extend({},i||{}),"input"===s?this._connectDatepicker(e,o):n&&this._inlineDatepicker(e,o)},_newInst:function(e,i){var s=e[0].id.replace(/([^A-Za-z0-9_\-])/g,"\\\\$1");return{id:s,input:e,selectedDay:0,selectedMonth:0,selectedYear:0,drawMonth:0,drawYear:0,inline:i,dpDiv:i?n(t("<div class='"+this._inlineClass+" ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all'></div>")):this.dpDiv}},_connectDatepicker:function(e,i){var s=t(e);i.append=t([]),i.trigger=t([]),s.hasClass(this.markerClassName)||(this._attachments(s,i),s.addClass(this.markerClassName).on("keydown",this._doKeyDown).on("keypress",this._doKeyPress).on("keyup",this._doKeyUp),this._autoSize(i),t.data(e,"datepicker",i),i.settings.disabled&&this._disableDatepicker(e))},_attachments:function(e,i){var s,n,o,a=this._get(i,"appendText"),r=this._get(i,"isRTL");i.append&&i.append.remove(),a&&(i.append=t("<span class='"+this._appendClass+"'>"+a+"</span>"),e[r?"before":"after"](i.append)),e.off("focus",this._showDatepicker),i.trigger&&i.trigger.remove(),s=this._get(i,"showOn"),("focus"===s||"both"===s)&&e.on("focus",this._showDatepicker),("button"===s||"both"===s)&&(n=this._get(i,"buttonText"),o=this._get(i,"buttonImage"),i.trigger=t(this._get(i,"buttonImageOnly")?t("<img/>").addClass(this._triggerClass).attr({src:o,alt:n,title:n}):t("<button type='button'></button>").addClass(this._triggerClass).html(o?t("<img/>").attr({src:o,alt:n,title:n}):n)),e[r?"before":"after"](i.trigger),i.trigger.on("click",function(){return t.datepicker._datepickerShowing&&t.datepicker._lastInput===e[0]?t.datepicker._hideDatepicker():t.datepicker._datepickerShowing&&t.datepicker._lastInput!==e[0]?(t.datepicker._hideDatepicker(),t.datepicker._showDatepicker(e[0])):t.datepicker._showDatepicker(e[0]),!1}))},_autoSize:function(t){if(this._get(t,"autoSize")&&!t.inline){var e,i,s,n,o=new Date(2009,11,20),a=this._get(t,"dateFormat");a.match(/[DM]/)&&(e=function(t){for(i=0,s=0,n=0;t.length>n;n++)t[n].length>i&&(i=t[n].length,s=n);return s},o.setMonth(e(this._get(t,a.match(/MM/)?"monthNames":"monthNamesShort"))),o.setDate(e(this._get(t,a.match(/DD/)?"dayNames":"dayNamesShort"))+20-o.getDay())),t.input.attr("size",this._formatDate(t,o).length)}},_inlineDatepicker:function(e,i){var s=t(e);s.hasClass(this.markerClassName)||(s.addClass(this.markerClassName).append(i.dpDiv),t.data(e,"datepicker",i),this._setDate(i,this._getDefaultDate(i),!0),this._updateDatepicker(i),this._updateAlternate(i),i.settings.disabled&&this._disableDatepicker(e),i.dpDiv.css("display","block"))},_dialogDatepicker:function(e,i,s,n,o){var r,h,l,c,u,d=this._dialogInst;return d||(this.uuid+=1,r="dp"+this.uuid,this._dialogInput=t("<input type='text' id='"+r+"' style='position: absolute; top: -100px; width: 0px;'/>"),this._dialogInput.on("keydown",this._doKeyDown),t("body").append(this._dialogInput),d=this._dialogInst=this._newInst(this._dialogInput,!1),d.settings={},t.data(this._dialogInput[0],"datepicker",d)),a(d.settings,n||{}),i=i&&i.constructor===Date?this._formatDate(d,i):i,this._dialogInput.val(i),this._pos=o?o.length?o:[o.pageX,o.pageY]:null,this._pos||(h=document.documentElement.clientWidth,l=document.documentElement.clientHeight,c=document.documentElement.scrollLeft||document.body.scrollLeft,u=document.documentElement.scrollTop||document.body.scrollTop,this._pos=[h/2-100+c,l/2-150+u]),this._dialogInput.css("left",this._pos[0]+20+"px").css("top",this._pos[1]+"px"),d.settings.onSelect=s,this._inDialog=!0,this.dpDiv.addClass(this._dialogClass),this._showDatepicker(this._dialogInput[0]),t.blockUI&&t.blockUI(this.dpDiv),t.data(this._dialogInput[0],"datepicker",d),this},_destroyDatepicker:function(e){var i,s=t(e),n=t.data(e,"datepicker");s.hasClass(this.markerClassName)&&(i=e.nodeName.toLowerCase(),t.removeData(e,"datepicker"),"input"===i?(n.append.remove(),n.trigger.remove(),s.removeClass(this.markerClassName).off("focus",this._showDatepicker).off("keydown",this._doKeyDown).off("keypress",this._doKeyPress).off("keyup",this._doKeyUp)):("div"===i||"span"===i)&&s.removeClass(this.markerClassName).empty(),m===n&&(m=null))},_enableDatepicker:function(e){var i,s,n=t(e),o=t.data(e,"datepicker");n.hasClass(this.markerClassName)&&(i=e.nodeName.toLowerCase(),"input"===i?(e.disabled=!1,o.trigger.filter("button").each(function(){this.disabled=!1}).end().filter("img").css({opacity:"1.0",cursor:""})):("div"===i||"span"===i)&&(s=n.children("."+this._inlineClass),s.children().removeClass("ui-state-disabled"),s.find("select.ui-datepicker-month, select.ui-datepicker-year").prop("disabled",!1)),this._disabledInputs=t.map(this._disabledInputs,function(t){return t===e?null:t}))},_disableDatepicker:function(e){var i,s,n=t(e),o=t.data(e,"datepicker");n.hasClass(this.markerClassName)&&(i=e.nodeName.toLowerCase(),"input"===i?(e.disabled=!0,o.trigger.filter("button").each(function(){this.disabled=!0}).end().filter("img").css({opacity:"0.5",cursor:"default"})):("div"===i||"span"===i)&&(s=n.children("."+this._inlineClass),s.children().addClass("ui-state-disabled"),s.find("select.ui-datepicker-month, select.ui-datepicker-year").prop("disabled",!0)),this._disabledInputs=t.map(this._disabledInputs,function(t){return t===e?null:t}),this._disabledInputs[this._disabledInputs.length]=e)},_isDisabledDatepicker:function(t){if(!t)return!1;for(var e=0;this._disabledInputs.length>e;e++)if(this._disabledInputs[e]===t)return!0;return!1},_getInst:function(e){try{return t.data(e,"datepicker")}catch(i){throw"Missing instance data for this datepicker"}},_optionDatepicker:function(e,i,s){var n,o,r,h,l=this._getInst(e);return 2===arguments.length&&"string"==typeof i?"defaults"===i?t.extend({},t.datepicker._defaults):l?"all"===i?t.extend({},l.settings):this._get(l,i):null:(n=i||{},"string"==typeof i&&(n={},n[i]=s),l&&(this._curInst===l&&this._hideDatepicker(),o=this._getDateDatepicker(e,!0),r=this._getMinMaxDate(l,"min"),h=this._getMinMaxDate(l,"max"),a(l.settings,n),null!==r&&void 0!==n.dateFormat&&void 0===n.minDate&&(l.settings.minDate=this._formatDate(l,r)),null!==h&&void 0!==n.dateFormat&&void 0===n.maxDate&&(l.settings.maxDate=this._formatDate(l,h)),"disabled"in n&&(n.disabled?this._disableDatepicker(e):this._enableDatepicker(e)),this._attachments(t(e),l),this._autoSize(l),this._setDate(l,o),this._updateAlternate(l),this._updateDatepicker(l)),void 0)},_changeDatepicker:function(t,e,i){this._optionDatepicker(t,e,i)},_refreshDatepicker:function(t){var e=this._getInst(t);e&&this._updateDatepicker(e)},_setDateDatepicker:function(t,e){var i=this._getInst(t);i&&(this._setDate(i,e),this._updateDatepicker(i),this._updateAlternate(i))},_getDateDatepicker:function(t,e){var i=this._getInst(t);return i&&!i.inline&&this._setDateFromField(i,e),i?this._getDate(i):null},_doKeyDown:function(e){var i,s,n,o=t.datepicker._getInst(e.target),a=!0,r=o.dpDiv.is(".ui-datepicker-rtl");if(o._keyEvent=!0,t.datepicker._datepickerShowing)switch(e.keyCode){case 9:t.datepicker._hideDatepicker(),a=!1;break;case 13:return n=t("td."+t.datepicker._dayOverClass+":not(."+t.datepicker._currentClass+")",o.dpDiv),n[0]&&t.datepicker._selectDay(e.target,o.selectedMonth,o.selectedYear,n[0]),i=t.datepicker._get(o,"onSelect"),i?(s=t.datepicker._formatDate(o),i.apply(o.input?o.input[0]:null,[s,o])):t.datepicker._hideDatepicker(),!1;case 27:t.datepicker._hideDatepicker();break;case 33:t.datepicker._adjustDate(e.target,e.ctrlKey?-t.datepicker._get(o,"stepBigMonths"):-t.datepicker._get(o,"stepMonths"),"M");break;case 34:t.datepicker._adjustDate(e.target,e.ctrlKey?+t.datepicker._get(o,"stepBigMonths"):+t.datepicker._get(o,"stepMonths"),"M");break;case 35:(e.ctrlKey||e.metaKey)&&t.datepicker._clearDate(e.target),a=e.ctrlKey||e.metaKey;break;case 36:(e.ctrlKey||e.metaKey)&&t.datepicker._gotoToday(e.target),a=e.ctrlKey||e.metaKey;break;case 37:(e.ctrlKey||e.metaKey)&&t.datepicker._adjustDate(e.target,r?1:-1,"D"),a=e.ctrlKey||e.metaKey,e.originalEvent.altKey&&t.datepicker._adjustDate(e.target,e.ctrlKey?-t.datepicker._get(o,"stepBigMonths"):-t.datepicker._get(o,"stepMonths"),"M");break;case 38:(e.ctrlKey||e.metaKey)&&t.datepicker._adjustDate(e.target,-7,"D"),a=e.ctrlKey||e.metaKey;break;case 39:(e.ctrlKey||e.metaKey)&&t.datepicker._adjustDate(e.target,r?-1:1,"D"),a=e.ctrlKey||e.metaKey,e.originalEvent.altKey&&t.datepicker._adjustDate(e.target,e.ctrlKey?+t.datepicker._get(o,"stepBigMonths"):+t.datepicker._get(o,"stepMonths"),"M");break;case 40:(e.ctrlKey||e.metaKey)&&t.datepicker._adjustDate(e.target,7,"D"),a=e.ctrlKey||e.metaKey;break;default:a=!1}else 36===e.keyCode&&e.ctrlKey?t.datepicker._showDatepicker(this):a=!1;a&&(e.preventDefault(),e.stopPropagation())},_doKeyPress:function(e){var i,s,n=t.datepicker._getInst(e.target);return t.datepicker._get(n,"constrainInput")?(i=t.datepicker._possibleChars(t.datepicker._get(n,"dateFormat")),s=String.fromCharCode(null==e.charCode?e.keyCode:e.charCode),e.ctrlKey||e.metaKey||" ">s||!i||i.indexOf(s)>-1):void 0},_doKeyUp:function(e){var i,s=t.datepicker._getInst(e.target);if(s.input.val()!==s.lastVal)try{i=t.datepicker.parseDate(t.datepicker._get(s,"dateFormat"),s.input?s.input.val():null,t.datepicker._getFormatConfig(s)),i&&(t.datepicker._setDateFromField(s),t.datepicker._updateAlternate(s),t.datepicker._updateDatepicker(s))}catch(n){}return!0},_showDatepicker:function(e){if(e=e.target||e,"input"!==e.nodeName.toLowerCase()&&(e=t("input",e.parentNode)[0]),!t.datepicker._isDisabledDatepicker(e)&&t.datepicker._lastInput!==e){var s,n,o,r,h,l,c;s=t.datepicker._getInst(e),t.datepicker._curInst&&t.datepicker._curInst!==s&&(t.datepicker._curInst.dpDiv.stop(!0,!0),s&&t.datepicker._datepickerShowing&&t.datepicker._hideDatepicker(t.datepicker._curInst.input[0])),n=t.datepicker._get(s,"beforeShow"),o=n?n.apply(e,[e,s]):{},o!==!1&&(a(s.settings,o),s.lastVal=null,t.datepicker._lastInput=e,t.datepicker._setDateFromField(s),t.datepicker._inDialog&&(e.value=""),t.datepicker._pos||(t.datepicker._pos=t.datepicker._findPos(e),t.datepicker._pos[1]+=e.offsetHeight),r=!1,t(e).parents().each(function(){return r|="fixed"===t(this).css("position"),!r}),h={left:t.datepicker._pos[0],top:t.datepicker._pos[1]},t.datepicker._pos=null,s.dpDiv.empty(),s.dpDiv.css({position:"absolute",display:"block",top:"-1000px"}),t.datepicker._updateDatepicker(s),h=t.datepicker._checkOffset(s,h,r),s.dpDiv.css({position:t.datepicker._inDialog&&t.blockUI?"static":r?"fixed":"absolute",display:"none",left:h.left+"px",top:h.top+"px"}),s.inline||(l=t.datepicker._get(s,"showAnim"),c=t.datepicker._get(s,"duration"),s.dpDiv.css("z-index",i(t(e))+1),t.datepicker._datepickerShowing=!0,t.effects&&t.effects.effect[l]?s.dpDiv.show(l,t.datepicker._get(s,"showOptions"),c):s.dpDiv[l||"show"](l?c:null),t.datepicker._shouldFocusInput(s)&&s.input.trigger("focus"),t.datepicker._curInst=s))
1229}},_updateDatepicker:function(e){this.maxRows=4,m=e,e.dpDiv.empty().append(this._generateHTML(e)),this._attachHandlers(e);var i,s=this._getNumberOfMonths(e),n=s[1],a=17,r=e.dpDiv.find("."+this._dayOverClass+" a");r.length>0&&o.apply(r.get(0)),e.dpDiv.removeClass("ui-datepicker-multi-2 ui-datepicker-multi-3 ui-datepicker-multi-4").width(""),n>1&&e.dpDiv.addClass("ui-datepicker-multi-"+n).css("width",a*n+"em"),e.dpDiv[(1!==s[0]||1!==s[1]?"add":"remove")+"Class"]("ui-datepicker-multi"),e.dpDiv[(this._get(e,"isRTL")?"add":"remove")+"Class"]("ui-datepicker-rtl"),e===t.datepicker._curInst&&t.datepicker._datepickerShowing&&t.datepicker._shouldFocusInput(e)&&e.input.trigger("focus"),e.yearshtml&&(i=e.yearshtml,setTimeout(function(){i===e.yearshtml&&e.yearshtml&&e.dpDiv.find("select.ui-datepicker-year:first").replaceWith(e.yearshtml),i=e.yearshtml=null},0))},_shouldFocusInput:function(t){return t.input&&t.input.is(":visible")&&!t.input.is(":disabled")&&!t.input.is(":focus")},_checkOffset:function(e,i,s){var n=e.dpDiv.outerWidth(),o=e.dpDiv.outerHeight(),a=e.input?e.input.outerWidth():0,r=e.input?e.input.outerHeight():0,h=document.documentElement.clientWidth+(s?0:t(document).scrollLeft()),l=document.documentElement.clientHeight+(s?0:t(document).scrollTop());return i.left-=this._get(e,"isRTL")?n-a:0,i.left-=s&&i.left===e.input.offset().left?t(document).scrollLeft():0,i.top-=s&&i.top===e.input.offset().top+r?t(document).scrollTop():0,i.left-=Math.min(i.left,i.left+n>h&&h>n?Math.abs(i.left+n-h):0),i.top-=Math.min(i.top,i.top+o>l&&l>o?Math.abs(o+r):0),i},_findPos:function(e){for(var i,s=this._getInst(e),n=this._get(s,"isRTL");e&&("hidden"===e.type||1!==e.nodeType||t.expr.filters.hidden(e));)e=e[n?"previousSibling":"nextSibling"];return i=t(e).offset(),[i.left,i.top]},_hideDatepicker:function(e){var i,s,n,o,a=this._curInst;!a||e&&a!==t.data(e,"datepicker")||this._datepickerShowing&&(i=this._get(a,"showAnim"),s=this._get(a,"duration"),n=function(){t.datepicker._tidyDialog(a)},t.effects&&(t.effects.effect[i]||t.effects[i])?a.dpDiv.hide(i,t.datepicker._get(a,"showOptions"),s,n):a.dpDiv["slideDown"===i?"slideUp":"fadeIn"===i?"fadeOut":"hide"](i?s:null,n),i||n(),this._datepickerShowing=!1,o=this._get(a,"onClose"),o&&o.apply(a.input?a.input[0]:null,[a.input?a.input.val():"",a]),this._lastInput=null,this._inDialog&&(this._dialogInput.css({position:"absolute",left:"0",top:"-100px"}),t.blockUI&&(t.unblockUI(),t("body").append(this.dpDiv))),this._inDialog=!1)},_tidyDialog:function(t){t.dpDiv.removeClass(this._dialogClass).off(".ui-datepicker-calendar")},_checkExternalClick:function(e){if(t.datepicker._curInst){var i=t(e.target),s=t.datepicker._getInst(i[0]);(i[0].id!==t.datepicker._mainDivId&&0===i.parents("#"+t.datepicker._mainDivId).length&&!i.hasClass(t.datepicker.markerClassName)&&!i.closest("."+t.datepicker._triggerClass).length&&t.datepicker._datepickerShowing&&(!t.datepicker._inDialog||!t.blockUI)||i.hasClass(t.datepicker.markerClassName)&&t.datepicker._curInst!==s)&&t.datepicker._hideDatepicker()}},_adjustDate:function(e,i,s){var n=t(e),o=this._getInst(n[0]);this._isDisabledDatepicker(n[0])||(this._adjustInstDate(o,i+("M"===s?this._get(o,"showCurrentAtPos"):0),s),this._updateDatepicker(o))},_gotoToday:function(e){var i,s=t(e),n=this._getInst(s[0]);this._get(n,"gotoCurrent")&&n.currentDay?(n.selectedDay=n.currentDay,n.drawMonth=n.selectedMonth=n.currentMonth,n.drawYear=n.selectedYear=n.currentYear):(i=new Date,n.selectedDay=i.getDate(),n.drawMonth=n.selectedMonth=i.getMonth(),n.drawYear=n.selectedYear=i.getFullYear()),this._notifyChange(n),this._adjustDate(s)},_selectMonthYear:function(e,i,s){var n=t(e),o=this._getInst(n[0]);o["selected"+("M"===s?"Month":"Year")]=o["draw"+("M"===s?"Month":"Year")]=parseInt(i.options[i.selectedIndex].value,10),this._notifyChange(o),this._adjustDate(n)},_selectDay:function(e,i,s,n){var o,a=t(e);t(n).hasClass(this._unselectableClass)||this._isDisabledDatepicker(a[0])||(o=this._getInst(a[0]),o.selectedDay=o.currentDay=t("a",n).html(),o.selectedMonth=o.currentMonth=i,o.selectedYear=o.currentYear=s,this._selectDate(e,this._formatDate(o,o.currentDay,o.currentMonth,o.currentYear)))},_clearDate:function(e){var i=t(e);this._selectDate(i,"")},_selectDate:function(e,i){var s,n=t(e),o=this._getInst(n[0]);i=null!=i?i:this._formatDate(o),o.input&&o.input.val(i),this._updateAlternate(o),s=this._get(o,"onSelect"),s?s.apply(o.input?o.input[0]:null,[i,o]):o.input&&o.input.trigger("change"),o.inline?this._updateDatepicker(o):(this._hideDatepicker(),this._lastInput=o.input[0],"object"!=typeof o.input[0]&&o.input.trigger("focus"),this._lastInput=null)},_updateAlternate:function(e){var i,s,n,o=this._get(e,"altField");o&&(i=this._get(e,"altFormat")||this._get(e,"dateFormat"),s=this._getDate(e),n=this.formatDate(i,s,this._getFormatConfig(e)),t(o).val(n))},noWeekends:function(t){var e=t.getDay();return[e>0&&6>e,""]},iso8601Week:function(t){var e,i=new Date(t.getTime());return i.setDate(i.getDate()+4-(i.getDay()||7)),e=i.getTime(),i.setMonth(0),i.setDate(1),Math.floor(Math.round((e-i)/864e5)/7)+1},parseDate:function(e,i,s){if(null==e||null==i)throw"Invalid arguments";if(i="object"==typeof i?""+i:i+"",""===i)return null;var n,o,a,r,h=0,l=(s?s.shortYearCutoff:null)||this._defaults.shortYearCutoff,c="string"!=typeof l?l:(new Date).getFullYear()%100+parseInt(l,10),u=(s?s.dayNamesShort:null)||this._defaults.dayNamesShort,d=(s?s.dayNames:null)||this._defaults.dayNames,p=(s?s.monthNamesShort:null)||this._defaults.monthNamesShort,f=(s?s.monthNames:null)||this._defaults.monthNames,g=-1,m=-1,_=-1,v=-1,b=!1,y=function(t){var i=e.length>n+1&&e.charAt(n+1)===t;return i&&n++,i},w=function(t){var e=y(t),s="@"===t?14:"!"===t?20:"y"===t&&e?4:"o"===t?3:2,n="y"===t?s:1,o=RegExp("^\\d{"+n+","+s+"}"),a=i.substring(h).match(o);if(!a)throw"Missing number at position "+h;return h+=a[0].length,parseInt(a[0],10)},k=function(e,s,n){var o=-1,a=t.map(y(e)?n:s,function(t,e){return[[e,t]]}).sort(function(t,e){return-(t[1].length-e[1].length)});if(t.each(a,function(t,e){var s=e[1];return i.substr(h,s.length).toLowerCase()===s.toLowerCase()?(o=e[0],h+=s.length,!1):void 0}),-1!==o)return o+1;throw"Unknown name at position "+h},x=function(){if(i.charAt(h)!==e.charAt(n))throw"Unexpected literal at position "+h;h++};for(n=0;e.length>n;n++)if(b)"'"!==e.charAt(n)||y("'")?x():b=!1;else switch(e.charAt(n)){case"d":_=w("d");break;case"D":k("D",u,d);break;case"o":v=w("o");break;case"m":m=w("m");break;case"M":m=k("M",p,f);break;case"y":g=w("y");break;case"@":r=new Date(w("@")),g=r.getFullYear(),m=r.getMonth()+1,_=r.getDate();break;case"!":r=new Date((w("!")-this._ticksTo1970)/1e4),g=r.getFullYear(),m=r.getMonth()+1,_=r.getDate();break;case"'":y("'")?x():b=!0;break;default:x()}if(i.length>h&&(a=i.substr(h),!/^\s+/.test(a)))throw"Extra/unparsed characters found in date: "+a;if(-1===g?g=(new Date).getFullYear():100>g&&(g+=(new Date).getFullYear()-(new Date).getFullYear()%100+(c>=g?0:-100)),v>-1)for(m=1,_=v;;){if(o=this._getDaysInMonth(g,m-1),o>=_)break;m++,_-=o}if(r=this._daylightSavingAdjust(new Date(g,m-1,_)),r.getFullYear()!==g||r.getMonth()+1!==m||r.getDate()!==_)throw"Invalid date";return r},ATOM:"yy-mm-dd",COOKIE:"D, dd M yy",ISO_8601:"yy-mm-dd",RFC_822:"D, d M y",RFC_850:"DD, dd-M-y",RFC_1036:"D, d M y",RFC_1123:"D, d M yy",RFC_2822:"D, d M yy",RSS:"D, d M y",TICKS:"!",TIMESTAMP:"@",W3C:"yy-mm-dd",_ticksTo1970:1e7*60*60*24*(718685+Math.floor(492.5)-Math.floor(19.7)+Math.floor(4.925)),formatDate:function(t,e,i){if(!e)return"";var s,n=(i?i.dayNamesShort:null)||this._defaults.dayNamesShort,o=(i?i.dayNames:null)||this._defaults.dayNames,a=(i?i.monthNamesShort:null)||this._defaults.monthNamesShort,r=(i?i.monthNames:null)||this._defaults.monthNames,h=function(e){var i=t.length>s+1&&t.charAt(s+1)===e;return i&&s++,i},l=function(t,e,i){var s=""+e;if(h(t))for(;i>s.length;)s="0"+s;return s},c=function(t,e,i,s){return h(t)?s[e]:i[e]},u="",d=!1;if(e)for(s=0;t.length>s;s++)if(d)"'"!==t.charAt(s)||h("'")?u+=t.charAt(s):d=!1;else switch(t.charAt(s)){case"d":u+=l("d",e.getDate(),2);break;case"D":u+=c("D",e.getDay(),n,o);break;case"o":u+=l("o",Math.round((new Date(e.getFullYear(),e.getMonth(),e.getDate()).getTime()-new Date(e.getFullYear(),0,0).getTime())/864e5),3);break;case"m":u+=l("m",e.getMonth()+1,2);break;case"M":u+=c("M",e.getMonth(),a,r);break;case"y":u+=h("y")?e.getFullYear():(10>e.getFullYear()%100?"0":"")+e.getFullYear()%100;break;case"@":u+=e.getTime();break;case"!":u+=1e4*e.getTime()+this._ticksTo1970;break;case"'":h("'")?u+="'":d=!0;break;default:u+=t.charAt(s)}return u},_possibleChars:function(t){var e,i="",s=!1,n=function(i){var s=t.length>e+1&&t.charAt(e+1)===i;return s&&e++,s};for(e=0;t.length>e;e++)if(s)"'"!==t.charAt(e)||n("'")?i+=t.charAt(e):s=!1;else switch(t.charAt(e)){case"d":case"m":case"y":case"@":i+="0123456789";break;case"D":case"M":return null;case"'":n("'")?i+="'":s=!0;break;default:i+=t.charAt(e)}return i},_get:function(t,e){return void 0!==t.settings[e]?t.settings[e]:this._defaults[e]},_setDateFromField:function(t,e){if(t.input.val()!==t.lastVal){var i=this._get(t,"dateFormat"),s=t.lastVal=t.input?t.input.val():null,n=this._getDefaultDate(t),o=n,a=this._getFormatConfig(t);try{o=this.parseDate(i,s,a)||n}catch(r){s=e?"":s}t.selectedDay=o.getDate(),t.drawMonth=t.selectedMonth=o.getMonth(),t.drawYear=t.selectedYear=o.getFullYear(),t.currentDay=s?o.getDate():0,t.currentMonth=s?o.getMonth():0,t.currentYear=s?o.getFullYear():0,this._adjustInstDate(t)}},_getDefaultDate:function(t){return this._restrictMinMax(t,this._determineDate(t,this._get(t,"defaultDate"),new Date))},_determineDate:function(e,i,s){var n=function(t){var e=new Date;return e.setDate(e.getDate()+t),e},o=function(i){try{return t.datepicker.parseDate(t.datepicker._get(e,"dateFormat"),i,t.datepicker._getFormatConfig(e))}catch(s){}for(var n=(i.toLowerCase().match(/^c/)?t.datepicker._getDate(e):null)||new Date,o=n.getFullYear(),a=n.getMonth(),r=n.getDate(),h=/([+\-]?[0-9]+)\s*(d|D|w|W|m|M|y|Y)?/g,l=h.exec(i);l;){switch(l[2]||"d"){case"d":case"D":r+=parseInt(l[1],10);break;case"w":case"W":r+=7*parseInt(l[1],10);break;case"m":case"M":a+=parseInt(l[1],10),r=Math.min(r,t.datepicker._getDaysInMonth(o,a));break;case"y":case"Y":o+=parseInt(l[1],10),r=Math.min(r,t.datepicker._getDaysInMonth(o,a))}l=h.exec(i)}return new Date(o,a,r)},a=null==i||""===i?s:"string"==typeof i?o(i):"number"==typeof i?isNaN(i)?s:n(i):new Date(i.getTime());return a=a&&"Invalid Date"==""+a?s:a,a&&(a.setHours(0),a.setMinutes(0),a.setSeconds(0),a.setMilliseconds(0)),this._daylightSavingAdjust(a)},_daylightSavingAdjust:function(t){return t?(t.setHours(t.getHours()>12?t.getHours()+2:0),t):null},_setDate:function(t,e,i){var s=!e,n=t.selectedMonth,o=t.selectedYear,a=this._restrictMinMax(t,this._determineDate(t,e,new Date));t.selectedDay=t.currentDay=a.getDate(),t.drawMonth=t.selectedMonth=t.currentMonth=a.getMonth(),t.drawYear=t.selectedYear=t.currentYear=a.getFullYear(),n===t.selectedMonth&&o===t.selectedYear||i||this._notifyChange(t),this._adjustInstDate(t),t.input&&t.input.val(s?"":this._formatDate(t))},_getDate:function(t){var e=!t.currentYear||t.input&&""===t.input.val()?null:this._daylightSavingAdjust(new Date(t.currentYear,t.currentMonth,t.currentDay));return e},_attachHandlers:function(e){var i=this._get(e,"stepMonths"),s="#"+e.id.replace(/\\\\/g,"\\");e.dpDiv.find("[data-handler]").map(function(){var e={prev:function(){t.datepicker._adjustDate(s,-i,"M")},next:function(){t.datepicker._adjustDate(s,+i,"M")},hide:function(){t.datepicker._hideDatepicker()},today:function(){t.datepicker._gotoToday(s)},selectDay:function(){return t.datepicker._selectDay(s,+this.getAttribute("data-month"),+this.getAttribute("data-year"),this),!1},selectMonth:function(){return t.datepicker._selectMonthYear(s,this,"M"),!1},selectYear:function(){return t.datepicker._selectMonthYear(s,this,"Y"),!1}};t(this).on(this.getAttribute("data-event"),e[this.getAttribute("data-handler")])})},_generateHTML:function(t){var e,i,s,n,o,a,r,h,l,c,u,d,p,f,g,m,_,v,b,y,w,k,x,C,D,I,T,P,M,S,H,z,O,A,N,W,E,F,L,R=new Date,B=this._daylightSavingAdjust(new Date(R.getFullYear(),R.getMonth(),R.getDate())),Y=this._get(t,"isRTL"),j=this._get(t,"showButtonPanel"),q=this._get(t,"hideIfNoPrevNext"),K=this._get(t,"navigationAsDateFormat"),U=this._getNumberOfMonths(t),V=this._get(t,"showCurrentAtPos"),$=this._get(t,"stepMonths"),X=1!==U[0]||1!==U[1],G=this._daylightSavingAdjust(t.currentDay?new Date(t.currentYear,t.currentMonth,t.currentDay):new Date(9999,9,9)),Q=this._getMinMaxDate(t,"min"),J=this._getMinMaxDate(t,"max"),Z=t.drawMonth-V,te=t.drawYear;if(0>Z&&(Z+=12,te--),J)for(e=this._daylightSavingAdjust(new Date(J.getFullYear(),J.getMonth()-U[0]*U[1]+1,J.getDate())),e=Q&&Q>e?Q:e;this._daylightSavingAdjust(new Date(te,Z,1))>e;)Z--,0>Z&&(Z=11,te--);for(t.drawMonth=Z,t.drawYear=te,i=this._get(t,"prevText"),i=K?this.formatDate(i,this._daylightSavingAdjust(new Date(te,Z-$,1)),this._getFormatConfig(t)):i,s=this._canAdjustMonth(t,-1,te,Z)?"<a class='ui-datepicker-prev ui-corner-all' data-handler='prev' data-event='click' title='"+i+"'><span class='ui-icon ui-icon-circle-triangle-"+(Y?"e":"w")+"'>"+i+"</span></a>":q?"":"<a class='ui-datepicker-prev ui-corner-all ui-state-disabled' title='"+i+"'><span class='ui-icon ui-icon-circle-triangle-"+(Y?"e":"w")+"'>"+i+"</span></a>",n=this._get(t,"nextText"),n=K?this.formatDate(n,this._daylightSavingAdjust(new Date(te,Z+$,1)),this._getFormatConfig(t)):n,o=this._canAdjustMonth(t,1,te,Z)?"<a class='ui-datepicker-next ui-corner-all' data-handler='next' data-event='click' title='"+n+"'><span class='ui-icon ui-icon-circle-triangle-"+(Y?"w":"e")+"'>"+n+"</span></a>":q?"":"<a class='ui-datepicker-next ui-corner-all ui-state-disabled' title='"+n+"'><span class='ui-icon ui-icon-circle-triangle-"+(Y?"w":"e")+"'>"+n+"</span></a>",a=this._get(t,"currentText"),r=this._get(t,"gotoCurrent")&&t.currentDay?G:B,a=K?this.formatDate(a,r,this._getFormatConfig(t)):a,h=t.inline?"":"<button type='button' class='ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all' data-handler='hide' data-event='click'>"+this._get(t,"closeText")+"</button>",l=j?"<div class='ui-datepicker-buttonpane ui-widget-content'>"+(Y?h:"")+(this._isInRange(t,r)?"<button type='button' class='ui-datepicker-current ui-state-default ui-priority-secondary ui-corner-all' data-handler='today' data-event='click'>"+a+"</button>":"")+(Y?"":h)+"</div>":"",c=parseInt(this._get(t,"firstDay"),10),c=isNaN(c)?0:c,u=this._get(t,"showWeek"),d=this._get(t,"dayNames"),p=this._get(t,"dayNamesMin"),f=this._get(t,"monthNames"),g=this._get(t,"monthNamesShort"),m=this._get(t,"beforeShowDay"),_=this._get(t,"showOtherMonths"),v=this._get(t,"selectOtherMonths"),b=this._getDefaultDate(t),y="",k=0;U[0]>k;k++){for(x="",this.maxRows=4,C=0;U[1]>C;C++){if(D=this._daylightSavingAdjust(new Date(te,Z,t.selectedDay)),I=" ui-corner-all",T="",X){if(T+="<div class='ui-datepicker-group",U[1]>1)switch(C){case 0:T+=" ui-datepicker-group-first",I=" ui-corner-"+(Y?"right":"left");break;case U[1]-1:T+=" ui-datepicker-group-last",I=" ui-corner-"+(Y?"left":"right");break;default:T+=" ui-datepicker-group-middle",I=""}T+="'>"}for(T+="<div class='ui-datepicker-header ui-widget-header ui-helper-clearfix"+I+"'>"+(/all|left/.test(I)&&0===k?Y?o:s:"")+(/all|right/.test(I)&&0===k?Y?s:o:"")+this._generateMonthYearHeader(t,Z,te,Q,J,k>0||C>0,f,g)+"</div><table class='ui-datepicker-calendar'><thead>"+"<tr>",P=u?"<th class='ui-datepicker-week-col'>"+this._get(t,"weekHeader")+"</th>":"",w=0;7>w;w++)M=(w+c)%7,P+="<th scope='col'"+((w+c+6)%7>=5?" class='ui-datepicker-week-end'":"")+">"+"<span title='"+d[M]+"'>"+p[M]+"</span></th>";for(T+=P+"</tr></thead><tbody>",S=this._getDaysInMonth(te,Z),te===t.selectedYear&&Z===t.selectedMonth&&(t.selectedDay=Math.min(t.selectedDay,S)),H=(this._getFirstDayOfMonth(te,Z)-c+7)%7,z=Math.ceil((H+S)/7),O=X?this.maxRows>z?this.maxRows:z:z,this.maxRows=O,A=this._daylightSavingAdjust(new Date(te,Z,1-H)),N=0;O>N;N++){for(T+="<tr>",W=u?"<td class='ui-datepicker-week-col'>"+this._get(t,"calculateWeek")(A)+"</td>":"",w=0;7>w;w++)E=m?m.apply(t.input?t.input[0]:null,[A]):[!0,""],F=A.getMonth()!==Z,L=F&&!v||!E[0]||Q&&Q>A||J&&A>J,W+="<td class='"+((w+c+6)%7>=5?" ui-datepicker-week-end":"")+(F?" ui-datepicker-other-month":"")+(A.getTime()===D.getTime()&&Z===t.selectedMonth&&t._keyEvent||b.getTime()===A.getTime()&&b.getTime()===D.getTime()?" "+this._dayOverClass:"")+(L?" "+this._unselectableClass+" ui-state-disabled":"")+(F&&!_?"":" "+E[1]+(A.getTime()===G.getTime()?" "+this._currentClass:"")+(A.getTime()===B.getTime()?" ui-datepicker-today":""))+"'"+(F&&!_||!E[2]?"":" title='"+E[2].replace(/'/g,"&#39;")+"'")+(L?"":" data-handler='selectDay' data-event='click' data-month='"+A.getMonth()+"' data-year='"+A.getFullYear()+"'")+">"+(F&&!_?"&#xa0;":L?"<span class='ui-state-default'>"+A.getDate()+"</span>":"<a class='ui-state-default"+(A.getTime()===B.getTime()?" ui-state-highlight":"")+(A.getTime()===G.getTime()?" ui-state-active":"")+(F?" ui-priority-secondary":"")+"' href='#'>"+A.getDate()+"</a>")+"</td>",A.setDate(A.getDate()+1),A=this._daylightSavingAdjust(A);T+=W+"</tr>"}Z++,Z>11&&(Z=0,te++),T+="</tbody></table>"+(X?"</div>"+(U[0]>0&&C===U[1]-1?"<div class='ui-datepicker-row-break'></div>":""):""),x+=T}y+=x}return y+=l,t._keyEvent=!1,y},_generateMonthYearHeader:function(t,e,i,s,n,o,a,r){var h,l,c,u,d,p,f,g,m=this._get(t,"changeMonth"),_=this._get(t,"changeYear"),v=this._get(t,"showMonthAfterYear"),b="<div class='ui-datepicker-title'>",y="";if(o||!m)y+="<span class='ui-datepicker-month'>"+a[e]+"</span>";else{for(h=s&&s.getFullYear()===i,l=n&&n.getFullYear()===i,y+="<select class='ui-datepicker-month' data-handler='selectMonth' data-event='change'>",c=0;12>c;c++)(!h||c>=s.getMonth())&&(!l||n.getMonth()>=c)&&(y+="<option value='"+c+"'"+(c===e?" selected='selected'":"")+">"+r[c]+"</option>");y+="</select>"}if(v||(b+=y+(!o&&m&&_?"":"&#xa0;")),!t.yearshtml)if(t.yearshtml="",o||!_)b+="<span class='ui-datepicker-year'>"+i+"</span>";else{for(u=this._get(t,"yearRange").split(":"),d=(new Date).getFullYear(),p=function(t){var e=t.match(/c[+\-].*/)?i+parseInt(t.substring(1),10):t.match(/[+\-].*/)?d+parseInt(t,10):parseInt(t,10);return isNaN(e)?d:e},f=p(u[0]),g=Math.max(f,p(u[1]||"")),f=s?Math.max(f,s.getFullYear()):f,g=n?Math.min(g,n.getFullYear()):g,t.yearshtml+="<select class='ui-datepicker-year' data-handler='selectYear' data-event='change'>";g>=f;f++)t.yearshtml+="<option value='"+f+"'"+(f===i?" selected='selected'":"")+">"+f+"</option>";t.yearshtml+="</select>",b+=t.yearshtml,t.yearshtml=null}return b+=this._get(t,"yearSuffix"),v&&(b+=(!o&&m&&_?"":"&#xa0;")+y),b+="</div>"},_adjustInstDate:function(t,e,i){var s=t.selectedYear+("Y"===i?e:0),n=t.selectedMonth+("M"===i?e:0),o=Math.min(t.selectedDay,this._getDaysInMonth(s,n))+("D"===i?e:0),a=this._restrictMinMax(t,this._daylightSavingAdjust(new Date(s,n,o)));t.selectedDay=a.getDate(),t.drawMonth=t.selectedMonth=a.getMonth(),t.drawYear=t.selectedYear=a.getFullYear(),("M"===i||"Y"===i)&&this._notifyChange(t)},_restrictMinMax:function(t,e){var i=this._getMinMaxDate(t,"min"),s=this._getMinMaxDate(t,"max"),n=i&&i>e?i:e;return s&&n>s?s:n},_notifyChange:function(t){var e=this._get(t,"onChangeMonthYear");e&&e.apply(t.input?t.input[0]:null,[t.selectedYear,t.selectedMonth+1,t])},_getNumberOfMonths:function(t){var e=this._get(t,"numberOfMonths");return null==e?[1,1]:"number"==typeof e?[1,e]:e},_getMinMaxDate:function(t,e){return this._determineDate(t,this._get(t,e+"Date"),null)},_getDaysInMonth:function(t,e){return 32-this._daylightSavingAdjust(new Date(t,e,32)).getDate()},_getFirstDayOfMonth:function(t,e){return new Date(t,e,1).getDay()},_canAdjustMonth:function(t,e,i,s){var n=this._getNumberOfMonths(t),o=this._daylightSavingAdjust(new Date(i,s+(0>e?e:n[0]*n[1]),1));return 0>e&&o.setDate(this._getDaysInMonth(o.getFullYear(),o.getMonth())),this._isInRange(t,o)},_isInRange:function(t,e){var i,s,n=this._getMinMaxDate(t,"min"),o=this._getMinMaxDate(t,"max"),a=null,r=null,h=this._get(t,"yearRange");return h&&(i=h.split(":"),s=(new Date).getFullYear(),a=parseInt(i[0],10),r=parseInt(i[1],10),i[0].match(/[+\-].*/)&&(a+=s),i[1].match(/[+\-].*/)&&(r+=s)),(!n||e.getTime()>=n.getTime())&&(!o||e.getTime()<=o.getTime())&&(!a||e.getFullYear()>=a)&&(!r||r>=e.getFullYear())},_getFormatConfig:function(t){var e=this._get(t,"shortYearCutoff");return e="string"!=typeof e?e:(new Date).getFullYear()%100+parseInt(e,10),{shortYearCutoff:e,dayNamesShort:this._get(t,"dayNamesShort"),dayNames:this._get(t,"dayNames"),monthNamesShort:this._get(t,"monthNamesShort"),monthNames:this._get(t,"monthNames")}},_formatDate:function(t,e,i,s){e||(t.currentDay=t.selectedDay,t.currentMonth=t.selectedMonth,t.currentYear=t.selectedYear);var n=e?"object"==typeof e?e:this._daylightSavingAdjust(new Date(s,i,e)):this._daylightSavingAdjust(new Date(t.currentYear,t.currentMonth,t.currentDay));return this.formatDate(this._get(t,"dateFormat"),n,this._getFormatConfig(t))}}),t.fn.datepicker=function(e){if(!this.length)return this;t.datepicker.initialized||(t(document).on("mousedown",t.datepicker._checkExternalClick),t.datepicker.initialized=!0),0===t("#"+t.datepicker._mainDivId).length&&t("body").append(t.datepicker.dpDiv);var i=Array.prototype.slice.call(arguments,1);return"string"!=typeof e||"isDisabled"!==e&&"getDate"!==e&&"widget"!==e?"option"===e&&2===arguments.length&&"string"==typeof arguments[1]?t.datepicker["_"+e+"Datepicker"].apply(t.datepicker,[this[0]].concat(i)):this.each(function(){"string"==typeof e?t.datepicker["_"+e+"Datepicker"].apply(t.datepicker,[this].concat(i)):t.datepicker._attachDatepicker(this,e)}):t.datepicker["_"+e+"Datepicker"].apply(t.datepicker,[this[0]].concat(i))},t.datepicker=new s,t.datepicker.initialized=!1,t.datepicker.uuid=(new Date).getTime(),t.datepicker.version="1.12.1",t.datepicker,t.ui.ie=!!/msie [\w.]+/.exec(navigator.userAgent.toLowerCase());var _=!1;t(document).on("mouseup",function(){_=!1}),t.widget("ui.mouse",{version:"1.12.1",options:{cancel:"input, textarea, button, select, option",distance:1,delay:0},_mouseInit:function(){var e=this;this.element.on("mousedown."+this.widgetName,function(t){return e._mouseDown(t)}).on("click."+this.widgetName,function(i){return!0===t.data(i.target,e.widgetName+".preventClickEvent")?(t.removeData(i.target,e.widgetName+".preventClickEvent"),i.stopImmediatePropagation(),!1):void 0}),this.started=!1},_mouseDestroy:function(){this.element.off("."+this.widgetName),this._mouseMoveDelegate&&this.document.off("mousemove."+this.widgetName,this._mouseMoveDelegate).off("mouseup."+this.widgetName,this._mouseUpDelegate)},_mouseDown:function(e){if(!_){this._mouseMoved=!1,this._mouseStarted&&this._mouseUp(e),this._mouseDownEvent=e;var i=this,s=1===e.which,n="string"==typeof this.options.cancel&&e.target.nodeName?t(e.target).closest(this.options.cancel).length:!1;return s&&!n&&this._mouseCapture(e)?(this.mouseDelayMet=!this.options.delay,this.mouseDelayMet||(this._mouseDelayTimer=setTimeout(function(){i.mouseDelayMet=!0},this.options.delay)),this._mouseDistanceMet(e)&&this._mouseDelayMet(e)&&(this._mouseStarted=this._mouseStart(e)!==!1,!this._mouseStarted)?(e.preventDefault(),!0):(!0===t.data(e.target,this.widgetName+".preventClickEvent")&&t.removeData(e.target,this.widgetName+".preventClickEvent"),this._mouseMoveDelegate=function(t){return i._mouseMove(t)},this._mouseUpDelegate=function(t){return i._mouseUp(t)},this.document.on("mousemove."+this.widgetName,this._mouseMoveDelegate).on("mouseup."+this.widgetName,this._mouseUpDelegate),e.preventDefault(),_=!0,!0)):!0}},_mouseMove:function(e){if(this._mouseMoved){if(t.ui.ie&&(!document.documentMode||9>document.documentMode)&&!e.button)return this._mouseUp(e);if(!e.which)if(e.originalEvent.altKey||e.originalEvent.ctrlKey||e.originalEvent.metaKey||e.originalEvent.shiftKey)this.ignoreMissingWhich=!0;else if(!this.ignoreMissingWhich)return this._mouseUp(e)}return(e.which||e.button)&&(this._mouseMoved=!0),this._mouseStarted?(this._mouseDrag(e),e.preventDefault()):(this._mouseDistanceMet(e)&&this._mouseDelayMet(e)&&(this._mouseStarted=this._mouseStart(this._mouseDownEvent,e)!==!1,this._mouseStarted?this._mouseDrag(e):this._mouseUp(e)),!this._mouseStarted)},_mouseUp:function(e){this.document.off("mousemove."+this.widgetName,this._mouseMoveDelegate).off("mouseup."+this.widgetName,this._mouseUpDelegate),this._mouseStarted&&(this._mouseStarted=!1,e.target===this._mouseDownEvent.target&&t.data(e.target,this.widgetName+".preventClickEvent",!0),this._mouseStop(e)),this._mouseDelayTimer&&(clearTimeout(this._mouseDelayTimer),delete this._mouseDelayTimer),this.ignoreMissingWhich=!1,_=!1,e.preventDefault()},_mouseDistanceMet:function(t){return Math.max(Math.abs(this._mouseDownEvent.pageX-t.pageX),Math.abs(this._mouseDownEvent.pageY-t.pageY))>=this.options.distance},_mouseDelayMet:function(){return this.mouseDelayMet},_mouseStart:function(){},_mouseDrag:function(){},_mouseStop:function(){},_mouseCapture:function(){return!0}}),t.ui.plugin={add:function(e,i,s){var n,o=t.ui[e].prototype;for(n in s)o.plugins[n]=o.plugins[n]||[],o.plugins[n].push([i,s[n]])},call:function(t,e,i,s){var n,o=t.plugins[e];if(o&&(s||t.element[0].parentNode&&11!==t.element[0].parentNode.nodeType))for(n=0;o.length>n;n++)t.options[o[n][0]]&&o[n][1].apply(t.element,i)}},t.ui.safeBlur=function(e){e&&"body"!==e.nodeName.toLowerCase()&&t(e).trigger("blur")},t.widget("ui.draggable",t.ui.mouse,{version:"1.12.1",widgetEventPrefix:"drag",options:{addClasses:!0,appendTo:"parent",axis:!1,connectToSortable:!1,containment:!1,cursor:"auto",cursorAt:!1,grid:!1,handle:!1,helper:"original",iframeFix:!1,opacity:!1,refreshPositions:!1,revert:!1,revertDuration:500,scope:"default",scroll:!0,scrollSensitivity:20,scrollSpeed:20,snap:!1,snapMode:"both",snapTolerance:20,stack:!1,zIndex:!1,drag:null,start:null,stop:null},_create:function(){"original"===this.options.helper&&this._setPositionRelative(),this.options.addClasses&&this._addClass("ui-draggable"),this._setHandleClassName(),this._mouseInit()},_setOption:function(t,e){this._super(t,e),"handle"===t&&(this._removeHandleClassName(),this._setHandleClassName())},_destroy:function(){return(this.helper||this.element).is(".ui-draggable-dragging")?(this.destroyOnClear=!0,void 0):(this._removeHandleClassName(),this._mouseDestroy(),void 0)},_mouseCapture:function(e){var i=this.options;return this.helper||i.disabled||t(e.target).closest(".ui-resizable-handle").length>0?!1:(this.handle=this._getHandle(e),this.handle?(this._blurActiveElement(e),this._blockFrames(i.iframeFix===!0?"iframe":i.iframeFix),!0):!1)},_blockFrames:function(e){this.iframeBlocks=this.document.find(e).map(function(){var e=t(this);return t("<div>").css("position","absolute").appendTo(e.parent()).outerWidth(e.outerWidth()).outerHeight(e.outerHeight()).offset(e.offset())[0]})},_unblockFrames:function(){this.iframeBlocks&&(this.iframeBlocks.remove(),delete this.iframeBlocks)},_blurActiveElement:function(e){var i=t.ui.safeActiveElement(this.document[0]),s=t(e.target);s.closest(i).length||t.ui.safeBlur(i)},_mouseStart:function(e){var i=this.options;return this.helper=this._createHelper(e),this._addClass(this.helper,"ui-draggable-dragging"),this._cacheHelperProportions(),t.ui.ddmanager&&(t.ui.ddmanager.current=this),this._cacheMargins(),this.cssPosition=this.helper.css("position"),this.scrollParent=this.helper.scrollParent(!0),this.offsetParent=this.helper.offsetParent(),this.hasFixedAncestor=this.helper.parents().filter(function(){return"fixed"===t(this).css("position")}).length>0,this.positionAbs=this.element.offset(),this._refreshOffsets(e),this.originalPosition=this.position=this._generatePosition(e,!1),this.originalPageX=e.pageX,this.originalPageY=e.pageY,i.cursorAt&&this._adjustOffsetFromHelper(i.cursorAt),this._setContainment(),this._trigger("start",e)===!1?(this._clear(),!1):(this._cacheHelperProportions(),t.ui.ddmanager&&!i.dropBehaviour&&t.ui.ddmanager.prepareOffsets(this,e),this._mouseDrag(e,!0),t.ui.ddmanager&&t.ui.ddmanager.dragStart(this,e),!0)},_refreshOffsets:function(t){this.offset={top:this.positionAbs.top-this.margins.top,left:this.positionAbs.left-this.margins.left,scroll:!1,parent:this._getParentOffset(),relative:this._getRelativeOffset()},this.offset.click={left:t.pageX-this.offset.left,top:t.pageY-this.offset.top}},_mouseDrag:function(e,i){if(this.hasFixedAncestor&&(this.offset.parent=this._getParentOffset()),this.position=this._generatePosition(e,!0),this.positionAbs=this._convertPositionTo("absolute"),!i){var s=this._uiHash();if(this._trigger("drag",e,s)===!1)return this._mouseUp(new t.Event("mouseup",e)),!1;this.position=s.position}return this.helper[0].style.left=this.position.left+"px",this.helper[0].style.top=this.position.top+"px",t.ui.ddmanager&&t.ui.ddmanager.drag(this,e),!1},_mouseStop:function(e){var i=this,s=!1;return t.ui.ddmanager&&!this.options.dropBehaviour&&(s=t.ui.ddmanager.drop(this,e)),this.dropped&&(s=this.dropped,this.dropped=!1),"invalid"===this.options.revert&&!s||"valid"===this.options.revert&&s||this.options.revert===!0||t.isFunction(this.options.revert)&&this.options.revert.call(this.element,s)?t(this.helper).animate(this.originalPosition,parseInt(this.options.revertDuration,10),function(){i._trigger("stop",e)!==!1&&i._clear()}):this._trigger("stop",e)!==!1&&this._clear(),!1},_mouseUp:function(e){return this._unblockFrames(),t.ui.ddmanager&&t.ui.ddmanager.dragStop(this,e),this.handleElement.is(e.target)&&this.element.trigger("focus"),t.ui.mouse.prototype._mouseUp.call(this,e)},cancel:function(){return this.helper.is(".ui-draggable-dragging")?this._mouseUp(new t.Event("mouseup",{target:this.element[0]})):this._clear(),this},_getHandle:function(e){return this.options.handle?!!t(e.target).closest(this.element.find(this.options.handle)).length:!0},_setHandleClassName:function(){this.handleElement=this.options.handle?this.element.find(this.options.handle):this.element,this._addClass(this.handleElement,"ui-draggable-handle")},_removeHandleClassName:function(){this._removeClass(this.handleElement,"ui-draggable-handle")},_createHelper:function(e){var i=this.options,s=t.isFunction(i.helper),n=s?t(i.helper.apply(this.element[0],[e])):"clone"===i.helper?this.element.clone().removeAttr("id"):this.element;return n.parents("body").length||n.appendTo("parent"===i.appendTo?this.element[0].parentNode:i.appendTo),s&&n[0]===this.element[0]&&this._setPositionRelative(),n[0]===this.element[0]||/(fixed|absolute)/.test(n.css("position"))||n.css("position","absolute"),n},_setPositionRelative:function(){/^(?:r|a|f)/.test(this.element.css("position"))||(this.element[0].style.position="relative")},_adjustOffsetFromHelper:function(e){"string"==typeof e&&(e=e.split(" ")),t.isArray(e)&&(e={left:+e[0],top:+e[1]||0}),"left"in e&&(this.offset.click.left=e.left+this.margins.left),"right"in e&&(this.offset.click.left=this.helperProportions.width-e.right+this.margins.left),"top"in e&&(this.offset.click.top=e.top+this.margins.top),"bottom"in e&&(this.offset.click.top=this.helperProportions.height-e.bottom+this.margins.top)},_isRootNode:function(t){return/(html|body)/i.test(t.tagName)||t===this.document[0]},_getParentOffset:function(){var e=this.offsetParent.offset(),i=this.document[0];return"absolute"===this.cssPosition&&this.scrollParent[0]!==i&&t.contains(this.scrollParent[0],this.offsetParent[0])&&(e.left+=this.scrollParent.scrollLeft(),e.top+=this.scrollParent.scrollTop()),this._isRootNode(this.offsetParent[0])&&(e={top:0,left:0}),{top:e.top+(parseInt(this.offsetParent.css("borderTopWidth"),10)||0),left:e.left+(parseInt(this.offsetParent.css("borderLeftWidth"),10)||0)}},_getRelativeOffset:function(){if("relative"!==this.cssPosition)return{top:0,left:0};var t=this.element.position(),e=this._isRootNode(this.scrollParent[0]);return{top:t.top-(parseInt(this.helper.css("top"),10)||0)+(e?0:this.scrollParent.scrollTop()),left:t.left-(parseInt(this.helper.css("left"),10)||0)+(e?0:this.scrollParent.scrollLeft())}
1230},_cacheMargins:function(){this.margins={left:parseInt(this.element.css("marginLeft"),10)||0,top:parseInt(this.element.css("marginTop"),10)||0,right:parseInt(this.element.css("marginRight"),10)||0,bottom:parseInt(this.element.css("marginBottom"),10)||0}},_cacheHelperProportions:function(){this.helperProportions={width:this.helper.outerWidth(),height:this.helper.outerHeight()}},_setContainment:function(){var e,i,s,n=this.options,o=this.document[0];return this.relativeContainer=null,n.containment?"window"===n.containment?(this.containment=[t(window).scrollLeft()-this.offset.relative.left-this.offset.parent.left,t(window).scrollTop()-this.offset.relative.top-this.offset.parent.top,t(window).scrollLeft()+t(window).width()-this.helperProportions.width-this.margins.left,t(window).scrollTop()+(t(window).height()||o.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top],void 0):"document"===n.containment?(this.containment=[0,0,t(o).width()-this.helperProportions.width-this.margins.left,(t(o).height()||o.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top],void 0):n.containment.constructor===Array?(this.containment=n.containment,void 0):("parent"===n.containment&&(n.containment=this.helper[0].parentNode),i=t(n.containment),s=i[0],s&&(e=/(scroll|auto)/.test(i.css("overflow")),this.containment=[(parseInt(i.css("borderLeftWidth"),10)||0)+(parseInt(i.css("paddingLeft"),10)||0),(parseInt(i.css("borderTopWidth"),10)||0)+(parseInt(i.css("paddingTop"),10)||0),(e?Math.max(s.scrollWidth,s.offsetWidth):s.offsetWidth)-(parseInt(i.css("borderRightWidth"),10)||0)-(parseInt(i.css("paddingRight"),10)||0)-this.helperProportions.width-this.margins.left-this.margins.right,(e?Math.max(s.scrollHeight,s.offsetHeight):s.offsetHeight)-(parseInt(i.css("borderBottomWidth"),10)||0)-(parseInt(i.css("paddingBottom"),10)||0)-this.helperProportions.height-this.margins.top-this.margins.bottom],this.relativeContainer=i),void 0):(this.containment=null,void 0)},_convertPositionTo:function(t,e){e||(e=this.position);var i="absolute"===t?1:-1,s=this._isRootNode(this.scrollParent[0]);return{top:e.top+this.offset.relative.top*i+this.offset.parent.top*i-("fixed"===this.cssPosition?-this.offset.scroll.top:s?0:this.offset.scroll.top)*i,left:e.left+this.offset.relative.left*i+this.offset.parent.left*i-("fixed"===this.cssPosition?-this.offset.scroll.left:s?0:this.offset.scroll.left)*i}},_generatePosition:function(t,e){var i,s,n,o,a=this.options,r=this._isRootNode(this.scrollParent[0]),h=t.pageX,l=t.pageY;return r&&this.offset.scroll||(this.offset.scroll={top:this.scrollParent.scrollTop(),left:this.scrollParent.scrollLeft()}),e&&(this.containment&&(this.relativeContainer?(s=this.relativeContainer.offset(),i=[this.containment[0]+s.left,this.containment[1]+s.top,this.containment[2]+s.left,this.containment[3]+s.top]):i=this.containment,t.pageX-this.offset.click.left<i[0]&&(h=i[0]+this.offset.click.left),t.pageY-this.offset.click.top<i[1]&&(l=i[1]+this.offset.click.top),t.pageX-this.offset.click.left>i[2]&&(h=i[2]+this.offset.click.left),t.pageY-this.offset.click.top>i[3]&&(l=i[3]+this.offset.click.top)),a.grid&&(n=a.grid[1]?this.originalPageY+Math.round((l-this.originalPageY)/a.grid[1])*a.grid[1]:this.originalPageY,l=i?n-this.offset.click.top>=i[1]||n-this.offset.click.top>i[3]?n:n-this.offset.click.top>=i[1]?n-a.grid[1]:n+a.grid[1]:n,o=a.grid[0]?this.originalPageX+Math.round((h-this.originalPageX)/a.grid[0])*a.grid[0]:this.originalPageX,h=i?o-this.offset.click.left>=i[0]||o-this.offset.click.left>i[2]?o:o-this.offset.click.left>=i[0]?o-a.grid[0]:o+a.grid[0]:o),"y"===a.axis&&(h=this.originalPageX),"x"===a.axis&&(l=this.originalPageY)),{top:l-this.offset.click.top-this.offset.relative.top-this.offset.parent.top+("fixed"===this.cssPosition?-this.offset.scroll.top:r?0:this.offset.scroll.top),left:h-this.offset.click.left-this.offset.relative.left-this.offset.parent.left+("fixed"===this.cssPosition?-this.offset.scroll.left:r?0:this.offset.scroll.left)}},_clear:function(){this._removeClass(this.helper,"ui-draggable-dragging"),this.helper[0]===this.element[0]||this.cancelHelperRemoval||this.helper.remove(),this.helper=null,this.cancelHelperRemoval=!1,this.destroyOnClear&&this.destroy()},_trigger:function(e,i,s){return s=s||this._uiHash(),t.ui.plugin.call(this,e,[i,s,this],!0),/^(drag|start|stop)/.test(e)&&(this.positionAbs=this._convertPositionTo("absolute"),s.offset=this.positionAbs),t.Widget.prototype._trigger.call(this,e,i,s)},plugins:{},_uiHash:function(){return{helper:this.helper,position:this.position,originalPosition:this.originalPosition,offset:this.positionAbs}}}),t.ui.plugin.add("draggable","connectToSortable",{start:function(e,i,s){var n=t.extend({},i,{item:s.element});s.sortables=[],t(s.options.connectToSortable).each(function(){var i=t(this).sortable("instance");i&&!i.options.disabled&&(s.sortables.push(i),i.refreshPositions(),i._trigger("activate",e,n))})},stop:function(e,i,s){var n=t.extend({},i,{item:s.element});s.cancelHelperRemoval=!1,t.each(s.sortables,function(){var t=this;t.isOver?(t.isOver=0,s.cancelHelperRemoval=!0,t.cancelHelperRemoval=!1,t._storedCSS={position:t.placeholder.css("position"),top:t.placeholder.css("top"),left:t.placeholder.css("left")},t._mouseStop(e),t.options.helper=t.options._helper):(t.cancelHelperRemoval=!0,t._trigger("deactivate",e,n))})},drag:function(e,i,s){t.each(s.sortables,function(){var n=!1,o=this;o.positionAbs=s.positionAbs,o.helperProportions=s.helperProportions,o.offset.click=s.offset.click,o._intersectsWith(o.containerCache)&&(n=!0,t.each(s.sortables,function(){return this.positionAbs=s.positionAbs,this.helperProportions=s.helperProportions,this.offset.click=s.offset.click,this!==o&&this._intersectsWith(this.containerCache)&&t.contains(o.element[0],this.element[0])&&(n=!1),n})),n?(o.isOver||(o.isOver=1,s._parent=i.helper.parent(),o.currentItem=i.helper.appendTo(o.element).data("ui-sortable-item",!0),o.options._helper=o.options.helper,o.options.helper=function(){return i.helper[0]},e.target=o.currentItem[0],o._mouseCapture(e,!0),o._mouseStart(e,!0,!0),o.offset.click.top=s.offset.click.top,o.offset.click.left=s.offset.click.left,o.offset.parent.left-=s.offset.parent.left-o.offset.parent.left,o.offset.parent.top-=s.offset.parent.top-o.offset.parent.top,s._trigger("toSortable",e),s.dropped=o.element,t.each(s.sortables,function(){this.refreshPositions()}),s.currentItem=s.element,o.fromOutside=s),o.currentItem&&(o._mouseDrag(e),i.position=o.position)):o.isOver&&(o.isOver=0,o.cancelHelperRemoval=!0,o.options._revert=o.options.revert,o.options.revert=!1,o._trigger("out",e,o._uiHash(o)),o._mouseStop(e,!0),o.options.revert=o.options._revert,o.options.helper=o.options._helper,o.placeholder&&o.placeholder.remove(),i.helper.appendTo(s._parent),s._refreshOffsets(e),i.position=s._generatePosition(e,!0),s._trigger("fromSortable",e),s.dropped=!1,t.each(s.sortables,function(){this.refreshPositions()}))})}}),t.ui.plugin.add("draggable","cursor",{start:function(e,i,s){var n=t("body"),o=s.options;n.css("cursor")&&(o._cursor=n.css("cursor")),n.css("cursor",o.cursor)},stop:function(e,i,s){var n=s.options;n._cursor&&t("body").css("cursor",n._cursor)}}),t.ui.plugin.add("draggable","opacity",{start:function(e,i,s){var n=t(i.helper),o=s.options;n.css("opacity")&&(o._opacity=n.css("opacity")),n.css("opacity",o.opacity)},stop:function(e,i,s){var n=s.options;n._opacity&&t(i.helper).css("opacity",n._opacity)}}),t.ui.plugin.add("draggable","scroll",{start:function(t,e,i){i.scrollParentNotHidden||(i.scrollParentNotHidden=i.helper.scrollParent(!1)),i.scrollParentNotHidden[0]!==i.document[0]&&"HTML"!==i.scrollParentNotHidden[0].tagName&&(i.overflowOffset=i.scrollParentNotHidden.offset())},drag:function(e,i,s){var n=s.options,o=!1,a=s.scrollParentNotHidden[0],r=s.document[0];a!==r&&"HTML"!==a.tagName?(n.axis&&"x"===n.axis||(s.overflowOffset.top+a.offsetHeight-e.pageY<n.scrollSensitivity?a.scrollTop=o=a.scrollTop+n.scrollSpeed:e.pageY-s.overflowOffset.top<n.scrollSensitivity&&(a.scrollTop=o=a.scrollTop-n.scrollSpeed)),n.axis&&"y"===n.axis||(s.overflowOffset.left+a.offsetWidth-e.pageX<n.scrollSensitivity?a.scrollLeft=o=a.scrollLeft+n.scrollSpeed:e.pageX-s.overflowOffset.left<n.scrollSensitivity&&(a.scrollLeft=o=a.scrollLeft-n.scrollSpeed))):(n.axis&&"x"===n.axis||(e.pageY-t(r).scrollTop()<n.scrollSensitivity?o=t(r).scrollTop(t(r).scrollTop()-n.scrollSpeed):t(window).height()-(e.pageY-t(r).scrollTop())<n.scrollSensitivity&&(o=t(r).scrollTop(t(r).scrollTop()+n.scrollSpeed))),n.axis&&"y"===n.axis||(e.pageX-t(r).scrollLeft()<n.scrollSensitivity?o=t(r).scrollLeft(t(r).scrollLeft()-n.scrollSpeed):t(window).width()-(e.pageX-t(r).scrollLeft())<n.scrollSensitivity&&(o=t(r).scrollLeft(t(r).scrollLeft()+n.scrollSpeed)))),o!==!1&&t.ui.ddmanager&&!n.dropBehaviour&&t.ui.ddmanager.prepareOffsets(s,e)}}),t.ui.plugin.add("draggable","snap",{start:function(e,i,s){var n=s.options;s.snapElements=[],t(n.snap.constructor!==String?n.snap.items||":data(ui-draggable)":n.snap).each(function(){var e=t(this),i=e.offset();this!==s.element[0]&&s.snapElements.push({item:this,width:e.outerWidth(),height:e.outerHeight(),top:i.top,left:i.left})})},drag:function(e,i,s){var n,o,a,r,h,l,c,u,d,p,f=s.options,g=f.snapTolerance,m=i.offset.left,_=m+s.helperProportions.width,v=i.offset.top,b=v+s.helperProportions.height;for(d=s.snapElements.length-1;d>=0;d--)h=s.snapElements[d].left-s.margins.left,l=h+s.snapElements[d].width,c=s.snapElements[d].top-s.margins.top,u=c+s.snapElements[d].height,h-g>_||m>l+g||c-g>b||v>u+g||!t.contains(s.snapElements[d].item.ownerDocument,s.snapElements[d].item)?(s.snapElements[d].snapping&&s.options.snap.release&&s.options.snap.release.call(s.element,e,t.extend(s._uiHash(),{snapItem:s.snapElements[d].item})),s.snapElements[d].snapping=!1):("inner"!==f.snapMode&&(n=g>=Math.abs(c-b),o=g>=Math.abs(u-v),a=g>=Math.abs(h-_),r=g>=Math.abs(l-m),n&&(i.position.top=s._convertPositionTo("relative",{top:c-s.helperProportions.height,left:0}).top),o&&(i.position.top=s._convertPositionTo("relative",{top:u,left:0}).top),a&&(i.position.left=s._convertPositionTo("relative",{top:0,left:h-s.helperProportions.width}).left),r&&(i.position.left=s._convertPositionTo("relative",{top:0,left:l}).left)),p=n||o||a||r,"outer"!==f.snapMode&&(n=g>=Math.abs(c-v),o=g>=Math.abs(u-b),a=g>=Math.abs(h-m),r=g>=Math.abs(l-_),n&&(i.position.top=s._convertPositionTo("relative",{top:c,left:0}).top),o&&(i.position.top=s._convertPositionTo("relative",{top:u-s.helperProportions.height,left:0}).top),a&&(i.position.left=s._convertPositionTo("relative",{top:0,left:h}).left),r&&(i.position.left=s._convertPositionTo("relative",{top:0,left:l-s.helperProportions.width}).left)),!s.snapElements[d].snapping&&(n||o||a||r||p)&&s.options.snap.snap&&s.options.snap.snap.call(s.element,e,t.extend(s._uiHash(),{snapItem:s.snapElements[d].item})),s.snapElements[d].snapping=n||o||a||r||p)}}),t.ui.plugin.add("draggable","stack",{start:function(e,i,s){var n,o=s.options,a=t.makeArray(t(o.stack)).sort(function(e,i){return(parseInt(t(e).css("zIndex"),10)||0)-(parseInt(t(i).css("zIndex"),10)||0)});a.length&&(n=parseInt(t(a[0]).css("zIndex"),10)||0,t(a).each(function(e){t(this).css("zIndex",n+e)}),this.css("zIndex",n+a.length))}}),t.ui.plugin.add("draggable","zIndex",{start:function(e,i,s){var n=t(i.helper),o=s.options;n.css("zIndex")&&(o._zIndex=n.css("zIndex")),n.css("zIndex",o.zIndex)},stop:function(e,i,s){var n=s.options;n._zIndex&&t(i.helper).css("zIndex",n._zIndex)}}),t.ui.draggable,t.widget("ui.resizable",t.ui.mouse,{version:"1.12.1",widgetEventPrefix:"resize",options:{alsoResize:!1,animate:!1,animateDuration:"slow",animateEasing:"swing",aspectRatio:!1,autoHide:!1,classes:{"ui-resizable-se":"ui-icon ui-icon-gripsmall-diagonal-se"},containment:!1,ghost:!1,grid:!1,handles:"e,s,se",helper:!1,maxHeight:null,maxWidth:null,minHeight:10,minWidth:10,zIndex:90,resize:null,start:null,stop:null},_num:function(t){return parseFloat(t)||0},_isNumber:function(t){return!isNaN(parseFloat(t))},_hasScroll:function(e,i){if("hidden"===t(e).css("overflow"))return!1;var s=i&&"left"===i?"scrollLeft":"scrollTop",n=!1;return e[s]>0?!0:(e[s]=1,n=e[s]>0,e[s]=0,n)},_create:function(){var e,i=this.options,s=this;this._addClass("ui-resizable"),t.extend(this,{_aspectRatio:!!i.aspectRatio,aspectRatio:i.aspectRatio,originalElement:this.element,_proportionallyResizeElements:[],_helper:i.helper||i.ghost||i.animate?i.helper||"ui-resizable-helper":null}),this.element[0].nodeName.match(/^(canvas|textarea|input|select|button|img)$/i)&&(this.element.wrap(t("<div class='ui-wrapper' style='overflow: hidden;'></div>").css({position:this.element.css("position"),width:this.element.outerWidth(),height:this.element.outerHeight(),top:this.element.css("top"),left:this.element.css("left")})),this.element=this.element.parent().data("ui-resizable",this.element.resizable("instance")),this.elementIsWrapper=!0,e={marginTop:this.originalElement.css("marginTop"),marginRight:this.originalElement.css("marginRight"),marginBottom:this.originalElement.css("marginBottom"),marginLeft:this.originalElement.css("marginLeft")},this.element.css(e),this.originalElement.css("margin",0),this.originalResizeStyle=this.originalElement.css("resize"),this.originalElement.css("resize","none"),this._proportionallyResizeElements.push(this.originalElement.css({position:"static",zoom:1,display:"block"})),this.originalElement.css(e),this._proportionallyResize()),this._setupHandles(),i.autoHide&&t(this.element).on("mouseenter",function(){i.disabled||(s._removeClass("ui-resizable-autohide"),s._handles.show())}).on("mouseleave",function(){i.disabled||s.resizing||(s._addClass("ui-resizable-autohide"),s._handles.hide())}),this._mouseInit()},_destroy:function(){this._mouseDestroy();var e,i=function(e){t(e).removeData("resizable").removeData("ui-resizable").off(".resizable").find(".ui-resizable-handle").remove()};return this.elementIsWrapper&&(i(this.element),e=this.element,this.originalElement.css({position:e.css("position"),width:e.outerWidth(),height:e.outerHeight(),top:e.css("top"),left:e.css("left")}).insertAfter(e),e.remove()),this.originalElement.css("resize",this.originalResizeStyle),i(this.originalElement),this},_setOption:function(t,e){switch(this._super(t,e),t){case"handles":this._removeHandles(),this._setupHandles();break;default:}},_setupHandles:function(){var e,i,s,n,o,a=this.options,r=this;if(this.handles=a.handles||(t(".ui-resizable-handle",this.element).length?{n:".ui-resizable-n",e:".ui-resizable-e",s:".ui-resizable-s",w:".ui-resizable-w",se:".ui-resizable-se",sw:".ui-resizable-sw",ne:".ui-resizable-ne",nw:".ui-resizable-nw"}:"e,s,se"),this._handles=t(),this.handles.constructor===String)for("all"===this.handles&&(this.handles="n,e,s,w,se,sw,ne,nw"),s=this.handles.split(","),this.handles={},i=0;s.length>i;i++)e=t.trim(s[i]),n="ui-resizable-"+e,o=t("<div>"),this._addClass(o,"ui-resizable-handle "+n),o.css({zIndex:a.zIndex}),this.handles[e]=".ui-resizable-"+e,this.element.append(o);this._renderAxis=function(e){var i,s,n,o;e=e||this.element;for(i in this.handles)this.handles[i].constructor===String?this.handles[i]=this.element.children(this.handles[i]).first().show():(this.handles[i].jquery||this.handles[i].nodeType)&&(this.handles[i]=t(this.handles[i]),this._on(this.handles[i],{mousedown:r._mouseDown})),this.elementIsWrapper&&this.originalElement[0].nodeName.match(/^(textarea|input|select|button)$/i)&&(s=t(this.handles[i],this.element),o=/sw|ne|nw|se|n|s/.test(i)?s.outerHeight():s.outerWidth(),n=["padding",/ne|nw|n/.test(i)?"Top":/se|sw|s/.test(i)?"Bottom":/^e$/.test(i)?"Right":"Left"].join(""),e.css(n,o),this._proportionallyResize()),this._handles=this._handles.add(this.handles[i])},this._renderAxis(this.element),this._handles=this._handles.add(this.element.find(".ui-resizable-handle")),this._handles.disableSelection(),this._handles.on("mouseover",function(){r.resizing||(this.className&&(o=this.className.match(/ui-resizable-(se|sw|ne|nw|n|e|s|w)/i)),r.axis=o&&o[1]?o[1]:"se")}),a.autoHide&&(this._handles.hide(),this._addClass("ui-resizable-autohide"))},_removeHandles:function(){this._handles.remove()},_mouseCapture:function(e){var i,s,n=!1;for(i in this.handles)s=t(this.handles[i])[0],(s===e.target||t.contains(s,e.target))&&(n=!0);return!this.options.disabled&&n},_mouseStart:function(e){var i,s,n,o=this.options,a=this.element;return this.resizing=!0,this._renderProxy(),i=this._num(this.helper.css("left")),s=this._num(this.helper.css("top")),o.containment&&(i+=t(o.containment).scrollLeft()||0,s+=t(o.containment).scrollTop()||0),this.offset=this.helper.offset(),this.position={left:i,top:s},this.size=this._helper?{width:this.helper.width(),height:this.helper.height()}:{width:a.width(),height:a.height()},this.originalSize=this._helper?{width:a.outerWidth(),height:a.outerHeight()}:{width:a.width(),height:a.height()},this.sizeDiff={width:a.outerWidth()-a.width(),height:a.outerHeight()-a.height()},this.originalPosition={left:i,top:s},this.originalMousePosition={left:e.pageX,top:e.pageY},this.aspectRatio="number"==typeof o.aspectRatio?o.aspectRatio:this.originalSize.width/this.originalSize.height||1,n=t(".ui-resizable-"+this.axis).css("cursor"),t("body").css("cursor","auto"===n?this.axis+"-resize":n),this._addClass("ui-resizable-resizing"),this._propagate("start",e),!0},_mouseDrag:function(e){var i,s,n=this.originalMousePosition,o=this.axis,a=e.pageX-n.left||0,r=e.pageY-n.top||0,h=this._change[o];return this._updatePrevProperties(),h?(i=h.apply(this,[e,a,r]),this._updateVirtualBoundaries(e.shiftKey),(this._aspectRatio||e.shiftKey)&&(i=this._updateRatio(i,e)),i=this._respectSize(i,e),this._updateCache(i),this._propagate("resize",e),s=this._applyChanges(),!this._helper&&this._proportionallyResizeElements.length&&this._proportionallyResize(),t.isEmptyObject(s)||(this._updatePrevProperties(),this._trigger("resize",e,this.ui()),this._applyChanges()),!1):!1},_mouseStop:function(e){this.resizing=!1;var i,s,n,o,a,r,h,l=this.options,c=this;return this._helper&&(i=this._proportionallyResizeElements,s=i.length&&/textarea/i.test(i[0].nodeName),n=s&&this._hasScroll(i[0],"left")?0:c.sizeDiff.height,o=s?0:c.sizeDiff.width,a={width:c.helper.width()-o,height:c.helper.height()-n},r=parseFloat(c.element.css("left"))+(c.position.left-c.originalPosition.left)||null,h=parseFloat(c.element.css("top"))+(c.position.top-c.originalPosition.top)||null,l.animate||this.element.css(t.extend(a,{top:h,left:r})),c.helper.height(c.size.height),c.helper.width(c.size.width),this._helper&&!l.animate&&this._proportionallyResize()),t("body").css("cursor","auto"),this._removeClass("ui-resizable-resizing"),this._propagate("stop",e),this._helper&&this.helper.remove(),!1},_updatePrevProperties:function(){this.prevPosition={top:this.position.top,left:this.position.left},this.prevSize={width:this.size.width,height:this.size.height}},_applyChanges:function(){var t={};return this.position.top!==this.prevPosition.top&&(t.top=this.position.top+"px"),this.position.left!==this.prevPosition.left&&(t.left=this.position.left+"px"),this.size.width!==this.prevSize.width&&(t.width=this.size.width+"px"),this.size.height!==this.prevSize.height&&(t.height=this.size.height+"px"),this.helper.css(t),t},_updateVirtualBoundaries:function(t){var e,i,s,n,o,a=this.options;o={minWidth:this._isNumber(a.minWidth)?a.minWidth:0,maxWidth:this._isNumber(a.maxWidth)?a.maxWidth:1/0,minHeight:this._isNumber(a.minHeight)?a.minHeight:0,maxHeight:this._isNumber(a.maxHeight)?a.maxHeight:1/0},(this._aspectRatio||t)&&(e=o.minHeight*this.aspectRatio,s=o.minWidth/this.aspectRatio,i=o.maxHeight*this.aspectRatio,n=o.maxWidth/this.aspectRatio,e>o.minWidth&&(o.minWidth=e),s>o.minHeight&&(o.minHeight=s),o.maxWidth>i&&(o.maxWidth=i),o.maxHeight>n&&(o.maxHeight=n)),this._vBoundaries=o},_updateCache:function(t){this.offset=this.helper.offset(),this._isNumber(t.left)&&(this.position.left=t.left),this._isNumber(t.top)&&(this.position.top=t.top),this._isNumber(t.height)&&(this.size.height=t.height),this._isNumber(t.width)&&(this.size.width=t.width)},_updateRatio:function(t){var e=this.position,i=this.size,s=this.axis;return this._isNumber(t.height)?t.width=t.height*this.aspectRatio:this._isNumber(t.width)&&(t.height=t.width/this.aspectRatio),"sw"===s&&(t.left=e.left+(i.width-t.width),t.top=null),"nw"===s&&(t.top=e.top+(i.height-t.height),t.left=e.left+(i.width-t.width)),t},_respectSize:function(t){var e=this._vBoundaries,i=this.axis,s=this._isNumber(t.width)&&e.maxWidth&&e.maxWidth<t.width,n=this._isNumber(t.height)&&e.maxHeight&&e.maxHeight<t.height,o=this._isNumber(t.width)&&e.minWidth&&e.minWidth>t.width,a=this._isNumber(t.height)&&e.minHeight&&e.minHeight>t.height,r=this.originalPosition.left+this.originalSize.width,h=this.originalPosition.top+this.originalSize.height,l=/sw|nw|w/.test(i),c=/nw|ne|n/.test(i);return o&&(t.width=e.minWidth),a&&(t.height=e.minHeight),s&&(t.width=e.maxWidth),n&&(t.height=e.maxHeight),o&&l&&(t.left=r-e.minWidth),s&&l&&(t.left=r-e.maxWidth),a&&c&&(t.top=h-e.minHeight),n&&c&&(t.top=h-e.maxHeight),t.width||t.height||t.left||!t.top?t.width||t.height||t.top||!t.left||(t.left=null):t.top=null,t},_getPaddingPlusBorderDimensions:function(t){for(var e=0,i=[],s=[t.css("borderTopWidth"),t.css("borderRightWidth"),t.css("borderBottomWidth"),t.css("borderLeftWidth")],n=[t.css("paddingTop"),t.css("paddingRight"),t.css("paddingBottom"),t.css("paddingLeft")];4>e;e++)i[e]=parseFloat(s[e])||0,i[e]+=parseFloat(n[e])||0;return{height:i[0]+i[2],width:i[1]+i[3]}},_proportionallyResize:function(){if(this._proportionallyResizeElements.length)for(var t,e=0,i=this.helper||this.element;this._proportionallyResizeElements.length>e;e++)t=this._proportionallyResizeElements[e],this.outerDimensions||(this.outerDimensions=this._getPaddingPlusBorderDimensions(t)),t.css({height:i.height()-this.outerDimensions.height||0,width:i.width()-this.outerDimensions.width||0})},_renderProxy:function(){var e=this.element,i=this.options;this.elementOffset=e.offset(),this._helper?(this.helper=this.helper||t("<div style='overflow:hidden;'></div>"),this._addClass(this.helper,this._helper),this.helper.css({width:this.element.outerWidth(),height:this.element.outerHeight(),position:"absolute",left:this.elementOffset.left+"px",top:this.elementOffset.top+"px",zIndex:++i.zIndex}),this.helper.appendTo("body").disableSelection()):this.helper=this.element},_change:{e:function(t,e){return{width:this.originalSize.width+e}},w:function(t,e){var i=this.originalSize,s=this.originalPosition;return{left:s.left+e,width:i.width-e}},n:function(t,e,i){var s=this.originalSize,n=this.originalPosition;return{top:n.top+i,height:s.height-i}},s:function(t,e,i){return{height:this.originalSize.height+i}},se:function(e,i,s){return t.extend(this._change.s.apply(this,arguments),this._change.e.apply(this,[e,i,s]))},sw:function(e,i,s){return t.extend(this._change.s.apply(this,arguments),this._change.w.apply(this,[e,i,s]))},ne:function(e,i,s){return t.extend(this._change.n.apply(this,arguments),this._change.e.apply(this,[e,i,s]))},nw:function(e,i,s){return t.extend(this._change.n.apply(this,arguments),this._change.w.apply(this,[e,i,s]))}},_propagate:function(e,i){t.ui.plugin.call(this,e,[i,this.ui()]),"resize"!==e&&this._trigger(e,i,this.ui())},plugins:{},ui:function(){return{originalElement:this.originalElement,element:this.element,helper:this.helper,position:this.position,size:this.size,originalSize:this.originalSize,originalPosition:this.originalPosition}}}),t.ui.plugin.add("resizable","animate",{stop:function(e){var i=t(this).resizable("instance"),s=i.options,n=i._proportionallyResizeElements,o=n.length&&/textarea/i.test(n[0].nodeName),a=o&&i._hasScroll(n[0],"left")?0:i.sizeDiff.height,r=o?0:i.sizeDiff.width,h={width:i.size.width-r,height:i.size.height-a},l=parseFloat(i.element.css("left"))+(i.position.left-i.originalPosition.left)||null,c=parseFloat(i.element.css("top"))+(i.position.top-i.originalPosition.top)||null;i.element.animate(t.extend(h,c&&l?{top:c,left:l}:{}),{duration:s.animateDuration,easing:s.animateEasing,step:function(){var s={width:parseFloat(i.element.css("width")),height:parseFloat(i.element.css("height")),top:parseFloat(i.element.css("top")),left:parseFloat(i.element.css("left"))};n&&n.length&&t(n[0]).css({width:s.width,height:s.height}),i._updateCache(s),i._propagate("resize",e)}})}}),t.ui.plugin.add("resizable","containment",{start:function(){var e,i,s,n,o,a,r,h=t(this).resizable("instance"),l=h.options,c=h.element,u=l.containment,d=u instanceof t?u.get(0):/parent/.test(u)?c.parent().get(0):u;d&&(h.containerElement=t(d),/document/.test(u)||u===document?(h.containerOffset={left:0,top:0},h.containerPosition={left:0,top:0},h.parentData={element:t(document),left:0,top:0,width:t(document).width(),height:t(document).height()||document.body.parentNode.scrollHeight}):(e=t(d),i=[],t(["Top","Right","Left","Bottom"]).each(function(t,s){i[t]=h._num(e.css("padding"+s))}),h.containerOffset=e.offset(),h.containerPosition=e.position(),h.containerSize={height:e.innerHeight()-i[3],width:e.innerWidth()-i[1]},s=h.containerOffset,n=h.containerSize.height,o=h.containerSize.width,a=h._hasScroll(d,"left")?d.scrollWidth:o,r=h._hasScroll(d)?d.scrollHeight:n,h.parentData={element:d,left:s.left,top:s.top,width:a,height:r}))},resize:function(e){var i,s,n,o,a=t(this).resizable("instance"),r=a.options,h=a.containerOffset,l=a.position,c=a._aspectRatio||e.shiftKey,u={top:0,left:0},d=a.containerElement,p=!0;d[0]!==document&&/static/.test(d.css("position"))&&(u=h),l.left<(a._helper?h.left:0)&&(a.size.width=a.size.width+(a._helper?a.position.left-h.left:a.position.left-u.left),c&&(a.size.height=a.size.width/a.aspectRatio,p=!1),a.position.left=r.helper?h.left:0),l.top<(a._helper?h.top:0)&&(a.size.height=a.size.height+(a._helper?a.position.top-h.top:a.position.top),c&&(a.size.width=a.size.height*a.aspectRatio,p=!1),a.position.top=a._helper?h.top:0),n=a.containerElement.get(0)===a.element.parent().get(0),o=/relative|absolute/.test(a.containerElement.css("position")),n&&o?(a.offset.left=a.parentData.left+a.position.left,a.offset.top=a.parentData.top+a.position.top):(a.offset.left=a.element.offset().left,a.offset.top=a.element.offset().top),i=Math.abs(a.sizeDiff.width+(a._helper?a.offset.left-u.left:a.offset.left-h.left)),s=Math.abs(a.sizeDiff.height+(a._helper?a.offset.top-u.top:a.offset.top-h.top)),i+a.size.width>=a.parentData.width&&(a.size.width=a.parentData.width-i,c&&(a.size.height=a.size.width/a.aspectRatio,p=!1)),s+a.size.height>=a.parentData.height&&(a.size.height=a.parentData.height-s,c&&(a.size.width=a.size.height*a.aspectRatio,p=!1)),p||(a.position.left=a.prevPosition.left,a.position.top=a.prevPosition.top,a.size.width=a.prevSize.width,a.size.height=a.prevSize.height)},stop:function(){var e=t(this).resizable("instance"),i=e.options,s=e.containerOffset,n=e.containerPosition,o=e.containerElement,a=t(e.helper),r=a.offset(),h=a.outerWidth()-e.sizeDiff.width,l=a.outerHeight()-e.sizeDiff.height;e._helper&&!i.animate&&/relative/.test(o.css("position"))&&t(this).css({left:r.left-n.left-s.left,width:h,height:l}),e._helper&&!i.animate&&/static/.test(o.css("position"))&&t(this).css({left:r.left-n.left-s.left,width:h,height:l})}}),t.ui.plugin.add("resizable","alsoResize",{start:function(){var e=t(this).resizable("instance"),i=e.options;t(i.alsoResize).each(function(){var e=t(this);e.data("ui-resizable-alsoresize",{width:parseFloat(e.width()),height:parseFloat(e.height()),left:parseFloat(e.css("left")),top:parseFloat(e.css("top"))})})},resize:function(e,i){var s=t(this).resizable("instance"),n=s.options,o=s.originalSize,a=s.originalPosition,r={height:s.size.height-o.height||0,width:s.size.width-o.width||0,top:s.position.top-a.top||0,left:s.position.left-a.left||0};t(n.alsoResize).each(function(){var e=t(this),s=t(this).data("ui-resizable-alsoresize"),n={},o=e.parents(i.originalElement[0]).length?["width","height"]:["width","height","top","left"];t.each(o,function(t,e){var i=(s[e]||0)+(r[e]||0);i&&i>=0&&(n[e]=i||null)}),e.css(n)})},stop:function(){t(this).removeData("ui-resizable-alsoresize")}}),t.ui.plugin.add("resizable","ghost",{start:function(){var e=t(this).resizable("instance"),i=e.size;e.ghost=e.originalElement.clone(),e.ghost.css({opacity:.25,display:"block",position:"relative",height:i.height,width:i.width,margin:0,left:0,top:0}),e._addClass(e.ghost,"ui-resizable-ghost"),t.uiBackCompat!==!1&&"string"==typeof e.options.ghost&&e.ghost.addClass(this.options.ghost),e.ghost.appendTo(e.helper)},resize:function(){var e=t(this).resizable("instance");e.ghost&&e.ghost.css({position:"relative",height:e.size.height,width:e.size.width})},stop:function(){var e=t(this).resizable("instance");e.ghost&&e.helper&&e.helper.get(0).removeChild(e.ghost.get(0))}}),t.ui.plugin.add("resizable","grid",{resize:function(){var e,i=t(this).resizable("instance"),s=i.options,n=i.size,o=i.originalSize,a=i.originalPosition,r=i.axis,h="number"==typeof s.grid?[s.grid,s.grid]:s.grid,l=h[0]||1,c=h[1]||1,u=Math.round((n.width-o.width)/l)*l,d=Math.round((n.height-o.height)/c)*c,p=o.width+u,f=o.height+d,g=s.maxWidth&&p>s.maxWidth,m=s.maxHeight&&f>s.maxHeight,_=s.minWidth&&s.minWidth>p,v=s.minHeight&&s.minHeight>f;s.grid=h,_&&(p+=l),v&&(f+=c),g&&(p-=l),m&&(f-=c),/^(se|s|e)$/.test(r)?(i.size.width=p,i.size.height=f):/^(ne)$/.test(r)?(i.size.width=p,i.size.height=f,i.position.top=a.top-d):/^(sw)$/.test(r)?(i.size.width=p,i.size.height=f,i.position.left=a.left-u):((0>=f-c||0>=p-l)&&(e=i._getPaddingPlusBorderDimensions(this)),f-c>0?(i.size.height=f,i.position.top=a.top-d):(f=c-e.height,i.size.height=f,i.position.top=a.top+o.height-f),p-l>0?(i.size.width=p,i.position.left=a.left-u):(p=l-e.width,i.size.width=p,i.position.left=a.left+o.width-p))}}),t.ui.resizable,t.widget("ui.dialog",{version:"1.12.1",options:{appendTo:"body",autoOpen:!0,buttons:[],classes:{"ui-dialog":"ui-corner-all","ui-dialog-titlebar":"ui-corner-all"},closeOnEscape:!0,closeText:"Close",draggable:!0,hide:null,height:"auto",maxHeight:null,maxWidth:null,minHeight:150,minWidth:150,modal:!1,position:{my:"center",at:"center",of:window,collision:"fit",using:function(e){var i=t(this).css(e).offset().top;0>i&&t(this).css("top",e.top-i)}},resizable:!0,show:null,title:null,width:300,beforeClose:null,close:null,drag:null,dragStart:null,dragStop:null,focus:null,open:null,resize:null,resizeStart:null,resizeStop:null},sizeRelatedOptions:{buttons:!0,height:!0,maxHeight:!0,maxWidth:!0,minHeight:!0,minWidth:!0,width:!0},resizableRelatedOptions:{maxHeight:!0,maxWidth:!0,minHeight:!0,minWidth:!0},_create:function(){this.originalCss={display:this.element[0].style.display,width:this.element[0].style.width,minHeight:this.element[0].style.minHeight,maxHeight:this.element[0].style.maxHeight,height:this.element[0].style.height},this.originalPosition={parent:this.element.parent(),index:this.element.parent().children().index(this.element)},this.originalTitle=this.element.attr("title"),null==this.options.title&&null!=this.originalTitle&&(this.options.title=this.originalTitle),this.options.disabled&&(this.options.disabled=!1),this._createWrapper(),this.element.show().removeAttr("title").appendTo(this.uiDialog),this._addClass("ui-dialog-content","ui-widget-content"),this._createTitlebar(),this._createButtonPane(),this.options.draggable&&t.fn.draggable&&this._makeDraggable(),this.options.resizable&&t.fn.resizable&&this._makeResizable(),this._isOpen=!1,this._trackFocus()},_init:function(){this.options.autoOpen&&this.open()},_appendTo:function(){var e=this.options.appendTo;return e&&(e.jquery||e.nodeType)?t(e):this.document.find(e||"body").eq(0)},_destroy:function(){var t,e=this.originalPosition;this._untrackInstance(),this._destroyOverlay(),this.element.removeUniqueId().css(this.originalCss).detach(),this.uiDialog.remove(),this.originalTitle&&this.element.attr("title",this.originalTitle),t=e.parent.children().eq(e.index),t.length&&t[0]!==this.element[0]?t.before(this.element):e.parent.append(this.element)},widget:function(){return this.uiDialog
1231},disable:t.noop,enable:t.noop,close:function(e){var i=this;this._isOpen&&this._trigger("beforeClose",e)!==!1&&(this._isOpen=!1,this._focusedElement=null,this._destroyOverlay(),this._untrackInstance(),this.opener.filter(":focusable").trigger("focus").length||t.ui.safeBlur(t.ui.safeActiveElement(this.document[0])),this._hide(this.uiDialog,this.options.hide,function(){i._trigger("close",e)}))},isOpen:function(){return this._isOpen},moveToTop:function(){this._moveToTop()},_moveToTop:function(e,i){var s=!1,n=this.uiDialog.siblings(".ui-front:visible").map(function(){return+t(this).css("z-index")}).get(),o=Math.max.apply(null,n);return o>=+this.uiDialog.css("z-index")&&(this.uiDialog.css("z-index",o+1),s=!0),s&&!i&&this._trigger("focus",e),s},open:function(){var e=this;return this._isOpen?(this._moveToTop()&&this._focusTabbable(),void 0):(this._isOpen=!0,this.opener=t(t.ui.safeActiveElement(this.document[0])),this._size(),this._position(),this._createOverlay(),this._moveToTop(null,!0),this.overlay&&this.overlay.css("z-index",this.uiDialog.css("z-index")-1),this._show(this.uiDialog,this.options.show,function(){e._focusTabbable(),e._trigger("focus")}),this._makeFocusTarget(),this._trigger("open"),void 0)},_focusTabbable:function(){var t=this._focusedElement;t||(t=this.element.find("[autofocus]")),t.length||(t=this.element.find(":tabbable")),t.length||(t=this.uiDialogButtonPane.find(":tabbable")),t.length||(t=this.uiDialogTitlebarClose.filter(":tabbable")),t.length||(t=this.uiDialog),t.eq(0).trigger("focus")},_keepFocus:function(e){function i(){var e=t.ui.safeActiveElement(this.document[0]),i=this.uiDialog[0]===e||t.contains(this.uiDialog[0],e);i||this._focusTabbable()}e.preventDefault(),i.call(this),this._delay(i)},_createWrapper:function(){this.uiDialog=t("<div>").hide().attr({tabIndex:-1,role:"dialog"}).appendTo(this._appendTo()),this._addClass(this.uiDialog,"ui-dialog","ui-widget ui-widget-content ui-front"),this._on(this.uiDialog,{keydown:function(e){if(this.options.closeOnEscape&&!e.isDefaultPrevented()&&e.keyCode&&e.keyCode===t.ui.keyCode.ESCAPE)return e.preventDefault(),this.close(e),void 0;if(e.keyCode===t.ui.keyCode.TAB&&!e.isDefaultPrevented()){var i=this.uiDialog.find(":tabbable"),s=i.filter(":first"),n=i.filter(":last");e.target!==n[0]&&e.target!==this.uiDialog[0]||e.shiftKey?e.target!==s[0]&&e.target!==this.uiDialog[0]||!e.shiftKey||(this._delay(function(){n.trigger("focus")}),e.preventDefault()):(this._delay(function(){s.trigger("focus")}),e.preventDefault())}},mousedown:function(t){this._moveToTop(t)&&this._focusTabbable()}}),this.element.find("[aria-describedby]").length||this.uiDialog.attr({"aria-describedby":this.element.uniqueId().attr("id")})},_createTitlebar:function(){var e;this.uiDialogTitlebar=t("<div>"),this._addClass(this.uiDialogTitlebar,"ui-dialog-titlebar","ui-widget-header ui-helper-clearfix"),this._on(this.uiDialogTitlebar,{mousedown:function(e){t(e.target).closest(".ui-dialog-titlebar-close")||this.uiDialog.trigger("focus")}}),this.uiDialogTitlebarClose=t("<button type='button'></button>").button({label:t("<a>").text(this.options.closeText).html(),icon:"ui-icon-closethick",showLabel:!1}).appendTo(this.uiDialogTitlebar),this._addClass(this.uiDialogTitlebarClose,"ui-dialog-titlebar-close"),this._on(this.uiDialogTitlebarClose,{click:function(t){t.preventDefault(),this.close(t)}}),e=t("<span>").uniqueId().prependTo(this.uiDialogTitlebar),this._addClass(e,"ui-dialog-title"),this._title(e),this.uiDialogTitlebar.prependTo(this.uiDialog),this.uiDialog.attr({"aria-labelledby":e.attr("id")})},_title:function(t){this.options.title?t.text(this.options.title):t.html("&#160;")},_createButtonPane:function(){this.uiDialogButtonPane=t("<div>"),this._addClass(this.uiDialogButtonPane,"ui-dialog-buttonpane","ui-widget-content ui-helper-clearfix"),this.uiButtonSet=t("<div>").appendTo(this.uiDialogButtonPane),this._addClass(this.uiButtonSet,"ui-dialog-buttonset"),this._createButtons()},_createButtons:function(){var e=this,i=this.options.buttons;return this.uiDialogButtonPane.remove(),this.uiButtonSet.empty(),t.isEmptyObject(i)||t.isArray(i)&&!i.length?(this._removeClass(this.uiDialog,"ui-dialog-buttons"),void 0):(t.each(i,function(i,s){var n,o;s=t.isFunction(s)?{click:s,text:i}:s,s=t.extend({type:"button"},s),n=s.click,o={icon:s.icon,iconPosition:s.iconPosition,showLabel:s.showLabel,icons:s.icons,text:s.text},delete s.click,delete s.icon,delete s.iconPosition,delete s.showLabel,delete s.icons,"boolean"==typeof s.text&&delete s.text,t("<button></button>",s).button(o).appendTo(e.uiButtonSet).on("click",function(){n.apply(e.element[0],arguments)})}),this._addClass(this.uiDialog,"ui-dialog-buttons"),this.uiDialogButtonPane.appendTo(this.uiDialog),void 0)},_makeDraggable:function(){function e(t){return{position:t.position,offset:t.offset}}var i=this,s=this.options;this.uiDialog.draggable({cancel:".ui-dialog-content, .ui-dialog-titlebar-close",handle:".ui-dialog-titlebar",containment:"document",start:function(s,n){i._addClass(t(this),"ui-dialog-dragging"),i._blockFrames(),i._trigger("dragStart",s,e(n))},drag:function(t,s){i._trigger("drag",t,e(s))},stop:function(n,o){var a=o.offset.left-i.document.scrollLeft(),r=o.offset.top-i.document.scrollTop();s.position={my:"left top",at:"left"+(a>=0?"+":"")+a+" "+"top"+(r>=0?"+":"")+r,of:i.window},i._removeClass(t(this),"ui-dialog-dragging"),i._unblockFrames(),i._trigger("dragStop",n,e(o))}})},_makeResizable:function(){function e(t){return{originalPosition:t.originalPosition,originalSize:t.originalSize,position:t.position,size:t.size}}var i=this,s=this.options,n=s.resizable,o=this.uiDialog.css("position"),a="string"==typeof n?n:"n,e,s,w,se,sw,ne,nw";this.uiDialog.resizable({cancel:".ui-dialog-content",containment:"document",alsoResize:this.element,maxWidth:s.maxWidth,maxHeight:s.maxHeight,minWidth:s.minWidth,minHeight:this._minHeight(),handles:a,start:function(s,n){i._addClass(t(this),"ui-dialog-resizing"),i._blockFrames(),i._trigger("resizeStart",s,e(n))},resize:function(t,s){i._trigger("resize",t,e(s))},stop:function(n,o){var a=i.uiDialog.offset(),r=a.left-i.document.scrollLeft(),h=a.top-i.document.scrollTop();s.height=i.uiDialog.height(),s.width=i.uiDialog.width(),s.position={my:"left top",at:"left"+(r>=0?"+":"")+r+" "+"top"+(h>=0?"+":"")+h,of:i.window},i._removeClass(t(this),"ui-dialog-resizing"),i._unblockFrames(),i._trigger("resizeStop",n,e(o))}}).css("position",o)},_trackFocus:function(){this._on(this.widget(),{focusin:function(e){this._makeFocusTarget(),this._focusedElement=t(e.target)}})},_makeFocusTarget:function(){this._untrackInstance(),this._trackingInstances().unshift(this)},_untrackInstance:function(){var e=this._trackingInstances(),i=t.inArray(this,e);-1!==i&&e.splice(i,1)},_trackingInstances:function(){var t=this.document.data("ui-dialog-instances");return t||(t=[],this.document.data("ui-dialog-instances",t)),t},_minHeight:function(){var t=this.options;return"auto"===t.height?t.minHeight:Math.min(t.minHeight,t.height)},_position:function(){var t=this.uiDialog.is(":visible");t||this.uiDialog.show(),this.uiDialog.position(this.options.position),t||this.uiDialog.hide()},_setOptions:function(e){var i=this,s=!1,n={};t.each(e,function(t,e){i._setOption(t,e),t in i.sizeRelatedOptions&&(s=!0),t in i.resizableRelatedOptions&&(n[t]=e)}),s&&(this._size(),this._position()),this.uiDialog.is(":data(ui-resizable)")&&this.uiDialog.resizable("option",n)},_setOption:function(e,i){var s,n,o=this.uiDialog;"disabled"!==e&&(this._super(e,i),"appendTo"===e&&this.uiDialog.appendTo(this._appendTo()),"buttons"===e&&this._createButtons(),"closeText"===e&&this.uiDialogTitlebarClose.button({label:t("<a>").text(""+this.options.closeText).html()}),"draggable"===e&&(s=o.is(":data(ui-draggable)"),s&&!i&&o.draggable("destroy"),!s&&i&&this._makeDraggable()),"position"===e&&this._position(),"resizable"===e&&(n=o.is(":data(ui-resizable)"),n&&!i&&o.resizable("destroy"),n&&"string"==typeof i&&o.resizable("option","handles",i),n||i===!1||this._makeResizable()),"title"===e&&this._title(this.uiDialogTitlebar.find(".ui-dialog-title")))},_size:function(){var t,e,i,s=this.options;this.element.show().css({width:"auto",minHeight:0,maxHeight:"none",height:0}),s.minWidth>s.width&&(s.width=s.minWidth),t=this.uiDialog.css({height:"auto",width:s.width}).outerHeight(),e=Math.max(0,s.minHeight-t),i="number"==typeof s.maxHeight?Math.max(0,s.maxHeight-t):"none","auto"===s.height?this.element.css({minHeight:e,maxHeight:i,height:"auto"}):this.element.height(Math.max(0,s.height-t)),this.uiDialog.is(":data(ui-resizable)")&&this.uiDialog.resizable("option","minHeight",this._minHeight())},_blockFrames:function(){this.iframeBlocks=this.document.find("iframe").map(function(){var e=t(this);return t("<div>").css({position:"absolute",width:e.outerWidth(),height:e.outerHeight()}).appendTo(e.parent()).offset(e.offset())[0]})},_unblockFrames:function(){this.iframeBlocks&&(this.iframeBlocks.remove(),delete this.iframeBlocks)},_allowInteraction:function(e){return t(e.target).closest(".ui-dialog").length?!0:!!t(e.target).closest(".ui-datepicker").length},_createOverlay:function(){if(this.options.modal){var e=!0;this._delay(function(){e=!1}),this.document.data("ui-dialog-overlays")||this._on(this.document,{focusin:function(t){e||this._allowInteraction(t)||(t.preventDefault(),this._trackingInstances()[0]._focusTabbable())}}),this.overlay=t("<div>").appendTo(this._appendTo()),this._addClass(this.overlay,null,"ui-widget-overlay ui-front"),this._on(this.overlay,{mousedown:"_keepFocus"}),this.document.data("ui-dialog-overlays",(this.document.data("ui-dialog-overlays")||0)+1)}},_destroyOverlay:function(){if(this.options.modal&&this.overlay){var t=this.document.data("ui-dialog-overlays")-1;t?this.document.data("ui-dialog-overlays",t):(this._off(this.document,"focusin"),this.document.removeData("ui-dialog-overlays")),this.overlay.remove(),this.overlay=null}}}),t.uiBackCompat!==!1&&t.widget("ui.dialog",t.ui.dialog,{options:{dialogClass:""},_createWrapper:function(){this._super(),this.uiDialog.addClass(this.options.dialogClass)},_setOption:function(t,e){"dialogClass"===t&&this.uiDialog.removeClass(this.options.dialogClass).addClass(e),this._superApply(arguments)}}),t.ui.dialog,t.widget("ui.droppable",{version:"1.12.1",widgetEventPrefix:"drop",options:{accept:"*",addClasses:!0,greedy:!1,scope:"default",tolerance:"intersect",activate:null,deactivate:null,drop:null,out:null,over:null},_create:function(){var e,i=this.options,s=i.accept;this.isover=!1,this.isout=!0,this.accept=t.isFunction(s)?s:function(t){return t.is(s)},this.proportions=function(){return arguments.length?(e=arguments[0],void 0):e?e:e={width:this.element[0].offsetWidth,height:this.element[0].offsetHeight}},this._addToManager(i.scope),i.addClasses&&this._addClass("ui-droppable")},_addToManager:function(e){t.ui.ddmanager.droppables[e]=t.ui.ddmanager.droppables[e]||[],t.ui.ddmanager.droppables[e].push(this)},_splice:function(t){for(var e=0;t.length>e;e++)t[e]===this&&t.splice(e,1)},_destroy:function(){var e=t.ui.ddmanager.droppables[this.options.scope];this._splice(e)},_setOption:function(e,i){if("accept"===e)this.accept=t.isFunction(i)?i:function(t){return t.is(i)};else if("scope"===e){var s=t.ui.ddmanager.droppables[this.options.scope];this._splice(s),this._addToManager(i)}this._super(e,i)},_activate:function(e){var i=t.ui.ddmanager.current;this._addActiveClass(),i&&this._trigger("activate",e,this.ui(i))},_deactivate:function(e){var i=t.ui.ddmanager.current;this._removeActiveClass(),i&&this._trigger("deactivate",e,this.ui(i))},_over:function(e){var i=t.ui.ddmanager.current;i&&(i.currentItem||i.element)[0]!==this.element[0]&&this.accept.call(this.element[0],i.currentItem||i.element)&&(this._addHoverClass(),this._trigger("over",e,this.ui(i)))},_out:function(e){var i=t.ui.ddmanager.current;i&&(i.currentItem||i.element)[0]!==this.element[0]&&this.accept.call(this.element[0],i.currentItem||i.element)&&(this._removeHoverClass(),this._trigger("out",e,this.ui(i)))},_drop:function(e,i){var s=i||t.ui.ddmanager.current,n=!1;return s&&(s.currentItem||s.element)[0]!==this.element[0]?(this.element.find(":data(ui-droppable)").not(".ui-draggable-dragging").each(function(){var i=t(this).droppable("instance");return i.options.greedy&&!i.options.disabled&&i.options.scope===s.options.scope&&i.accept.call(i.element[0],s.currentItem||s.element)&&v(s,t.extend(i,{offset:i.element.offset()}),i.options.tolerance,e)?(n=!0,!1):void 0}),n?!1:this.accept.call(this.element[0],s.currentItem||s.element)?(this._removeActiveClass(),this._removeHoverClass(),this._trigger("drop",e,this.ui(s)),this.element):!1):!1},ui:function(t){return{draggable:t.currentItem||t.element,helper:t.helper,position:t.position,offset:t.positionAbs}},_addHoverClass:function(){this._addClass("ui-droppable-hover")},_removeHoverClass:function(){this._removeClass("ui-droppable-hover")},_addActiveClass:function(){this._addClass("ui-droppable-active")},_removeActiveClass:function(){this._removeClass("ui-droppable-active")}});var v=t.ui.intersect=function(){function t(t,e,i){return t>=e&&e+i>t}return function(e,i,s,n){if(!i.offset)return!1;var o=(e.positionAbs||e.position.absolute).left+e.margins.left,a=(e.positionAbs||e.position.absolute).top+e.margins.top,r=o+e.helperProportions.width,h=a+e.helperProportions.height,l=i.offset.left,c=i.offset.top,u=l+i.proportions().width,d=c+i.proportions().height;switch(s){case"fit":return o>=l&&u>=r&&a>=c&&d>=h;case"intersect":return o+e.helperProportions.width/2>l&&u>r-e.helperProportions.width/2&&a+e.helperProportions.height/2>c&&d>h-e.helperProportions.height/2;case"pointer":return t(n.pageY,c,i.proportions().height)&&t(n.pageX,l,i.proportions().width);case"touch":return(a>=c&&d>=a||h>=c&&d>=h||c>a&&h>d)&&(o>=l&&u>=o||r>=l&&u>=r||l>o&&r>u);default:return!1}}}();t.ui.ddmanager={current:null,droppables:{"default":[]},prepareOffsets:function(e,i){var s,n,o=t.ui.ddmanager.droppables[e.options.scope]||[],a=i?i.type:null,r=(e.currentItem||e.element).find(":data(ui-droppable)").addBack();t:for(s=0;o.length>s;s++)if(!(o[s].options.disabled||e&&!o[s].accept.call(o[s].element[0],e.currentItem||e.element))){for(n=0;r.length>n;n++)if(r[n]===o[s].element[0]){o[s].proportions().height=0;continue t}o[s].visible="none"!==o[s].element.css("display"),o[s].visible&&("mousedown"===a&&o[s]._activate.call(o[s],i),o[s].offset=o[s].element.offset(),o[s].proportions({width:o[s].element[0].offsetWidth,height:o[s].element[0].offsetHeight}))}},drop:function(e,i){var s=!1;return t.each((t.ui.ddmanager.droppables[e.options.scope]||[]).slice(),function(){this.options&&(!this.options.disabled&&this.visible&&v(e,this,this.options.tolerance,i)&&(s=this._drop.call(this,i)||s),!this.options.disabled&&this.visible&&this.accept.call(this.element[0],e.currentItem||e.element)&&(this.isout=!0,this.isover=!1,this._deactivate.call(this,i)))}),s},dragStart:function(e,i){e.element.parentsUntil("body").on("scroll.droppable",function(){e.options.refreshPositions||t.ui.ddmanager.prepareOffsets(e,i)})},drag:function(e,i){e.options.refreshPositions&&t.ui.ddmanager.prepareOffsets(e,i),t.each(t.ui.ddmanager.droppables[e.options.scope]||[],function(){if(!this.options.disabled&&!this.greedyChild&&this.visible){var s,n,o,a=v(e,this,this.options.tolerance,i),r=!a&&this.isover?"isout":a&&!this.isover?"isover":null;r&&(this.options.greedy&&(n=this.options.scope,o=this.element.parents(":data(ui-droppable)").filter(function(){return t(this).droppable("instance").options.scope===n}),o.length&&(s=t(o[0]).droppable("instance"),s.greedyChild="isover"===r)),s&&"isover"===r&&(s.isover=!1,s.isout=!0,s._out.call(s,i)),this[r]=!0,this["isout"===r?"isover":"isout"]=!1,this["isover"===r?"_over":"_out"].call(this,i),s&&"isout"===r&&(s.isout=!1,s.isover=!0,s._over.call(s,i)))}})},dragStop:function(e,i){e.element.parentsUntil("body").off("scroll.droppable"),e.options.refreshPositions||t.ui.ddmanager.prepareOffsets(e,i)}},t.uiBackCompat!==!1&&t.widget("ui.droppable",t.ui.droppable,{options:{hoverClass:!1,activeClass:!1},_addActiveClass:function(){this._super(),this.options.activeClass&&this.element.addClass(this.options.activeClass)},_removeActiveClass:function(){this._super(),this.options.activeClass&&this.element.removeClass(this.options.activeClass)},_addHoverClass:function(){this._super(),this.options.hoverClass&&this.element.addClass(this.options.hoverClass)},_removeHoverClass:function(){this._super(),this.options.hoverClass&&this.element.removeClass(this.options.hoverClass)}}),t.ui.droppable,t.widget("ui.progressbar",{version:"1.12.1",options:{classes:{"ui-progressbar":"ui-corner-all","ui-progressbar-value":"ui-corner-left","ui-progressbar-complete":"ui-corner-right"},max:100,value:0,change:null,complete:null},min:0,_create:function(){this.oldValue=this.options.value=this._constrainedValue(),this.element.attr({role:"progressbar","aria-valuemin":this.min}),this._addClass("ui-progressbar","ui-widget ui-widget-content"),this.valueDiv=t("<div>").appendTo(this.element),this._addClass(this.valueDiv,"ui-progressbar-value","ui-widget-header"),this._refreshValue()},_destroy:function(){this.element.removeAttr("role aria-valuemin aria-valuemax aria-valuenow"),this.valueDiv.remove()},value:function(t){return void 0===t?this.options.value:(this.options.value=this._constrainedValue(t),this._refreshValue(),void 0)},_constrainedValue:function(t){return void 0===t&&(t=this.options.value),this.indeterminate=t===!1,"number"!=typeof t&&(t=0),this.indeterminate?!1:Math.min(this.options.max,Math.max(this.min,t))},_setOptions:function(t){var e=t.value;delete t.value,this._super(t),this.options.value=this._constrainedValue(e),this._refreshValue()},_setOption:function(t,e){"max"===t&&(e=Math.max(this.min,e)),this._super(t,e)},_setOptionDisabled:function(t){this._super(t),this.element.attr("aria-disabled",t),this._toggleClass(null,"ui-state-disabled",!!t)},_percentage:function(){return this.indeterminate?100:100*(this.options.value-this.min)/(this.options.max-this.min)},_refreshValue:function(){var e=this.options.value,i=this._percentage();this.valueDiv.toggle(this.indeterminate||e>this.min).width(i.toFixed(0)+"%"),this._toggleClass(this.valueDiv,"ui-progressbar-complete",null,e===this.options.max)._toggleClass("ui-progressbar-indeterminate",null,this.indeterminate),this.indeterminate?(this.element.removeAttr("aria-valuenow"),this.overlayDiv||(this.overlayDiv=t("<div>").appendTo(this.valueDiv),this._addClass(this.overlayDiv,"ui-progressbar-overlay"))):(this.element.attr({"aria-valuemax":this.options.max,"aria-valuenow":e}),this.overlayDiv&&(this.overlayDiv.remove(),this.overlayDiv=null)),this.oldValue!==e&&(this.oldValue=e,this._trigger("change")),e===this.options.max&&this._trigger("complete")}}),t.widget("ui.selectable",t.ui.mouse,{version:"1.12.1",options:{appendTo:"body",autoRefresh:!0,distance:0,filter:"*",tolerance:"touch",selected:null,selecting:null,start:null,stop:null,unselected:null,unselecting:null},_create:function(){var e=this;this._addClass("ui-selectable"),this.dragged=!1,this.refresh=function(){e.elementPos=t(e.element[0]).offset(),e.selectees=t(e.options.filter,e.element[0]),e._addClass(e.selectees,"ui-selectee"),e.selectees.each(function(){var i=t(this),s=i.offset(),n={left:s.left-e.elementPos.left,top:s.top-e.elementPos.top};t.data(this,"selectable-item",{element:this,$element:i,left:n.left,top:n.top,right:n.left+i.outerWidth(),bottom:n.top+i.outerHeight(),startselected:!1,selected:i.hasClass("ui-selected"),selecting:i.hasClass("ui-selecting"),unselecting:i.hasClass("ui-unselecting")})})},this.refresh(),this._mouseInit(),this.helper=t("<div>"),this._addClass(this.helper,"ui-selectable-helper")},_destroy:function(){this.selectees.removeData("selectable-item"),this._mouseDestroy()},_mouseStart:function(e){var i=this,s=this.options;this.opos=[e.pageX,e.pageY],this.elementPos=t(this.element[0]).offset(),this.options.disabled||(this.selectees=t(s.filter,this.element[0]),this._trigger("start",e),t(s.appendTo).append(this.helper),this.helper.css({left:e.pageX,top:e.pageY,width:0,height:0}),s.autoRefresh&&this.refresh(),this.selectees.filter(".ui-selected").each(function(){var s=t.data(this,"selectable-item");s.startselected=!0,e.metaKey||e.ctrlKey||(i._removeClass(s.$element,"ui-selected"),s.selected=!1,i._addClass(s.$element,"ui-unselecting"),s.unselecting=!0,i._trigger("unselecting",e,{unselecting:s.element}))}),t(e.target).parents().addBack().each(function(){var s,n=t.data(this,"selectable-item");return n?(s=!e.metaKey&&!e.ctrlKey||!n.$element.hasClass("ui-selected"),i._removeClass(n.$element,s?"ui-unselecting":"ui-selected")._addClass(n.$element,s?"ui-selecting":"ui-unselecting"),n.unselecting=!s,n.selecting=s,n.selected=s,s?i._trigger("selecting",e,{selecting:n.element}):i._trigger("unselecting",e,{unselecting:n.element}),!1):void 0}))},_mouseDrag:function(e){if(this.dragged=!0,!this.options.disabled){var i,s=this,n=this.options,o=this.opos[0],a=this.opos[1],r=e.pageX,h=e.pageY;return o>r&&(i=r,r=o,o=i),a>h&&(i=h,h=a,a=i),this.helper.css({left:o,top:a,width:r-o,height:h-a}),this.selectees.each(function(){var i=t.data(this,"selectable-item"),l=!1,c={};i&&i.element!==s.element[0]&&(c.left=i.left+s.elementPos.left,c.right=i.right+s.elementPos.left,c.top=i.top+s.elementPos.top,c.bottom=i.bottom+s.elementPos.top,"touch"===n.tolerance?l=!(c.left>r||o>c.right||c.top>h||a>c.bottom):"fit"===n.tolerance&&(l=c.left>o&&r>c.right&&c.top>a&&h>c.bottom),l?(i.selected&&(s._removeClass(i.$element,"ui-selected"),i.selected=!1),i.unselecting&&(s._removeClass(i.$element,"ui-unselecting"),i.unselecting=!1),i.selecting||(s._addClass(i.$element,"ui-selecting"),i.selecting=!0,s._trigger("selecting",e,{selecting:i.element}))):(i.selecting&&((e.metaKey||e.ctrlKey)&&i.startselected?(s._removeClass(i.$element,"ui-selecting"),i.selecting=!1,s._addClass(i.$element,"ui-selected"),i.selected=!0):(s._removeClass(i.$element,"ui-selecting"),i.selecting=!1,i.startselected&&(s._addClass(i.$element,"ui-unselecting"),i.unselecting=!0),s._trigger("unselecting",e,{unselecting:i.element}))),i.selected&&(e.metaKey||e.ctrlKey||i.startselected||(s._removeClass(i.$element,"ui-selected"),i.selected=!1,s._addClass(i.$element,"ui-unselecting"),i.unselecting=!0,s._trigger("unselecting",e,{unselecting:i.element})))))}),!1}},_mouseStop:function(e){var i=this;return this.dragged=!1,t(".ui-unselecting",this.element[0]).each(function(){var s=t.data(this,"selectable-item");i._removeClass(s.$element,"ui-unselecting"),s.unselecting=!1,s.startselected=!1,i._trigger("unselected",e,{unselected:s.element})}),t(".ui-selecting",this.element[0]).each(function(){var s=t.data(this,"selectable-item");i._removeClass(s.$element,"ui-selecting")._addClass(s.$element,"ui-selected"),s.selecting=!1,s.selected=!0,s.startselected=!0,i._trigger("selected",e,{selected:s.element})}),this._trigger("stop",e),this.helper.remove(),!1}}),t.widget("ui.selectmenu",[t.ui.formResetMixin,{version:"1.12.1",defaultElement:"<select>",options:{appendTo:null,classes:{"ui-selectmenu-button-open":"ui-corner-top","ui-selectmenu-button-closed":"ui-corner-all"},disabled:null,icons:{button:"ui-icon-triangle-1-s"},position:{my:"left top",at:"left bottom",collision:"none"},width:!1,change:null,close:null,focus:null,open:null,select:null},_create:function(){var e=this.element.uniqueId().attr("id");this.ids={element:e,button:e+"-button",menu:e+"-menu"},this._drawButton(),this._drawMenu(),this._bindFormResetHandler(),this._rendered=!1,this.menuItems=t()},_drawButton:function(){var e,i=this,s=this._parseOption(this.element.find("option:selected"),this.element[0].selectedIndex);this.labels=this.element.labels().attr("for",this.ids.button),this._on(this.labels,{click:function(t){this.button.focus(),t.preventDefault()}}),this.element.hide(),this.button=t("<span>",{tabindex:this.options.disabled?-1:0,id:this.ids.button,role:"combobox","aria-expanded":"false","aria-autocomplete":"list","aria-owns":this.ids.menu,"aria-haspopup":"true",title:this.element.attr("title")}).insertAfter(this.element),this._addClass(this.button,"ui-selectmenu-button ui-selectmenu-button-closed","ui-button ui-widget"),e=t("<span>").appendTo(this.button),this._addClass(e,"ui-selectmenu-icon","ui-icon "+this.options.icons.button),this.buttonItem=this._renderButtonItem(s).appendTo(this.button),this.options.width!==!1&&this._resizeButton(),this._on(this.button,this._buttonEvents),this.button.one("focusin",function(){i._rendered||i._refreshMenu()})},_drawMenu:function(){var e=this;this.menu=t("<ul>",{"aria-hidden":"true","aria-labelledby":this.ids.button,id:this.ids.menu}),this.menuWrap=t("<div>").append(this.menu),this._addClass(this.menuWrap,"ui-selectmenu-menu","ui-front"),this.menuWrap.appendTo(this._appendTo()),this.menuInstance=this.menu.menu({classes:{"ui-menu":"ui-corner-bottom"},role:"listbox",select:function(t,i){t.preventDefault(),e._setSelection(),e._select(i.item.data("ui-selectmenu-item"),t)},focus:function(t,i){var s=i.item.data("ui-selectmenu-item");null!=e.focusIndex&&s.index!==e.focusIndex&&(e._trigger("focus",t,{item:s}),e.isOpen||e._select(s,t)),e.focusIndex=s.index,e.button.attr("aria-activedescendant",e.menuItems.eq(s.index).attr("id"))}}).menu("instance"),this.menuInstance._off(this.menu,"mouseleave"),this.menuInstance._closeOnDocumentClick=function(){return!1},this.menuInstance._isDivider=function(){return!1}},refresh:function(){this._refreshMenu(),this.buttonItem.replaceWith(this.buttonItem=this._renderButtonItem(this._getSelectedItem().data("ui-selectmenu-item")||{})),null===this.options.width&&this._resizeButton()},_refreshMenu:function(){var t,e=this.element.find("option");this.menu.empty(),this._parseOptions(e),this._renderMenu(this.menu,this.items),this.menuInstance.refresh(),this.menuItems=this.menu.find("li").not(".ui-selectmenu-optgroup").find(".ui-menu-item-wrapper"),this._rendered=!0,e.length&&(t=this._getSelectedItem(),this.menuInstance.focus(null,t),this._setAria(t.data("ui-selectmenu-item")),this._setOption("disabled",this.element.prop("disabled")))},open:function(t){this.options.disabled||(this._rendered?(this._removeClass(this.menu.find(".ui-state-active"),null,"ui-state-active"),this.menuInstance.focus(null,this._getSelectedItem())):this._refreshMenu(),this.menuItems.length&&(this.isOpen=!0,this._toggleAttr(),this._resizeMenu(),this._position(),this._on(this.document,this._documentClick),this._trigger("open",t)))},_position:function(){this.menuWrap.position(t.extend({of:this.button},this.options.position))},close:function(t){this.isOpen&&(this.isOpen=!1,this._toggleAttr(),this.range=null,this._off(this.document),this._trigger("close",t))},widget:function(){return this.button},menuWidget:function(){return this.menu},_renderButtonItem:function(e){var i=t("<span>");return this._setText(i,e.label),this._addClass(i,"ui-selectmenu-text"),i},_renderMenu:function(e,i){var s=this,n="";t.each(i,function(i,o){var a;o.optgroup!==n&&(a=t("<li>",{text:o.optgroup}),s._addClass(a,"ui-selectmenu-optgroup","ui-menu-divider"+(o.element.parent("optgroup").prop("disabled")?" ui-state-disabled":"")),a.appendTo(e),n=o.optgroup),s._renderItemData(e,o)})},_renderItemData:function(t,e){return this._renderItem(t,e).data("ui-selectmenu-item",e)},_renderItem:function(e,i){var s=t("<li>"),n=t("<div>",{title:i.element.attr("title")});return i.disabled&&this._addClass(s,null,"ui-state-disabled"),this._setText(n,i.label),s.append(n).appendTo(e)},_setText:function(t,e){e?t.text(e):t.html("&#160;")},_move:function(t,e){var i,s,n=".ui-menu-item";this.isOpen?i=this.menuItems.eq(this.focusIndex).parent("li"):(i=this.menuItems.eq(this.element[0].selectedIndex).parent("li"),n+=":not(.ui-state-disabled)"),s="first"===t||"last"===t?i["first"===t?"prevAll":"nextAll"](n).eq(-1):i[t+"All"](n).eq(0),s.length&&this.menuInstance.focus(e,s)},_getSelectedItem:function(){return this.menuItems.eq(this.element[0].selectedIndex).parent("li")},_toggle:function(t){this[this.isOpen?"close":"open"](t)},_setSelection:function(){var t;this.range&&(window.getSelection?(t=window.getSelection(),t.removeAllRanges(),t.addRange(this.range)):this.range.select(),this.button.focus())},_documentClick:{mousedown:function(e){this.isOpen&&(t(e.target).closest(".ui-selectmenu-menu, #"+t.ui.escapeSelector(this.ids.button)).length||this.close(e))}},_buttonEvents:{mousedown:function(){var t;window.getSelection?(t=window.getSelection(),t.rangeCount&&(this.range=t.getRangeAt(0))):this.range=document.selection.createRange()},click:function(t){this._setSelection(),this._toggle(t)},keydown:function(e){var i=!0;switch(e.keyCode){case t.ui.keyCode.TAB:case t.ui.keyCode.ESCAPE:this.close(e),i=!1;break;case t.ui.keyCode.ENTER:this.isOpen&&this._selectFocusedItem(e);break;case t.ui.keyCode.UP:e.altKey?this._toggle(e):this._move("prev",e);break;case t.ui.keyCode.DOWN:e.altKey?this._toggle(e):this._move("next",e);break;case t.ui.keyCode.SPACE:this.isOpen?this._selectFocusedItem(e):this._toggle(e);break;case t.ui.keyCode.LEFT:this._move("prev",e);break;case t.ui.keyCode.RIGHT:this._move("next",e);break;case t.ui.keyCode.HOME:case t.ui.keyCode.PAGE_UP:this._move("first",e);break;case t.ui.keyCode.END:case t.ui.keyCode.PAGE_DOWN:this._move("last",e);break;default:this.menu.trigger(e),i=!1}i&&e.preventDefault()}},_selectFocusedItem:function(t){var e=this.menuItems.eq(this.focusIndex).parent("li");e.hasClass("ui-state-disabled")||this._select(e.data("ui-selectmenu-item"),t)},_select:function(t,e){var i=this.element[0].selectedIndex;this.element[0].selectedIndex=t.index,this.buttonItem.replaceWith(this.buttonItem=this._renderButtonItem(t)),this._setAria(t),this._trigger("select",e,{item:t}),t.index!==i&&this._trigger("change",e,{item:t}),this.close(e)},_setAria:function(t){var e=this.menuItems.eq(t.index).attr("id");this.button.attr({"aria-labelledby":e,"aria-activedescendant":e}),this.menu.attr("aria-activedescendant",e)},_setOption:function(t,e){if("icons"===t){var i=this.button.find("span.ui-icon");this._removeClass(i,null,this.options.icons.button)._addClass(i,null,e.button)}this._super(t,e),"appendTo"===t&&this.menuWrap.appendTo(this._appendTo()),"width"===t&&this._resizeButton()},_setOptionDisabled:function(t){this._super(t),this.menuInstance.option("disabled",t),this.button.attr("aria-disabled",t),this._toggleClass(this.button,null,"ui-state-disabled",t),this.element.prop("disabled",t),t?(this.button.attr("tabindex",-1),this.close()):this.button.attr("tabindex",0)},_appendTo:function(){var e=this.options.appendTo;return e&&(e=e.jquery||e.nodeType?t(e):this.document.find(e).eq(0)),e&&e[0]||(e=this.element.closest(".ui-front, dialog")),e.length||(e=this.document[0].body),e},_toggleAttr:function(){this.button.attr("aria-expanded",this.isOpen),this._removeClass(this.button,"ui-selectmenu-button-"+(this.isOpen?"closed":"open"))._addClass(this.button,"ui-selectmenu-button-"+(this.isOpen?"open":"closed"))._toggleClass(this.menuWrap,"ui-selectmenu-open",null,this.isOpen),this.menu.attr("aria-hidden",!this.isOpen)},_resizeButton:function(){var t=this.options.width;return t===!1?(this.button.css("width",""),void 0):(null===t&&(t=this.element.show().outerWidth(),this.element.hide()),this.button.outerWidth(t),void 0)},_resizeMenu:function(){this.menu.outerWidth(Math.max(this.button.outerWidth(),this.menu.width("").outerWidth()+1))},_getCreateOptions:function(){var t=this._super();return t.disabled=this.element.prop("disabled"),t},_parseOptions:function(e){var i=this,s=[];e.each(function(e,n){s.push(i._parseOption(t(n),e))}),this.items=s},_parseOption:function(t,e){var i=t.parent("optgroup");return{element:t,index:e,value:t.val(),label:t.text(),optgroup:i.attr("label")||"",disabled:i.prop("disabled")||t.prop("disabled")}},_destroy:function(){this._unbindFormResetHandler(),this.menuWrap.remove(),this.button.remove(),this.element.show(),this.element.removeUniqueId(),this.labels.attr("for",this.ids.element)}}]),t.widget("ui.slider",t.ui.mouse,{version:"1.12.1",widgetEventPrefix:"slide",options:{animate:!1,classes:{"ui-slider":"ui-corner-all","ui-slider-handle":"ui-corner-all","ui-slider-range":"ui-corner-all ui-widget-header"},distance:0,max:100,min:0,orientation:"horizontal",range:!1,step:1,value:0,values:null,change:null,slide:null,start:null,stop:null},numPages:5,_create:function(){this._keySliding=!1,this._mouseSliding=!1,this._animateOff=!0,this._handleIndex=null,this._detectOrientation(),this._mouseInit(),this._calculateNewMax(),this._addClass("ui-slider ui-slider-"+this.orientation,"ui-widget ui-widget-content"),this._refresh(),this._animateOff=!1
1232},_refresh:function(){this._createRange(),this._createHandles(),this._setupEvents(),this._refreshValue()},_createHandles:function(){var e,i,s=this.options,n=this.element.find(".ui-slider-handle"),o="<span tabindex='0'></span>",a=[];for(i=s.values&&s.values.length||1,n.length>i&&(n.slice(i).remove(),n=n.slice(0,i)),e=n.length;i>e;e++)a.push(o);this.handles=n.add(t(a.join("")).appendTo(this.element)),this._addClass(this.handles,"ui-slider-handle","ui-state-default"),this.handle=this.handles.eq(0),this.handles.each(function(e){t(this).data("ui-slider-handle-index",e).attr("tabIndex",0)})},_createRange:function(){var e=this.options;e.range?(e.range===!0&&(e.values?e.values.length&&2!==e.values.length?e.values=[e.values[0],e.values[0]]:t.isArray(e.values)&&(e.values=e.values.slice(0)):e.values=[this._valueMin(),this._valueMin()]),this.range&&this.range.length?(this._removeClass(this.range,"ui-slider-range-min ui-slider-range-max"),this.range.css({left:"",bottom:""})):(this.range=t("<div>").appendTo(this.element),this._addClass(this.range,"ui-slider-range")),("min"===e.range||"max"===e.range)&&this._addClass(this.range,"ui-slider-range-"+e.range)):(this.range&&this.range.remove(),this.range=null)},_setupEvents:function(){this._off(this.handles),this._on(this.handles,this._handleEvents),this._hoverable(this.handles),this._focusable(this.handles)},_destroy:function(){this.handles.remove(),this.range&&this.range.remove(),this._mouseDestroy()},_mouseCapture:function(e){var i,s,n,o,a,r,h,l,c=this,u=this.options;return u.disabled?!1:(this.elementSize={width:this.element.outerWidth(),height:this.element.outerHeight()},this.elementOffset=this.element.offset(),i={x:e.pageX,y:e.pageY},s=this._normValueFromMouse(i),n=this._valueMax()-this._valueMin()+1,this.handles.each(function(e){var i=Math.abs(s-c.values(e));(n>i||n===i&&(e===c._lastChangedValue||c.values(e)===u.min))&&(n=i,o=t(this),a=e)}),r=this._start(e,a),r===!1?!1:(this._mouseSliding=!0,this._handleIndex=a,this._addClass(o,null,"ui-state-active"),o.trigger("focus"),h=o.offset(),l=!t(e.target).parents().addBack().is(".ui-slider-handle"),this._clickOffset=l?{left:0,top:0}:{left:e.pageX-h.left-o.width()/2,top:e.pageY-h.top-o.height()/2-(parseInt(o.css("borderTopWidth"),10)||0)-(parseInt(o.css("borderBottomWidth"),10)||0)+(parseInt(o.css("marginTop"),10)||0)},this.handles.hasClass("ui-state-hover")||this._slide(e,a,s),this._animateOff=!0,!0))},_mouseStart:function(){return!0},_mouseDrag:function(t){var e={x:t.pageX,y:t.pageY},i=this._normValueFromMouse(e);return this._slide(t,this._handleIndex,i),!1},_mouseStop:function(t){return this._removeClass(this.handles,null,"ui-state-active"),this._mouseSliding=!1,this._stop(t,this._handleIndex),this._change(t,this._handleIndex),this._handleIndex=null,this._clickOffset=null,this._animateOff=!1,!1},_detectOrientation:function(){this.orientation="vertical"===this.options.orientation?"vertical":"horizontal"},_normValueFromMouse:function(t){var e,i,s,n,o;return"horizontal"===this.orientation?(e=this.elementSize.width,i=t.x-this.elementOffset.left-(this._clickOffset?this._clickOffset.left:0)):(e=this.elementSize.height,i=t.y-this.elementOffset.top-(this._clickOffset?this._clickOffset.top:0)),s=i/e,s>1&&(s=1),0>s&&(s=0),"vertical"===this.orientation&&(s=1-s),n=this._valueMax()-this._valueMin(),o=this._valueMin()+s*n,this._trimAlignValue(o)},_uiHash:function(t,e,i){var s={handle:this.handles[t],handleIndex:t,value:void 0!==e?e:this.value()};return this._hasMultipleValues()&&(s.value=void 0!==e?e:this.values(t),s.values=i||this.values()),s},_hasMultipleValues:function(){return this.options.values&&this.options.values.length},_start:function(t,e){return this._trigger("start",t,this._uiHash(e))},_slide:function(t,e,i){var s,n,o=this.value(),a=this.values();this._hasMultipleValues()&&(n=this.values(e?0:1),o=this.values(e),2===this.options.values.length&&this.options.range===!0&&(i=0===e?Math.min(n,i):Math.max(n,i)),a[e]=i),i!==o&&(s=this._trigger("slide",t,this._uiHash(e,i,a)),s!==!1&&(this._hasMultipleValues()?this.values(e,i):this.value(i)))},_stop:function(t,e){this._trigger("stop",t,this._uiHash(e))},_change:function(t,e){this._keySliding||this._mouseSliding||(this._lastChangedValue=e,this._trigger("change",t,this._uiHash(e)))},value:function(t){return arguments.length?(this.options.value=this._trimAlignValue(t),this._refreshValue(),this._change(null,0),void 0):this._value()},values:function(e,i){var s,n,o;if(arguments.length>1)return this.options.values[e]=this._trimAlignValue(i),this._refreshValue(),this._change(null,e),void 0;if(!arguments.length)return this._values();if(!t.isArray(arguments[0]))return this._hasMultipleValues()?this._values(e):this.value();for(s=this.options.values,n=arguments[0],o=0;s.length>o;o+=1)s[o]=this._trimAlignValue(n[o]),this._change(null,o);this._refreshValue()},_setOption:function(e,i){var s,n=0;switch("range"===e&&this.options.range===!0&&("min"===i?(this.options.value=this._values(0),this.options.values=null):"max"===i&&(this.options.value=this._values(this.options.values.length-1),this.options.values=null)),t.isArray(this.options.values)&&(n=this.options.values.length),this._super(e,i),e){case"orientation":this._detectOrientation(),this._removeClass("ui-slider-horizontal ui-slider-vertical")._addClass("ui-slider-"+this.orientation),this._refreshValue(),this.options.range&&this._refreshRange(i),this.handles.css("horizontal"===i?"bottom":"left","");break;case"value":this._animateOff=!0,this._refreshValue(),this._change(null,0),this._animateOff=!1;break;case"values":for(this._animateOff=!0,this._refreshValue(),s=n-1;s>=0;s--)this._change(null,s);this._animateOff=!1;break;case"step":case"min":case"max":this._animateOff=!0,this._calculateNewMax(),this._refreshValue(),this._animateOff=!1;break;case"range":this._animateOff=!0,this._refresh(),this._animateOff=!1}},_setOptionDisabled:function(t){this._super(t),this._toggleClass(null,"ui-state-disabled",!!t)},_value:function(){var t=this.options.value;return t=this._trimAlignValue(t)},_values:function(t){var e,i,s;if(arguments.length)return e=this.options.values[t],e=this._trimAlignValue(e);if(this._hasMultipleValues()){for(i=this.options.values.slice(),s=0;i.length>s;s+=1)i[s]=this._trimAlignValue(i[s]);return i}return[]},_trimAlignValue:function(t){if(this._valueMin()>=t)return this._valueMin();if(t>=this._valueMax())return this._valueMax();var e=this.options.step>0?this.options.step:1,i=(t-this._valueMin())%e,s=t-i;return 2*Math.abs(i)>=e&&(s+=i>0?e:-e),parseFloat(s.toFixed(5))},_calculateNewMax:function(){var t=this.options.max,e=this._valueMin(),i=this.options.step,s=Math.round((t-e)/i)*i;t=s+e,t>this.options.max&&(t-=i),this.max=parseFloat(t.toFixed(this._precision()))},_precision:function(){var t=this._precisionOf(this.options.step);return null!==this.options.min&&(t=Math.max(t,this._precisionOf(this.options.min))),t},_precisionOf:function(t){var e=""+t,i=e.indexOf(".");return-1===i?0:e.length-i-1},_valueMin:function(){return this.options.min},_valueMax:function(){return this.max},_refreshRange:function(t){"vertical"===t&&this.range.css({width:"",left:""}),"horizontal"===t&&this.range.css({height:"",bottom:""})},_refreshValue:function(){var e,i,s,n,o,a=this.options.range,r=this.options,h=this,l=this._animateOff?!1:r.animate,c={};this._hasMultipleValues()?this.handles.each(function(s){i=100*((h.values(s)-h._valueMin())/(h._valueMax()-h._valueMin())),c["horizontal"===h.orientation?"left":"bottom"]=i+"%",t(this).stop(1,1)[l?"animate":"css"](c,r.animate),h.options.range===!0&&("horizontal"===h.orientation?(0===s&&h.range.stop(1,1)[l?"animate":"css"]({left:i+"%"},r.animate),1===s&&h.range[l?"animate":"css"]({width:i-e+"%"},{queue:!1,duration:r.animate})):(0===s&&h.range.stop(1,1)[l?"animate":"css"]({bottom:i+"%"},r.animate),1===s&&h.range[l?"animate":"css"]({height:i-e+"%"},{queue:!1,duration:r.animate}))),e=i}):(s=this.value(),n=this._valueMin(),o=this._valueMax(),i=o!==n?100*((s-n)/(o-n)):0,c["horizontal"===this.orientation?"left":"bottom"]=i+"%",this.handle.stop(1,1)[l?"animate":"css"](c,r.animate),"min"===a&&"horizontal"===this.orientation&&this.range.stop(1,1)[l?"animate":"css"]({width:i+"%"},r.animate),"max"===a&&"horizontal"===this.orientation&&this.range.stop(1,1)[l?"animate":"css"]({width:100-i+"%"},r.animate),"min"===a&&"vertical"===this.orientation&&this.range.stop(1,1)[l?"animate":"css"]({height:i+"%"},r.animate),"max"===a&&"vertical"===this.orientation&&this.range.stop(1,1)[l?"animate":"css"]({height:100-i+"%"},r.animate))},_handleEvents:{keydown:function(e){var i,s,n,o,a=t(e.target).data("ui-slider-handle-index");switch(e.keyCode){case t.ui.keyCode.HOME:case t.ui.keyCode.END:case t.ui.keyCode.PAGE_UP:case t.ui.keyCode.PAGE_DOWN:case t.ui.keyCode.UP:case t.ui.keyCode.RIGHT:case t.ui.keyCode.DOWN:case t.ui.keyCode.LEFT:if(e.preventDefault(),!this._keySliding&&(this._keySliding=!0,this._addClass(t(e.target),null,"ui-state-active"),i=this._start(e,a),i===!1))return}switch(o=this.options.step,s=n=this._hasMultipleValues()?this.values(a):this.value(),e.keyCode){case t.ui.keyCode.HOME:n=this._valueMin();break;case t.ui.keyCode.END:n=this._valueMax();break;case t.ui.keyCode.PAGE_UP:n=this._trimAlignValue(s+(this._valueMax()-this._valueMin())/this.numPages);break;case t.ui.keyCode.PAGE_DOWN:n=this._trimAlignValue(s-(this._valueMax()-this._valueMin())/this.numPages);break;case t.ui.keyCode.UP:case t.ui.keyCode.RIGHT:if(s===this._valueMax())return;n=this._trimAlignValue(s+o);break;case t.ui.keyCode.DOWN:case t.ui.keyCode.LEFT:if(s===this._valueMin())return;n=this._trimAlignValue(s-o)}this._slide(e,a,n)},keyup:function(e){var i=t(e.target).data("ui-slider-handle-index");this._keySliding&&(this._keySliding=!1,this._stop(e,i),this._change(e,i),this._removeClass(t(e.target),null,"ui-state-active"))}}}),t.widget("ui.sortable",t.ui.mouse,{version:"1.12.1",widgetEventPrefix:"sort",ready:!1,options:{appendTo:"parent",axis:!1,connectWith:!1,containment:!1,cursor:"auto",cursorAt:!1,dropOnEmpty:!0,forcePlaceholderSize:!1,forceHelperSize:!1,grid:!1,handle:!1,helper:"original",items:"> *",opacity:!1,placeholder:!1,revert:!1,scroll:!0,scrollSensitivity:20,scrollSpeed:20,scope:"default",tolerance:"intersect",zIndex:1e3,activate:null,beforeStop:null,change:null,deactivate:null,out:null,over:null,receive:null,remove:null,sort:null,start:null,stop:null,update:null},_isOverAxis:function(t,e,i){return t>=e&&e+i>t},_isFloating:function(t){return/left|right/.test(t.css("float"))||/inline|table-cell/.test(t.css("display"))},_create:function(){this.containerCache={},this._addClass("ui-sortable"),this.refresh(),this.offset=this.element.offset(),this._mouseInit(),this._setHandleClassName(),this.ready=!0},_setOption:function(t,e){this._super(t,e),"handle"===t&&this._setHandleClassName()},_setHandleClassName:function(){var e=this;this._removeClass(this.element.find(".ui-sortable-handle"),"ui-sortable-handle"),t.each(this.items,function(){e._addClass(this.instance.options.handle?this.item.find(this.instance.options.handle):this.item,"ui-sortable-handle")})},_destroy:function(){this._mouseDestroy();for(var t=this.items.length-1;t>=0;t--)this.items[t].item.removeData(this.widgetName+"-item");return this},_mouseCapture:function(e,i){var s=null,n=!1,o=this;return this.reverting?!1:this.options.disabled||"static"===this.options.type?!1:(this._refreshItems(e),t(e.target).parents().each(function(){return t.data(this,o.widgetName+"-item")===o?(s=t(this),!1):void 0}),t.data(e.target,o.widgetName+"-item")===o&&(s=t(e.target)),s?!this.options.handle||i||(t(this.options.handle,s).find("*").addBack().each(function(){this===e.target&&(n=!0)}),n)?(this.currentItem=s,this._removeCurrentsFromItems(),!0):!1:!1)},_mouseStart:function(e,i,s){var n,o,a=this.options;if(this.currentContainer=this,this.refreshPositions(),this.helper=this._createHelper(e),this._cacheHelperProportions(),this._cacheMargins(),this.scrollParent=this.helper.scrollParent(),this.offset=this.currentItem.offset(),this.offset={top:this.offset.top-this.margins.top,left:this.offset.left-this.margins.left},t.extend(this.offset,{click:{left:e.pageX-this.offset.left,top:e.pageY-this.offset.top},parent:this._getParentOffset(),relative:this._getRelativeOffset()}),this.helper.css("position","absolute"),this.cssPosition=this.helper.css("position"),this.originalPosition=this._generatePosition(e),this.originalPageX=e.pageX,this.originalPageY=e.pageY,a.cursorAt&&this._adjustOffsetFromHelper(a.cursorAt),this.domPosition={prev:this.currentItem.prev()[0],parent:this.currentItem.parent()[0]},this.helper[0]!==this.currentItem[0]&&this.currentItem.hide(),this._createPlaceholder(),a.containment&&this._setContainment(),a.cursor&&"auto"!==a.cursor&&(o=this.document.find("body"),this.storedCursor=o.css("cursor"),o.css("cursor",a.cursor),this.storedStylesheet=t("<style>*{ cursor: "+a.cursor+" !important; }</style>").appendTo(o)),a.opacity&&(this.helper.css("opacity")&&(this._storedOpacity=this.helper.css("opacity")),this.helper.css("opacity",a.opacity)),a.zIndex&&(this.helper.css("zIndex")&&(this._storedZIndex=this.helper.css("zIndex")),this.helper.css("zIndex",a.zIndex)),this.scrollParent[0]!==this.document[0]&&"HTML"!==this.scrollParent[0].tagName&&(this.overflowOffset=this.scrollParent.offset()),this._trigger("start",e,this._uiHash()),this._preserveHelperProportions||this._cacheHelperProportions(),!s)for(n=this.containers.length-1;n>=0;n--)this.containers[n]._trigger("activate",e,this._uiHash(this));return t.ui.ddmanager&&(t.ui.ddmanager.current=this),t.ui.ddmanager&&!a.dropBehaviour&&t.ui.ddmanager.prepareOffsets(this,e),this.dragging=!0,this._addClass(this.helper,"ui-sortable-helper"),this._mouseDrag(e),!0},_mouseDrag:function(e){var i,s,n,o,a=this.options,r=!1;for(this.position=this._generatePosition(e),this.positionAbs=this._convertPositionTo("absolute"),this.lastPositionAbs||(this.lastPositionAbs=this.positionAbs),this.options.scroll&&(this.scrollParent[0]!==this.document[0]&&"HTML"!==this.scrollParent[0].tagName?(this.overflowOffset.top+this.scrollParent[0].offsetHeight-e.pageY<a.scrollSensitivity?this.scrollParent[0].scrollTop=r=this.scrollParent[0].scrollTop+a.scrollSpeed:e.pageY-this.overflowOffset.top<a.scrollSensitivity&&(this.scrollParent[0].scrollTop=r=this.scrollParent[0].scrollTop-a.scrollSpeed),this.overflowOffset.left+this.scrollParent[0].offsetWidth-e.pageX<a.scrollSensitivity?this.scrollParent[0].scrollLeft=r=this.scrollParent[0].scrollLeft+a.scrollSpeed:e.pageX-this.overflowOffset.left<a.scrollSensitivity&&(this.scrollParent[0].scrollLeft=r=this.scrollParent[0].scrollLeft-a.scrollSpeed)):(e.pageY-this.document.scrollTop()<a.scrollSensitivity?r=this.document.scrollTop(this.document.scrollTop()-a.scrollSpeed):this.window.height()-(e.pageY-this.document.scrollTop())<a.scrollSensitivity&&(r=this.document.scrollTop(this.document.scrollTop()+a.scrollSpeed)),e.pageX-this.document.scrollLeft()<a.scrollSensitivity?r=this.document.scrollLeft(this.document.scrollLeft()-a.scrollSpeed):this.window.width()-(e.pageX-this.document.scrollLeft())<a.scrollSensitivity&&(r=this.document.scrollLeft(this.document.scrollLeft()+a.scrollSpeed))),r!==!1&&t.ui.ddmanager&&!a.dropBehaviour&&t.ui.ddmanager.prepareOffsets(this,e)),this.positionAbs=this._convertPositionTo("absolute"),this.options.axis&&"y"===this.options.axis||(this.helper[0].style.left=this.position.left+"px"),this.options.axis&&"x"===this.options.axis||(this.helper[0].style.top=this.position.top+"px"),i=this.items.length-1;i>=0;i--)if(s=this.items[i],n=s.item[0],o=this._intersectsWithPointer(s),o&&s.instance===this.currentContainer&&n!==this.currentItem[0]&&this.placeholder[1===o?"next":"prev"]()[0]!==n&&!t.contains(this.placeholder[0],n)&&("semi-dynamic"===this.options.type?!t.contains(this.element[0],n):!0)){if(this.direction=1===o?"down":"up","pointer"!==this.options.tolerance&&!this._intersectsWithSides(s))break;this._rearrange(e,s),this._trigger("change",e,this._uiHash());break}return this._contactContainers(e),t.ui.ddmanager&&t.ui.ddmanager.drag(this,e),this._trigger("sort",e,this._uiHash()),this.lastPositionAbs=this.positionAbs,!1},_mouseStop:function(e,i){if(e){if(t.ui.ddmanager&&!this.options.dropBehaviour&&t.ui.ddmanager.drop(this,e),this.options.revert){var s=this,n=this.placeholder.offset(),o=this.options.axis,a={};o&&"x"!==o||(a.left=n.left-this.offset.parent.left-this.margins.left+(this.offsetParent[0]===this.document[0].body?0:this.offsetParent[0].scrollLeft)),o&&"y"!==o||(a.top=n.top-this.offset.parent.top-this.margins.top+(this.offsetParent[0]===this.document[0].body?0:this.offsetParent[0].scrollTop)),this.reverting=!0,t(this.helper).animate(a,parseInt(this.options.revert,10)||500,function(){s._clear(e)})}else this._clear(e,i);return!1}},cancel:function(){if(this.dragging){this._mouseUp(new t.Event("mouseup",{target:null})),"original"===this.options.helper?(this.currentItem.css(this._storedCSS),this._removeClass(this.currentItem,"ui-sortable-helper")):this.currentItem.show();for(var e=this.containers.length-1;e>=0;e--)this.containers[e]._trigger("deactivate",null,this._uiHash(this)),this.containers[e].containerCache.over&&(this.containers[e]._trigger("out",null,this._uiHash(this)),this.containers[e].containerCache.over=0)}return this.placeholder&&(this.placeholder[0].parentNode&&this.placeholder[0].parentNode.removeChild(this.placeholder[0]),"original"!==this.options.helper&&this.helper&&this.helper[0].parentNode&&this.helper.remove(),t.extend(this,{helper:null,dragging:!1,reverting:!1,_noFinalSort:null}),this.domPosition.prev?t(this.domPosition.prev).after(this.currentItem):t(this.domPosition.parent).prepend(this.currentItem)),this},serialize:function(e){var i=this._getItemsAsjQuery(e&&e.connected),s=[];return e=e||{},t(i).each(function(){var i=(t(e.item||this).attr(e.attribute||"id")||"").match(e.expression||/(.+)[\-=_](.+)/);i&&s.push((e.key||i[1]+"[]")+"="+(e.key&&e.expression?i[1]:i[2]))}),!s.length&&e.key&&s.push(e.key+"="),s.join("&")},toArray:function(e){var i=this._getItemsAsjQuery(e&&e.connected),s=[];return e=e||{},i.each(function(){s.push(t(e.item||this).attr(e.attribute||"id")||"")}),s},_intersectsWith:function(t){var e=this.positionAbs.left,i=e+this.helperProportions.width,s=this.positionAbs.top,n=s+this.helperProportions.height,o=t.left,a=o+t.width,r=t.top,h=r+t.height,l=this.offset.click.top,c=this.offset.click.left,u="x"===this.options.axis||s+l>r&&h>s+l,d="y"===this.options.axis||e+c>o&&a>e+c,p=u&&d;return"pointer"===this.options.tolerance||this.options.forcePointerForContainers||"pointer"!==this.options.tolerance&&this.helperProportions[this.floating?"width":"height"]>t[this.floating?"width":"height"]?p:e+this.helperProportions.width/2>o&&a>i-this.helperProportions.width/2&&s+this.helperProportions.height/2>r&&h>n-this.helperProportions.height/2},_intersectsWithPointer:function(t){var e,i,s="x"===this.options.axis||this._isOverAxis(this.positionAbs.top+this.offset.click.top,t.top,t.height),n="y"===this.options.axis||this._isOverAxis(this.positionAbs.left+this.offset.click.left,t.left,t.width),o=s&&n;return o?(e=this._getDragVerticalDirection(),i=this._getDragHorizontalDirection(),this.floating?"right"===i||"down"===e?2:1:e&&("down"===e?2:1)):!1},_intersectsWithSides:function(t){var e=this._isOverAxis(this.positionAbs.top+this.offset.click.top,t.top+t.height/2,t.height),i=this._isOverAxis(this.positionAbs.left+this.offset.click.left,t.left+t.width/2,t.width),s=this._getDragVerticalDirection(),n=this._getDragHorizontalDirection();return this.floating&&n?"right"===n&&i||"left"===n&&!i:s&&("down"===s&&e||"up"===s&&!e)},_getDragVerticalDirection:function(){var t=this.positionAbs.top-this.lastPositionAbs.top;return 0!==t&&(t>0?"down":"up")},_getDragHorizontalDirection:function(){var t=this.positionAbs.left-this.lastPositionAbs.left;return 0!==t&&(t>0?"right":"left")},refresh:function(t){return this._refreshItems(t),this._setHandleClassName(),this.refreshPositions(),this},_connectWith:function(){var t=this.options;return t.connectWith.constructor===String?[t.connectWith]:t.connectWith},_getItemsAsjQuery:function(e){function i(){r.push(this)}var s,n,o,a,r=[],h=[],l=this._connectWith();if(l&&e)for(s=l.length-1;s>=0;s--)for(o=t(l[s],this.document[0]),n=o.length-1;n>=0;n--)a=t.data(o[n],this.widgetFullName),a&&a!==this&&!a.options.disabled&&h.push([t.isFunction(a.options.items)?a.options.items.call(a.element):t(a.options.items,a.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"),a]);for(h.push([t.isFunction(this.options.items)?this.options.items.call(this.element,null,{options:this.options,item:this.currentItem}):t(this.options.items,this.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"),this]),s=h.length-1;s>=0;s--)h[s][0].each(i);return t(r)},_removeCurrentsFromItems:function(){var e=this.currentItem.find(":data("+this.widgetName+"-item)");this.items=t.grep(this.items,function(t){for(var i=0;e.length>i;i++)if(e[i]===t.item[0])return!1;return!0})},_refreshItems:function(e){this.items=[],this.containers=[this];var i,s,n,o,a,r,h,l,c=this.items,u=[[t.isFunction(this.options.items)?this.options.items.call(this.element[0],e,{item:this.currentItem}):t(this.options.items,this.element),this]],d=this._connectWith();if(d&&this.ready)for(i=d.length-1;i>=0;i--)for(n=t(d[i],this.document[0]),s=n.length-1;s>=0;s--)o=t.data(n[s],this.widgetFullName),o&&o!==this&&!o.options.disabled&&(u.push([t.isFunction(o.options.items)?o.options.items.call(o.element[0],e,{item:this.currentItem}):t(o.options.items,o.element),o]),this.containers.push(o));for(i=u.length-1;i>=0;i--)for(a=u[i][1],r=u[i][0],s=0,l=r.length;l>s;s++)h=t(r[s]),h.data(this.widgetName+"-item",a),c.push({item:h,instance:a,width:0,height:0,left:0,top:0})},refreshPositions:function(e){this.floating=this.items.length?"x"===this.options.axis||this._isFloating(this.items[0].item):!1,this.offsetParent&&this.helper&&(this.offset.parent=this._getParentOffset());var i,s,n,o;for(i=this.items.length-1;i>=0;i--)s=this.items[i],s.instance!==this.currentContainer&&this.currentContainer&&s.item[0]!==this.currentItem[0]||(n=this.options.toleranceElement?t(this.options.toleranceElement,s.item):s.item,e||(s.width=n.outerWidth(),s.height=n.outerHeight()),o=n.offset(),s.left=o.left,s.top=o.top);if(this.options.custom&&this.options.custom.refreshContainers)this.options.custom.refreshContainers.call(this);else for(i=this.containers.length-1;i>=0;i--)o=this.containers[i].element.offset(),this.containers[i].containerCache.left=o.left,this.containers[i].containerCache.top=o.top,this.containers[i].containerCache.width=this.containers[i].element.outerWidth(),this.containers[i].containerCache.height=this.containers[i].element.outerHeight();return this},_createPlaceholder:function(e){e=e||this;var i,s=e.options;s.placeholder&&s.placeholder.constructor!==String||(i=s.placeholder,s.placeholder={element:function(){var s=e.currentItem[0].nodeName.toLowerCase(),n=t("<"+s+">",e.document[0]);return e._addClass(n,"ui-sortable-placeholder",i||e.currentItem[0].className)._removeClass(n,"ui-sortable-helper"),"tbody"===s?e._createTrPlaceholder(e.currentItem.find("tr").eq(0),t("<tr>",e.document[0]).appendTo(n)):"tr"===s?e._createTrPlaceholder(e.currentItem,n):"img"===s&&n.attr("src",e.currentItem.attr("src")),i||n.css("visibility","hidden"),n},update:function(t,n){(!i||s.forcePlaceholderSize)&&(n.height()||n.height(e.currentItem.innerHeight()-parseInt(e.currentItem.css("paddingTop")||0,10)-parseInt(e.currentItem.css("paddingBottom")||0,10)),n.width()||n.width(e.currentItem.innerWidth()-parseInt(e.currentItem.css("paddingLeft")||0,10)-parseInt(e.currentItem.css("paddingRight")||0,10)))}}),e.placeholder=t(s.placeholder.element.call(e.element,e.currentItem)),e.currentItem.after(e.placeholder),s.placeholder.update(e,e.placeholder)},_createTrPlaceholder:function(e,i){var s=this;e.children().each(function(){t("<td>&#160;</td>",s.document[0]).attr("colspan",t(this).attr("colspan")||1).appendTo(i)})},_contactContainers:function(e){var i,s,n,o,a,r,h,l,c,u,d=null,p=null;for(i=this.containers.length-1;i>=0;i--)if(!t.contains(this.currentItem[0],this.containers[i].element[0]))if(this._intersectsWith(this.containers[i].containerCache)){if(d&&t.contains(this.containers[i].element[0],d.element[0]))continue;d=this.containers[i],p=i}else this.containers[i].containerCache.over&&(this.containers[i]._trigger("out",e,this._uiHash(this)),this.containers[i].containerCache.over=0);if(d)if(1===this.containers.length)this.containers[p].containerCache.over||(this.containers[p]._trigger("over",e,this._uiHash(this)),this.containers[p].containerCache.over=1);else{for(n=1e4,o=null,c=d.floating||this._isFloating(this.currentItem),a=c?"left":"top",r=c?"width":"height",u=c?"pageX":"pageY",s=this.items.length-1;s>=0;s--)t.contains(this.containers[p].element[0],this.items[s].item[0])&&this.items[s].item[0]!==this.currentItem[0]&&(h=this.items[s].item.offset()[a],l=!1,e[u]-h>this.items[s][r]/2&&(l=!0),n>Math.abs(e[u]-h)&&(n=Math.abs(e[u]-h),o=this.items[s],this.direction=l?"up":"down"));if(!o&&!this.options.dropOnEmpty)return;if(this.currentContainer===this.containers[p])return this.currentContainer.containerCache.over||(this.containers[p]._trigger("over",e,this._uiHash()),this.currentContainer.containerCache.over=1),void 0;o?this._rearrange(e,o,null,!0):this._rearrange(e,null,this.containers[p].element,!0),this._trigger("change",e,this._uiHash()),this.containers[p]._trigger("change",e,this._uiHash(this)),this.currentContainer=this.containers[p],this.options.placeholder.update(this.currentContainer,this.placeholder),this.containers[p]._trigger("over",e,this._uiHash(this)),this.containers[p].containerCache.over=1}},_createHelper:function(e){var i=this.options,s=t.isFunction(i.helper)?t(i.helper.apply(this.element[0],[e,this.currentItem])):"clone"===i.helper?this.currentItem.clone():this.currentItem;return s.parents("body").length||t("parent"!==i.appendTo?i.appendTo:this.currentItem[0].parentNode)[0].appendChild(s[0]),s[0]===this.currentItem[0]&&(this._storedCSS={width:this.currentItem[0].style.width,height:this.currentItem[0].style.height,position:this.currentItem.css("position"),top:this.currentItem.css("top"),left:this.currentItem.css("left")}),(!s[0].style.width||i.forceHelperSize)&&s.width(this.currentItem.width()),(!s[0].style.height||i.forceHelperSize)&&s.height(this.currentItem.height()),s},_adjustOffsetFromHelper:function(e){"string"==typeof e&&(e=e.split(" ")),t.isArray(e)&&(e={left:+e[0],top:+e[1]||0}),"left"in e&&(this.offset.click.left=e.left+this.margins.left),"right"in e&&(this.offset.click.left=this.helperProportions.width-e.right+this.margins.left),"top"in e&&(this.offset.click.top=e.top+this.margins.top),"bottom"in e&&(this.offset.click.top=this.helperProportions.height-e.bottom+this.margins.top)},_getParentOffset:function(){this.offsetParent=this.helper.offsetParent();var e=this.offsetParent.offset();return"absolute"===this.cssPosition&&this.scrollParent[0]!==this.document[0]&&t.contains(this.scrollParent[0],this.offsetParent[0])&&(e.left+=this.scrollParent.scrollLeft(),e.top+=this.scrollParent.scrollTop()),(this.offsetParent[0]===this.document[0].body||this.offsetParent[0].tagName&&"html"===this.offsetParent[0].tagName.toLowerCase()&&t.ui.ie)&&(e={top:0,left:0}),{top:e.top+(parseInt(this.offsetParent.css("borderTopWidth"),10)||0),left:e.left+(parseInt(this.offsetParent.css("borderLeftWidth"),10)||0)}},_getRelativeOffset:function(){if("relative"===this.cssPosition){var t=this.currentItem.position();return{top:t.top-(parseInt(this.helper.css("top"),10)||0)+this.scrollParent.scrollTop(),left:t.left-(parseInt(this.helper.css("left"),10)||0)+this.scrollParent.scrollLeft()}}return{top:0,left:0}},_cacheMargins:function(){this.margins={left:parseInt(this.currentItem.css("marginLeft"),10)||0,top:parseInt(this.currentItem.css("marginTop"),10)||0}},_cacheHelperProportions:function(){this.helperProportions={width:this.helper.outerWidth(),height:this.helper.outerHeight()}},_setContainment:function(){var e,i,s,n=this.options;"parent"===n.containment&&(n.containment=this.helper[0].parentNode),("document"===n.containment||"window"===n.containment)&&(this.containment=[0-this.offset.relative.left-this.offset.parent.left,0-this.offset.relative.top-this.offset.parent.top,"document"===n.containment?this.document.width():this.window.width()-this.helperProportions.width-this.margins.left,("document"===n.containment?this.document.height()||document.body.parentNode.scrollHeight:this.window.height()||this.document[0].body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top]),/^(document|window|parent)$/.test(n.containment)||(e=t(n.containment)[0],i=t(n.containment).offset(),s="hidden"!==t(e).css("overflow"),this.containment=[i.left+(parseInt(t(e).css("borderLeftWidth"),10)||0)+(parseInt(t(e).css("paddingLeft"),10)||0)-this.margins.left,i.top+(parseInt(t(e).css("borderTopWidth"),10)||0)+(parseInt(t(e).css("paddingTop"),10)||0)-this.margins.top,i.left+(s?Math.max(e.scrollWidth,e.offsetWidth):e.offsetWidth)-(parseInt(t(e).css("borderLeftWidth"),10)||0)-(parseInt(t(e).css("paddingRight"),10)||0)-this.helperProportions.width-this.margins.left,i.top+(s?Math.max(e.scrollHeight,e.offsetHeight):e.offsetHeight)-(parseInt(t(e).css("borderTopWidth"),10)||0)-(parseInt(t(e).css("paddingBottom"),10)||0)-this.helperProportions.height-this.margins.top])},_convertPositionTo:function(e,i){i||(i=this.position);var s="absolute"===e?1:-1,n="absolute"!==this.cssPosition||this.scrollParent[0]!==this.document[0]&&t.contains(this.scrollParent[0],this.offsetParent[0])?this.scrollParent:this.offsetParent,o=/(html|body)/i.test(n[0].tagName);return{top:i.top+this.offset.relative.top*s+this.offset.parent.top*s-("fixed"===this.cssPosition?-this.scrollParent.scrollTop():o?0:n.scrollTop())*s,left:i.left+this.offset.relative.left*s+this.offset.parent.left*s-("fixed"===this.cssPosition?-this.scrollParent.scrollLeft():o?0:n.scrollLeft())*s}},_generatePosition:function(e){var i,s,n=this.options,o=e.pageX,a=e.pageY,r="absolute"!==this.cssPosition||this.scrollParent[0]!==this.document[0]&&t.contains(this.scrollParent[0],this.offsetParent[0])?this.scrollParent:this.offsetParent,h=/(html|body)/i.test(r[0].tagName);return"relative"!==this.cssPosition||this.scrollParent[0]!==this.document[0]&&this.scrollParent[0]!==this.offsetParent[0]||(this.offset.relative=this._getRelativeOffset()),this.originalPosition&&(this.containment&&(e.pageX-this.offset.click.left<this.containment[0]&&(o=this.containment[0]+this.offset.click.left),e.pageY-this.offset.click.top<this.containment[1]&&(a=this.containment[1]+this.offset.click.top),e.pageX-this.offset.click.left>this.containment[2]&&(o=this.containment[2]+this.offset.click.left),e.pageY-this.offset.click.top>this.containment[3]&&(a=this.containment[3]+this.offset.click.top)),n.grid&&(i=this.originalPageY+Math.round((a-this.originalPageY)/n.grid[1])*n.grid[1],a=this.containment?i-this.offset.click.top>=this.containment[1]&&i-this.offset.click.top<=this.containment[3]?i:i-this.offset.click.top>=this.containment[1]?i-n.grid[1]:i+n.grid[1]:i,s=this.originalPageX+Math.round((o-this.originalPageX)/n.grid[0])*n.grid[0],o=this.containment?s-this.offset.click.left>=this.containment[0]&&s-this.offset.click.left<=this.containment[2]?s:s-this.offset.click.left>=this.containment[0]?s-n.grid[0]:s+n.grid[0]:s)),{top:a-this.offset.click.top-this.offset.relative.top-this.offset.parent.top+("fixed"===this.cssPosition?-this.scrollParent.scrollTop():h?0:r.scrollTop()),left:o-this.offset.click.left-this.offset.relative.left-this.offset.parent.left+("fixed"===this.cssPosition?-this.scrollParent.scrollLeft():h?0:r.scrollLeft())}},_rearrange:function(t,e,i,s){i?i[0].appendChild(this.placeholder[0]):e.item[0].parentNode.insertBefore(this.placeholder[0],"down"===this.direction?e.item[0]:e.item[0].nextSibling),this.counter=this.counter?++this.counter:1;var n=this.counter;
1233this._delay(function(){n===this.counter&&this.refreshPositions(!s)})},_clear:function(t,e){function i(t,e,i){return function(s){i._trigger(t,s,e._uiHash(e))}}this.reverting=!1;var s,n=[];if(!this._noFinalSort&&this.currentItem.parent().length&&this.placeholder.before(this.currentItem),this._noFinalSort=null,this.helper[0]===this.currentItem[0]){for(s in this._storedCSS)("auto"===this._storedCSS[s]||"static"===this._storedCSS[s])&&(this._storedCSS[s]="");this.currentItem.css(this._storedCSS),this._removeClass(this.currentItem,"ui-sortable-helper")}else this.currentItem.show();for(this.fromOutside&&!e&&n.push(function(t){this._trigger("receive",t,this._uiHash(this.fromOutside))}),!this.fromOutside&&this.domPosition.prev===this.currentItem.prev().not(".ui-sortable-helper")[0]&&this.domPosition.parent===this.currentItem.parent()[0]||e||n.push(function(t){this._trigger("update",t,this._uiHash())}),this!==this.currentContainer&&(e||(n.push(function(t){this._trigger("remove",t,this._uiHash())}),n.push(function(t){return function(e){t._trigger("receive",e,this._uiHash(this))}}.call(this,this.currentContainer)),n.push(function(t){return function(e){t._trigger("update",e,this._uiHash(this))}}.call(this,this.currentContainer)))),s=this.containers.length-1;s>=0;s--)e||n.push(i("deactivate",this,this.containers[s])),this.containers[s].containerCache.over&&(n.push(i("out",this,this.containers[s])),this.containers[s].containerCache.over=0);if(this.storedCursor&&(this.document.find("body").css("cursor",this.storedCursor),this.storedStylesheet.remove()),this._storedOpacity&&this.helper.css("opacity",this._storedOpacity),this._storedZIndex&&this.helper.css("zIndex","auto"===this._storedZIndex?"":this._storedZIndex),this.dragging=!1,e||this._trigger("beforeStop",t,this._uiHash()),this.placeholder[0].parentNode.removeChild(this.placeholder[0]),this.cancelHelperRemoval||(this.helper[0]!==this.currentItem[0]&&this.helper.remove(),this.helper=null),!e){for(s=0;n.length>s;s++)n[s].call(this,t);this._trigger("stop",t,this._uiHash())}return this.fromOutside=!1,!this.cancelHelperRemoval},_trigger:function(){t.Widget.prototype._trigger.apply(this,arguments)===!1&&this.cancel()},_uiHash:function(e){var i=e||this;return{helper:i.helper,placeholder:i.placeholder||t([]),position:i.position,originalPosition:i.originalPosition,offset:i.positionAbs,item:i.currentItem,sender:e?e.element:null}}}),t.widget("ui.spinner",{version:"1.12.1",defaultElement:"<input>",widgetEventPrefix:"spin",options:{classes:{"ui-spinner":"ui-corner-all","ui-spinner-down":"ui-corner-br","ui-spinner-up":"ui-corner-tr"},culture:null,icons:{down:"ui-icon-triangle-1-s",up:"ui-icon-triangle-1-n"},incremental:!0,max:null,min:null,numberFormat:null,page:10,step:1,change:null,spin:null,start:null,stop:null},_create:function(){this._setOption("max",this.options.max),this._setOption("min",this.options.min),this._setOption("step",this.options.step),""!==this.value()&&this._value(this.element.val(),!0),this._draw(),this._on(this._events),this._refresh(),this._on(this.window,{beforeunload:function(){this.element.removeAttr("autocomplete")}})},_getCreateOptions:function(){var e=this._super(),i=this.element;return t.each(["min","max","step"],function(t,s){var n=i.attr(s);null!=n&&n.length&&(e[s]=n)}),e},_events:{keydown:function(t){this._start(t)&&this._keydown(t)&&t.preventDefault()},keyup:"_stop",focus:function(){this.previous=this.element.val()},blur:function(t){return this.cancelBlur?(delete this.cancelBlur,void 0):(this._stop(),this._refresh(),this.previous!==this.element.val()&&this._trigger("change",t),void 0)},mousewheel:function(t,e){if(e){if(!this.spinning&&!this._start(t))return!1;this._spin((e>0?1:-1)*this.options.step,t),clearTimeout(this.mousewheelTimer),this.mousewheelTimer=this._delay(function(){this.spinning&&this._stop(t)},100),t.preventDefault()}},"mousedown .ui-spinner-button":function(e){function i(){var e=this.element[0]===t.ui.safeActiveElement(this.document[0]);e||(this.element.trigger("focus"),this.previous=s,this._delay(function(){this.previous=s}))}var s;s=this.element[0]===t.ui.safeActiveElement(this.document[0])?this.previous:this.element.val(),e.preventDefault(),i.call(this),this.cancelBlur=!0,this._delay(function(){delete this.cancelBlur,i.call(this)}),this._start(e)!==!1&&this._repeat(null,t(e.currentTarget).hasClass("ui-spinner-up")?1:-1,e)},"mouseup .ui-spinner-button":"_stop","mouseenter .ui-spinner-button":function(e){return t(e.currentTarget).hasClass("ui-state-active")?this._start(e)===!1?!1:(this._repeat(null,t(e.currentTarget).hasClass("ui-spinner-up")?1:-1,e),void 0):void 0},"mouseleave .ui-spinner-button":"_stop"},_enhance:function(){this.uiSpinner=this.element.attr("autocomplete","off").wrap("<span>").parent().append("<a></a><a></a>")},_draw:function(){this._enhance(),this._addClass(this.uiSpinner,"ui-spinner","ui-widget ui-widget-content"),this._addClass("ui-spinner-input"),this.element.attr("role","spinbutton"),this.buttons=this.uiSpinner.children("a").attr("tabIndex",-1).attr("aria-hidden",!0).button({classes:{"ui-button":""}}),this._removeClass(this.buttons,"ui-corner-all"),this._addClass(this.buttons.first(),"ui-spinner-button ui-spinner-up"),this._addClass(this.buttons.last(),"ui-spinner-button ui-spinner-down"),this.buttons.first().button({icon:this.options.icons.up,showLabel:!1}),this.buttons.last().button({icon:this.options.icons.down,showLabel:!1}),this.buttons.height()>Math.ceil(.5*this.uiSpinner.height())&&this.uiSpinner.height()>0&&this.uiSpinner.height(this.uiSpinner.height())},_keydown:function(e){var i=this.options,s=t.ui.keyCode;switch(e.keyCode){case s.UP:return this._repeat(null,1,e),!0;case s.DOWN:return this._repeat(null,-1,e),!0;case s.PAGE_UP:return this._repeat(null,i.page,e),!0;case s.PAGE_DOWN:return this._repeat(null,-i.page,e),!0}return!1},_start:function(t){return this.spinning||this._trigger("start",t)!==!1?(this.counter||(this.counter=1),this.spinning=!0,!0):!1},_repeat:function(t,e,i){t=t||500,clearTimeout(this.timer),this.timer=this._delay(function(){this._repeat(40,e,i)},t),this._spin(e*this.options.step,i)},_spin:function(t,e){var i=this.value()||0;this.counter||(this.counter=1),i=this._adjustValue(i+t*this._increment(this.counter)),this.spinning&&this._trigger("spin",e,{value:i})===!1||(this._value(i),this.counter++)},_increment:function(e){var i=this.options.incremental;return i?t.isFunction(i)?i(e):Math.floor(e*e*e/5e4-e*e/500+17*e/200+1):1},_precision:function(){var t=this._precisionOf(this.options.step);return null!==this.options.min&&(t=Math.max(t,this._precisionOf(this.options.min))),t},_precisionOf:function(t){var e=""+t,i=e.indexOf(".");return-1===i?0:e.length-i-1},_adjustValue:function(t){var e,i,s=this.options;return e=null!==s.min?s.min:0,i=t-e,i=Math.round(i/s.step)*s.step,t=e+i,t=parseFloat(t.toFixed(this._precision())),null!==s.max&&t>s.max?s.max:null!==s.min&&s.min>t?s.min:t},_stop:function(t){this.spinning&&(clearTimeout(this.timer),clearTimeout(this.mousewheelTimer),this.counter=0,this.spinning=!1,this._trigger("stop",t))},_setOption:function(t,e){var i,s,n;return"culture"===t||"numberFormat"===t?(i=this._parse(this.element.val()),this.options[t]=e,this.element.val(this._format(i)),void 0):(("max"===t||"min"===t||"step"===t)&&"string"==typeof e&&(e=this._parse(e)),"icons"===t&&(s=this.buttons.first().find(".ui-icon"),this._removeClass(s,null,this.options.icons.up),this._addClass(s,null,e.up),n=this.buttons.last().find(".ui-icon"),this._removeClass(n,null,this.options.icons.down),this._addClass(n,null,e.down)),this._super(t,e),void 0)},_setOptionDisabled:function(t){this._super(t),this._toggleClass(this.uiSpinner,null,"ui-state-disabled",!!t),this.element.prop("disabled",!!t),this.buttons.button(t?"disable":"enable")},_setOptions:r(function(t){this._super(t)}),_parse:function(t){return"string"==typeof t&&""!==t&&(t=window.Globalize&&this.options.numberFormat?Globalize.parseFloat(t,10,this.options.culture):+t),""===t||isNaN(t)?null:t},_format:function(t){return""===t?"":window.Globalize&&this.options.numberFormat?Globalize.format(t,this.options.numberFormat,this.options.culture):t},_refresh:function(){this.element.attr({"aria-valuemin":this.options.min,"aria-valuemax":this.options.max,"aria-valuenow":this._parse(this.element.val())})},isValid:function(){var t=this.value();return null===t?!1:t===this._adjustValue(t)},_value:function(t,e){var i;""!==t&&(i=this._parse(t),null!==i&&(e||(i=this._adjustValue(i)),t=this._format(i))),this.element.val(t),this._refresh()},_destroy:function(){this.element.prop("disabled",!1).removeAttr("autocomplete role aria-valuemin aria-valuemax aria-valuenow"),this.uiSpinner.replaceWith(this.element)},stepUp:r(function(t){this._stepUp(t)}),_stepUp:function(t){this._start()&&(this._spin((t||1)*this.options.step),this._stop())},stepDown:r(function(t){this._stepDown(t)}),_stepDown:function(t){this._start()&&(this._spin((t||1)*-this.options.step),this._stop())},pageUp:r(function(t){this._stepUp((t||1)*this.options.page)}),pageDown:r(function(t){this._stepDown((t||1)*this.options.page)}),value:function(t){return arguments.length?(r(this._value).call(this,t),void 0):this._parse(this.element.val())},widget:function(){return this.uiSpinner}}),t.uiBackCompat!==!1&&t.widget("ui.spinner",t.ui.spinner,{_enhance:function(){this.uiSpinner=this.element.attr("autocomplete","off").wrap(this._uiSpinnerHtml()).parent().append(this._buttonHtml())},_uiSpinnerHtml:function(){return"<span>"},_buttonHtml:function(){return"<a></a><a></a>"}}),t.ui.spinner,t.widget("ui.tabs",{version:"1.12.1",delay:300,options:{active:null,classes:{"ui-tabs":"ui-corner-all","ui-tabs-nav":"ui-corner-all","ui-tabs-panel":"ui-corner-bottom","ui-tabs-tab":"ui-corner-top"},collapsible:!1,event:"click",heightStyle:"content",hide:null,show:null,activate:null,beforeActivate:null,beforeLoad:null,load:null},_isLocal:function(){var t=/#.*$/;return function(e){var i,s;i=e.href.replace(t,""),s=location.href.replace(t,"");try{i=decodeURIComponent(i)}catch(n){}try{s=decodeURIComponent(s)}catch(n){}return e.hash.length>1&&i===s}}(),_create:function(){var e=this,i=this.options;this.running=!1,this._addClass("ui-tabs","ui-widget ui-widget-content"),this._toggleClass("ui-tabs-collapsible",null,i.collapsible),this._processTabs(),i.active=this._initialActive(),t.isArray(i.disabled)&&(i.disabled=t.unique(i.disabled.concat(t.map(this.tabs.filter(".ui-state-disabled"),function(t){return e.tabs.index(t)}))).sort()),this.active=this.options.active!==!1&&this.anchors.length?this._findActive(i.active):t(),this._refresh(),this.active.length&&this.load(i.active)},_initialActive:function(){var e=this.options.active,i=this.options.collapsible,s=location.hash.substring(1);return null===e&&(s&&this.tabs.each(function(i,n){return t(n).attr("aria-controls")===s?(e=i,!1):void 0}),null===e&&(e=this.tabs.index(this.tabs.filter(".ui-tabs-active"))),(null===e||-1===e)&&(e=this.tabs.length?0:!1)),e!==!1&&(e=this.tabs.index(this.tabs.eq(e)),-1===e&&(e=i?!1:0)),!i&&e===!1&&this.anchors.length&&(e=0),e},_getCreateEventData:function(){return{tab:this.active,panel:this.active.length?this._getPanelForTab(this.active):t()}},_tabKeydown:function(e){var i=t(t.ui.safeActiveElement(this.document[0])).closest("li"),s=this.tabs.index(i),n=!0;if(!this._handlePageNav(e)){switch(e.keyCode){case t.ui.keyCode.RIGHT:case t.ui.keyCode.DOWN:s++;break;case t.ui.keyCode.UP:case t.ui.keyCode.LEFT:n=!1,s--;break;case t.ui.keyCode.END:s=this.anchors.length-1;break;case t.ui.keyCode.HOME:s=0;break;case t.ui.keyCode.SPACE:return e.preventDefault(),clearTimeout(this.activating),this._activate(s),void 0;case t.ui.keyCode.ENTER:return e.preventDefault(),clearTimeout(this.activating),this._activate(s===this.options.active?!1:s),void 0;default:return}e.preventDefault(),clearTimeout(this.activating),s=this._focusNextTab(s,n),e.ctrlKey||e.metaKey||(i.attr("aria-selected","false"),this.tabs.eq(s).attr("aria-selected","true"),this.activating=this._delay(function(){this.option("active",s)},this.delay))}},_panelKeydown:function(e){this._handlePageNav(e)||e.ctrlKey&&e.keyCode===t.ui.keyCode.UP&&(e.preventDefault(),this.active.trigger("focus"))},_handlePageNav:function(e){return e.altKey&&e.keyCode===t.ui.keyCode.PAGE_UP?(this._activate(this._focusNextTab(this.options.active-1,!1)),!0):e.altKey&&e.keyCode===t.ui.keyCode.PAGE_DOWN?(this._activate(this._focusNextTab(this.options.active+1,!0)),!0):void 0},_findNextTab:function(e,i){function s(){return e>n&&(e=0),0>e&&(e=n),e}for(var n=this.tabs.length-1;-1!==t.inArray(s(),this.options.disabled);)e=i?e+1:e-1;return e},_focusNextTab:function(t,e){return t=this._findNextTab(t,e),this.tabs.eq(t).trigger("focus"),t},_setOption:function(t,e){return"active"===t?(this._activate(e),void 0):(this._super(t,e),"collapsible"===t&&(this._toggleClass("ui-tabs-collapsible",null,e),e||this.options.active!==!1||this._activate(0)),"event"===t&&this._setupEvents(e),"heightStyle"===t&&this._setupHeightStyle(e),void 0)},_sanitizeSelector:function(t){return t?t.replace(/[!"$%&'()*+,.\/:;<=>?@\[\]\^`{|}~]/g,"\\$&"):""},refresh:function(){var e=this.options,i=this.tablist.children(":has(a[href])");e.disabled=t.map(i.filter(".ui-state-disabled"),function(t){return i.index(t)}),this._processTabs(),e.active!==!1&&this.anchors.length?this.active.length&&!t.contains(this.tablist[0],this.active[0])?this.tabs.length===e.disabled.length?(e.active=!1,this.active=t()):this._activate(this._findNextTab(Math.max(0,e.active-1),!1)):e.active=this.tabs.index(this.active):(e.active=!1,this.active=t()),this._refresh()},_refresh:function(){this._setOptionDisabled(this.options.disabled),this._setupEvents(this.options.event),this._setupHeightStyle(this.options.heightStyle),this.tabs.not(this.active).attr({"aria-selected":"false","aria-expanded":"false",tabIndex:-1}),this.panels.not(this._getPanelForTab(this.active)).hide().attr({"aria-hidden":"true"}),this.active.length?(this.active.attr({"aria-selected":"true","aria-expanded":"true",tabIndex:0}),this._addClass(this.active,"ui-tabs-active","ui-state-active"),this._getPanelForTab(this.active).show().attr({"aria-hidden":"false"})):this.tabs.eq(0).attr("tabIndex",0)},_processTabs:function(){var e=this,i=this.tabs,s=this.anchors,n=this.panels;this.tablist=this._getList().attr("role","tablist"),this._addClass(this.tablist,"ui-tabs-nav","ui-helper-reset ui-helper-clearfix ui-widget-header"),this.tablist.on("mousedown"+this.eventNamespace,"> li",function(e){t(this).is(".ui-state-disabled")&&e.preventDefault()}).on("focus"+this.eventNamespace,".ui-tabs-anchor",function(){t(this).closest("li").is(".ui-state-disabled")&&this.blur()}),this.tabs=this.tablist.find("> li:has(a[href])").attr({role:"tab",tabIndex:-1}),this._addClass(this.tabs,"ui-tabs-tab","ui-state-default"),this.anchors=this.tabs.map(function(){return t("a",this)[0]}).attr({role:"presentation",tabIndex:-1}),this._addClass(this.anchors,"ui-tabs-anchor"),this.panels=t(),this.anchors.each(function(i,s){var n,o,a,r=t(s).uniqueId().attr("id"),h=t(s).closest("li"),l=h.attr("aria-controls");e._isLocal(s)?(n=s.hash,a=n.substring(1),o=e.element.find(e._sanitizeSelector(n))):(a=h.attr("aria-controls")||t({}).uniqueId()[0].id,n="#"+a,o=e.element.find(n),o.length||(o=e._createPanel(a),o.insertAfter(e.panels[i-1]||e.tablist)),o.attr("aria-live","polite")),o.length&&(e.panels=e.panels.add(o)),l&&h.data("ui-tabs-aria-controls",l),h.attr({"aria-controls":a,"aria-labelledby":r}),o.attr("aria-labelledby",r)}),this.panels.attr("role","tabpanel"),this._addClass(this.panels,"ui-tabs-panel","ui-widget-content"),i&&(this._off(i.not(this.tabs)),this._off(s.not(this.anchors)),this._off(n.not(this.panels)))},_getList:function(){return this.tablist||this.element.find("ol, ul").eq(0)},_createPanel:function(e){return t("<div>").attr("id",e).data("ui-tabs-destroy",!0)},_setOptionDisabled:function(e){var i,s,n;for(t.isArray(e)&&(e.length?e.length===this.anchors.length&&(e=!0):e=!1),n=0;s=this.tabs[n];n++)i=t(s),e===!0||-1!==t.inArray(n,e)?(i.attr("aria-disabled","true"),this._addClass(i,null,"ui-state-disabled")):(i.removeAttr("aria-disabled"),this._removeClass(i,null,"ui-state-disabled"));this.options.disabled=e,this._toggleClass(this.widget(),this.widgetFullName+"-disabled",null,e===!0)},_setupEvents:function(e){var i={};e&&t.each(e.split(" "),function(t,e){i[e]="_eventHandler"}),this._off(this.anchors.add(this.tabs).add(this.panels)),this._on(!0,this.anchors,{click:function(t){t.preventDefault()}}),this._on(this.anchors,i),this._on(this.tabs,{keydown:"_tabKeydown"}),this._on(this.panels,{keydown:"_panelKeydown"}),this._focusable(this.tabs),this._hoverable(this.tabs)},_setupHeightStyle:function(e){var i,s=this.element.parent();"fill"===e?(i=s.height(),i-=this.element.outerHeight()-this.element.height(),this.element.siblings(":visible").each(function(){var e=t(this),s=e.css("position");"absolute"!==s&&"fixed"!==s&&(i-=e.outerHeight(!0))}),this.element.children().not(this.panels).each(function(){i-=t(this).outerHeight(!0)}),this.panels.each(function(){t(this).height(Math.max(0,i-t(this).innerHeight()+t(this).height()))}).css("overflow","auto")):"auto"===e&&(i=0,this.panels.each(function(){i=Math.max(i,t(this).height("").height())}).height(i))},_eventHandler:function(e){var i=this.options,s=this.active,n=t(e.currentTarget),o=n.closest("li"),a=o[0]===s[0],r=a&&i.collapsible,h=r?t():this._getPanelForTab(o),l=s.length?this._getPanelForTab(s):t(),c={oldTab:s,oldPanel:l,newTab:r?t():o,newPanel:h};e.preventDefault(),o.hasClass("ui-state-disabled")||o.hasClass("ui-tabs-loading")||this.running||a&&!i.collapsible||this._trigger("beforeActivate",e,c)===!1||(i.active=r?!1:this.tabs.index(o),this.active=a?t():o,this.xhr&&this.xhr.abort(),l.length||h.length||t.error("jQuery UI Tabs: Mismatching fragment identifier."),h.length&&this.load(this.tabs.index(o),e),this._toggle(e,c))},_toggle:function(e,i){function s(){o.running=!1,o._trigger("activate",e,i)}function n(){o._addClass(i.newTab.closest("li"),"ui-tabs-active","ui-state-active"),a.length&&o.options.show?o._show(a,o.options.show,s):(a.show(),s())}var o=this,a=i.newPanel,r=i.oldPanel;this.running=!0,r.length&&this.options.hide?this._hide(r,this.options.hide,function(){o._removeClass(i.oldTab.closest("li"),"ui-tabs-active","ui-state-active"),n()}):(this._removeClass(i.oldTab.closest("li"),"ui-tabs-active","ui-state-active"),r.hide(),n()),r.attr("aria-hidden","true"),i.oldTab.attr({"aria-selected":"false","aria-expanded":"false"}),a.length&&r.length?i.oldTab.attr("tabIndex",-1):a.length&&this.tabs.filter(function(){return 0===t(this).attr("tabIndex")}).attr("tabIndex",-1),a.attr("aria-hidden","false"),i.newTab.attr({"aria-selected":"true","aria-expanded":"true",tabIndex:0})},_activate:function(e){var i,s=this._findActive(e);s[0]!==this.active[0]&&(s.length||(s=this.active),i=s.find(".ui-tabs-anchor")[0],this._eventHandler({target:i,currentTarget:i,preventDefault:t.noop}))},_findActive:function(e){return e===!1?t():this.tabs.eq(e)},_getIndex:function(e){return"string"==typeof e&&(e=this.anchors.index(this.anchors.filter("[href$='"+t.ui.escapeSelector(e)+"']"))),e},_destroy:function(){this.xhr&&this.xhr.abort(),this.tablist.removeAttr("role").off(this.eventNamespace),this.anchors.removeAttr("role tabIndex").removeUniqueId(),this.tabs.add(this.panels).each(function(){t.data(this,"ui-tabs-destroy")?t(this).remove():t(this).removeAttr("role tabIndex aria-live aria-busy aria-selected aria-labelledby aria-hidden aria-expanded")}),this.tabs.each(function(){var e=t(this),i=e.data("ui-tabs-aria-controls");i?e.attr("aria-controls",i).removeData("ui-tabs-aria-controls"):e.removeAttr("aria-controls")}),this.panels.show(),"content"!==this.options.heightStyle&&this.panels.css("height","")},enable:function(e){var i=this.options.disabled;i!==!1&&(void 0===e?i=!1:(e=this._getIndex(e),i=t.isArray(i)?t.map(i,function(t){return t!==e?t:null}):t.map(this.tabs,function(t,i){return i!==e?i:null})),this._setOptionDisabled(i))},disable:function(e){var i=this.options.disabled;if(i!==!0){if(void 0===e)i=!0;else{if(e=this._getIndex(e),-1!==t.inArray(e,i))return;i=t.isArray(i)?t.merge([e],i).sort():[e]}this._setOptionDisabled(i)}},load:function(e,i){e=this._getIndex(e);var s=this,n=this.tabs.eq(e),o=n.find(".ui-tabs-anchor"),a=this._getPanelForTab(n),r={tab:n,panel:a},h=function(t,e){"abort"===e&&s.panels.stop(!1,!0),s._removeClass(n,"ui-tabs-loading"),a.removeAttr("aria-busy"),t===s.xhr&&delete s.xhr};this._isLocal(o[0])||(this.xhr=t.ajax(this._ajaxSettings(o,i,r)),this.xhr&&"canceled"!==this.xhr.statusText&&(this._addClass(n,"ui-tabs-loading"),a.attr("aria-busy","true"),this.xhr.done(function(t,e,n){setTimeout(function(){a.html(t),s._trigger("load",i,r),h(n,e)},1)}).fail(function(t,e){setTimeout(function(){h(t,e)},1)})))},_ajaxSettings:function(e,i,s){var n=this;return{url:e.attr("href").replace(/#.*$/,""),beforeSend:function(e,o){return n._trigger("beforeLoad",i,t.extend({jqXHR:e,ajaxSettings:o},s))}}},_getPanelForTab:function(e){var i=t(e).attr("aria-controls");return this.element.find(this._sanitizeSelector("#"+i))}}),t.uiBackCompat!==!1&&t.widget("ui.tabs",t.ui.tabs,{_processTabs:function(){this._superApply(arguments),this._addClass(this.tabs,"ui-tab")}}),t.ui.tabs,t.widget("ui.tooltip",{version:"1.12.1",options:{classes:{"ui-tooltip":"ui-corner-all ui-widget-shadow"},content:function(){var e=t(this).attr("title")||"";return t("<a>").text(e).html()},hide:!0,items:"[title]:not([disabled])",position:{my:"left top+15",at:"left bottom",collision:"flipfit flip"},show:!0,track:!1,close:null,open:null},_addDescribedBy:function(e,i){var s=(e.attr("aria-describedby")||"").split(/\s+/);s.push(i),e.data("ui-tooltip-id",i).attr("aria-describedby",t.trim(s.join(" ")))},_removeDescribedBy:function(e){var i=e.data("ui-tooltip-id"),s=(e.attr("aria-describedby")||"").split(/\s+/),n=t.inArray(i,s);-1!==n&&s.splice(n,1),e.removeData("ui-tooltip-id"),s=t.trim(s.join(" ")),s?e.attr("aria-describedby",s):e.removeAttr("aria-describedby")},_create:function(){this._on({mouseover:"open",focusin:"open"}),this.tooltips={},this.parents={},this.liveRegion=t("<div>").attr({role:"log","aria-live":"assertive","aria-relevant":"additions"}).appendTo(this.document[0].body),this._addClass(this.liveRegion,null,"ui-helper-hidden-accessible"),this.disabledTitles=t([])},_setOption:function(e,i){var s=this;this._super(e,i),"content"===e&&t.each(this.tooltips,function(t,e){s._updateContent(e.element)})},_setOptionDisabled:function(t){this[t?"_disable":"_enable"]()},_disable:function(){var e=this;t.each(this.tooltips,function(i,s){var n=t.Event("blur");n.target=n.currentTarget=s.element[0],e.close(n,!0)}),this.disabledTitles=this.disabledTitles.add(this.element.find(this.options.items).addBack().filter(function(){var e=t(this);return e.is("[title]")?e.data("ui-tooltip-title",e.attr("title")).removeAttr("title"):void 0}))},_enable:function(){this.disabledTitles.each(function(){var e=t(this);e.data("ui-tooltip-title")&&e.attr("title",e.data("ui-tooltip-title"))}),this.disabledTitles=t([])},open:function(e){var i=this,s=t(e?e.target:this.element).closest(this.options.items);s.length&&!s.data("ui-tooltip-id")&&(s.attr("title")&&s.data("ui-tooltip-title",s.attr("title")),s.data("ui-tooltip-open",!0),e&&"mouseover"===e.type&&s.parents().each(function(){var e,s=t(this);s.data("ui-tooltip-open")&&(e=t.Event("blur"),e.target=e.currentTarget=this,i.close(e,!0)),s.attr("title")&&(s.uniqueId(),i.parents[this.id]={element:this,title:s.attr("title")},s.attr("title",""))}),this._registerCloseHandlers(e,s),this._updateContent(s,e))},_updateContent:function(t,e){var i,s=this.options.content,n=this,o=e?e.type:null;return"string"==typeof s||s.nodeType||s.jquery?this._open(e,t,s):(i=s.call(t[0],function(i){n._delay(function(){t.data("ui-tooltip-open")&&(e&&(e.type=o),this._open(e,t,i))})}),i&&this._open(e,t,i),void 0)},_open:function(e,i,s){function n(t){l.of=t,a.is(":hidden")||a.position(l)}var o,a,r,h,l=t.extend({},this.options.position);if(s){if(o=this._find(i))return o.tooltip.find(".ui-tooltip-content").html(s),void 0;i.is("[title]")&&(e&&"mouseover"===e.type?i.attr("title",""):i.removeAttr("title")),o=this._tooltip(i),a=o.tooltip,this._addDescribedBy(i,a.attr("id")),a.find(".ui-tooltip-content").html(s),this.liveRegion.children().hide(),h=t("<div>").html(a.find(".ui-tooltip-content").html()),h.removeAttr("name").find("[name]").removeAttr("name"),h.removeAttr("id").find("[id]").removeAttr("id"),h.appendTo(this.liveRegion),this.options.track&&e&&/^mouse/.test(e.type)?(this._on(this.document,{mousemove:n}),n(e)):a.position(t.extend({of:i},this.options.position)),a.hide(),this._show(a,this.options.show),this.options.track&&this.options.show&&this.options.show.delay&&(r=this.delayedShow=setInterval(function(){a.is(":visible")&&(n(l.of),clearInterval(r))},t.fx.interval)),this._trigger("open",e,{tooltip:a})}},_registerCloseHandlers:function(e,i){var s={keyup:function(e){if(e.keyCode===t.ui.keyCode.ESCAPE){var s=t.Event(e);s.currentTarget=i[0],this.close(s,!0)}}};i[0]!==this.element[0]&&(s.remove=function(){this._removeTooltip(this._find(i).tooltip)}),e&&"mouseover"!==e.type||(s.mouseleave="close"),e&&"focusin"!==e.type||(s.focusout="close"),this._on(!0,i,s)},close:function(e){var i,s=this,n=t(e?e.currentTarget:this.element),o=this._find(n);return o?(i=o.tooltip,o.closing||(clearInterval(this.delayedShow),n.data("ui-tooltip-title")&&!n.attr("title")&&n.attr("title",n.data("ui-tooltip-title")),this._removeDescribedBy(n),o.hiding=!0,i.stop(!0),this._hide(i,this.options.hide,function(){s._removeTooltip(t(this))}),n.removeData("ui-tooltip-open"),this._off(n,"mouseleave focusout keyup"),n[0]!==this.element[0]&&this._off(n,"remove"),this._off(this.document,"mousemove"),e&&"mouseleave"===e.type&&t.each(this.parents,function(e,i){t(i.element).attr("title",i.title),delete s.parents[e]}),o.closing=!0,this._trigger("close",e,{tooltip:i}),o.hiding||(o.closing=!1)),void 0):(n.removeData("ui-tooltip-open"),void 0)},_tooltip:function(e){var i=t("<div>").attr("role","tooltip"),s=t("<div>").appendTo(i),n=i.uniqueId().attr("id");return this._addClass(s,"ui-tooltip-content"),this._addClass(i,"ui-tooltip","ui-widget ui-widget-content"),i.appendTo(this._appendTo(e)),this.tooltips[n]={element:e,tooltip:i}},_find:function(t){var e=t.data("ui-tooltip-id");return e?this.tooltips[e]:null},_removeTooltip:function(t){t.remove(),delete this.tooltips[t.attr("id")]},_appendTo:function(t){var e=t.closest(".ui-front, dialog");return e.length||(e=this.document[0].body),e},_destroy:function(){var e=this;t.each(this.tooltips,function(i,s){var n=t.Event("blur"),o=s.element;n.target=n.currentTarget=o[0],e.close(n,!0),t("#"+i).remove(),o.data("ui-tooltip-title")&&(o.attr("title")||o.attr("title",o.data("ui-tooltip-title")),o.removeData("ui-tooltip-title"))}),this.liveRegion.remove()}}),t.uiBackCompat!==!1&&t.widget("ui.tooltip",t.ui.tooltip,{options:{tooltipClass:null},_tooltip:function(){var t=this._superApply(arguments);return this.options.tooltipClass&&t.tooltip.addClass(this.options.tooltipClass),t}}),t.ui.tooltip});
1233
1234// jQuery HC-Sticky
1235// =============
1236// Version: 1.2.43
1237// Copyright: Some Web Media
1238// Author: Some Web Guy
1239// Author URL: http://twitter.com/some_web_guy
1240// Website: http://someweblog.com/
1241// Plugin URL: https://github.com/somewebmedia/hc-sticky
1242// License: Released under the MIT License www.opensource.org/licenses/mit-license.php
1243// Description: Cross-browser jQuery plugin that makes any element attached to the page and always visible while you scroll.
1244
1245(function($, window, undefined) {
1246	"use strict";
1247
1248	// console.log shortcut
1249	var log = function(t){console.log(t)};
1250
1251	var $window = $(window),
1252		document = window.document,
1253		$document = $(document);
1254
1255	// detect IE version
1256	var ie = (function(){var undef, v = 3, div = document.createElement('div'), all = div.getElementsByTagName('i'); while (div.innerHTML = '<!--[if gt IE ' + (++v) + ']><i></i><![endif]-->', all[0]){}; return v > 4 ? v : undef})();
1257
1258	/*----------------------------------------------------
1259						Global functions
1260	----------------------------------------------------*/
1261
1262	// check for scroll direction and speed
1263	var getScroll = function() {
1264		var pageXOffset = window.pageXOffset !== undefined ? window.pageXOffset : (document.compatMode == "CSS1Compat" ? window.document.documentElement.scrollLeft : window.document.body.scrollLeft),
1265			pageYOffset = window.pageYOffset !== undefined ? window.pageYOffset : (document.compatMode == "CSS1Compat" ? window.document.documentElement.scrollTop : window.document.body.scrollTop);
1266
1267		if (typeof getScroll.x == 'undefined') {
1268			getScroll.x = pageXOffset;
1269			getScroll.y = pageYOffset;
1270		}
1271		if (typeof getScroll.distanceX == 'undefined') {
1272			getScroll.distanceX = pageXOffset;
1273			getScroll.distanceY = pageYOffset;
1274		} else {
1275			getScroll.distanceX = pageXOffset - getScroll.x;
1276			getScroll.distanceY = pageYOffset - getScroll.y;
1277		}
1278
1279		var diffX = getScroll.x - pageXOffset,
1280			diffY = getScroll.y - pageYOffset;
1281
1282		getScroll.direction = diffX < 0 ? 'right' :
1283			diffX > 0 ? 'left' :
1284			diffY <= 0 ? 'down' :
1285			diffY > 0 ? 'up' : 'first';
1286
1287		getScroll.x = pageXOffset;
1288		getScroll.y = pageYOffset;
1289	};
1290	$window.on('scroll', getScroll);
1291
1292
1293	// little original style plugin
1294	$.fn.style = function(style) {
1295		if (!style) return null;
1296
1297		var $this = $(this),
1298			value;
1299
1300		// clone element
1301		var $clone = $this.clone().css('display','none');
1302		// randomize the name of cloned radio buttons, otherwise selections get screwed
1303		$clone.find('input:radio').attr('name','copy-' + Math.floor((Math.random()*100)+1));
1304		// insert clone to DOM
1305		$this.after($clone);
1306
1307		var getStyle = function(el, style){
1308			var val;
1309			if (el.currentStyle) {
1310				// replace dashes with capitalized letter, e.g. padding-left to paddingLeft
1311				val = el.currentStyle[style.replace(/-\w/g, function(s){return s.toUpperCase().replace('-','')})];
1312			} else if (window.getComputedStyle) {
1313				val = document.defaultView.getComputedStyle(el,null).getPropertyValue(style);
1314			}
1315			// check for margin:auto
1316			val = (/margin/g.test(style)) ? ((parseInt(val) === $this[0].offsetLeft) ? val : 'auto') : val;
1317			return val;
1318		};
1319
1320		if (typeof style == 'string') {
1321			value = getStyle($clone[0], style);
1322		} else {
1323			value = {};
1324			$.each(style, function(i, s){
1325				value[s] = getStyle($clone[0], s);
1326			});
1327		}
1328
1329		// destroy clone
1330		$clone.remove();
1331
1332		return value || null;
1333	};
1334
1335
1336	/*----------------------------------------------------
1337						jQuery plugin
1338	----------------------------------------------------*/
1339
1340	$.fn.extend({
1341
1342		hcSticky: function(options) {
1343
1344			// check if selected element exist in DOM, user doesn't have to worry about that
1345			if (this.length == 0) return this;
1346
1347			this.pluginOptions('hcSticky', {
1348				top: 0,
1349				bottom: 0,
1350				bottomEnd: 0,
1351				innerTop: 0,
1352				innerSticker: null,
1353				className: 'sticky',
1354				wrapperClassName: 'wrapper-sticky',
1355				stickTo: null,
1356				responsive: true,
1357				followScroll: true,
1358				offResolutions: null,
1359				onStart: $.noop,
1360				onStop: $.noop,
1361				on: true,
1362				fn: null // used only by the plugin
1363			}, options || {}, {
1364				reinit: function(){
1365					// just call itself again
1366					$(this).hcSticky();
1367				},
1368				stop: function(){
1369					$(this).pluginOptions('hcSticky', {on: false}).each(function(){
1370						var $this = $(this),
1371							options = $this.pluginOptions('hcSticky'),
1372							$wrapper = $this.parent('.' + options.wrapperClassName);
1373
1374						// set current position
1375						var top = $this.offset().top - $wrapper.offset().top;
1376						$this.css({
1377							position: 'relative',
1378							top: top,
1379							bottom: 'auto',
1380							left: 'auto',
1381							right: 'auto'
1382						}).removeClass(options.className);
1383					});
1384				},
1385				off: function(){
1386					$(this).pluginOptions('hcSticky', {on: false}).each(function(){
1387						var $this = $(this),
1388							options = $this.pluginOptions('hcSticky'),
1389							$wrapper = $this.parent('.' + options.wrapperClassName);
1390
1391						// clear position
1392						$this.css({
1393							position: 'relative',
1394							top: 'auto',
1395							bottom: 'auto',
1396							left: 'auto',
1397							right: 'auto'
1398						}).removeClass(options.className);
1399
1400						$wrapper.css('height', 'auto');
1401					});
1402				},
1403				on: function(){
1404					$(this).each(function(){
1405						$(this).pluginOptions('hcSticky', {
1406							on: true,
1407							remember: {
1408								offsetTop: $window.scrollTop()
1409							}
1410						}).hcSticky();
1411					});
1412				},
1413				destroy: function(){
1414					var $this = $(this),
1415						options = $this.pluginOptions('hcSticky'),
1416						$wrapper = $this.parent('.' + options.wrapperClassName);
1417
1418					// reset position to original
1419					$this.removeData('hcStickyInit').css({
1420						position: $wrapper.css('position'),
1421						top: $wrapper.css('top'),
1422						bottom: $wrapper.css('bottom'),
1423						left: $wrapper.css('left'),
1424						right: $wrapper.css('right')
1425					}).removeClass(options.className);
1426
1427					// remove events
1428					$window.off('resize', options.fn.resize).off('scroll', options.fn.scroll);
1429
1430					// destroy wrapper
1431					$this.unwrap();
1432				}
1433			});
1434
1435			// on/off settings
1436			if (options && typeof options.on != 'undefined') {
1437				if (options.on) {
1438					this.hcSticky('on');
1439				} else {
1440					this.hcSticky('off');
1441				}
1442			}
1443
1444			// stop on commands
1445			if (typeof options == 'string') return this;
1446
1447			// do our thing
1448			return this.each(function(){
1449
1450				var $this = $(this),
1451					options = $this.pluginOptions('hcSticky');
1452
1453				var $wrapper = (function(){ // wrapper exists
1454						var $this_wrapper = $this.parent('.' + options.wrapperClassName);
1455						if ($this_wrapper.length > 0) {
1456							$this_wrapper.css({
1457								'height': 'auto',
1458								'width': (function(){
1459									// check if wrapper already has width in %
1460									var width = $this_wrapper.style('width');
1461									if (width.indexOf('%') >= 0 || width == 'auto') {
1462										if ($this.css('box-sizing') == 'border-box' || $this.css('-moz-box-sizing') == 'border-box') {
1463											$this.css('width', $this_wrapper.width());
1464										} else {
1465											$this.css('width', $this_wrapper.width() - parseInt($this.css('padding-left') - parseInt($this.css('padding-right'))));
1466										}
1467										return width;
1468									} else {
1469										return $this.outerWidth(true);
1470									}
1471								})()
1472							});
1473							return $this_wrapper;
1474						} else {
1475							return false;
1476						}
1477					})() || (function(){ // wrapper doesn't exist
1478
1479						var this_css = $this.style(['width', 'margin-left', 'left', 'right', 'top', 'bottom', 'float', 'display']);
1480						var display = $this.css('display');
1481
1482						var $this_wrapper = $('<div>', {
1483							'class': options.wrapperClassName
1484						}).css({
1485							'display': display,
1486							'height': 'auto',
1487							'width': (function(){
1488								if (this_css['width'].indexOf('%') >= 0 || (this_css['width'] == 'auto' && display != 'inline-block' && display != 'inline')) { // check if element has width in %
1489									$this.css('width', parseFloat($this.css('width')));
1490									return this_css['width'];
1491								} else if (this_css['width'] == 'auto' && (display == 'inline-block' || display == 'inline')) {
1492									return $this.width();
1493								} else {
1494									// check if margin is set to 'auto'
1495									return (this_css['margin-left'] == 'auto') ? $this.outerWidth() : $this.outerWidth(true);
1496								}
1497							})(),
1498							'margin': (this_css['margin-left']) ? 'auto' : null,
1499							'position': (function(){
1500								var position = $this.css('position');
1501								return position == 'static' ? 'relative' : position;
1502							})(),
1503							'float': this_css['float'] || null,
1504							'left': this_css['left'],
1505							'right': this_css['right'],
1506							'top': this_css['top'],
1507							'bottom': this_css['bottom'],
1508							'vertical-align': 'top'
1509						});
1510
1511						$this.wrap($this_wrapper);
1512
1513						// ie7 inline-block fix
1514						if (ie === 7) {
1515							if ($('head').find('style#hcsticky-iefix').length === 0) {
1516								$('<style id="hcsticky-iefix">.' + options.wrapperClassName + ' {zoom: 1;}</style>').appendTo('head');
1517							}
1518						}
1519
1520						// return appended element
1521						return $this.parent();
1522					})();
1523
1524
1525				// check if we should go further
1526				if ($this.data('hcStickyInit')) return;
1527				// leave our mark
1528				$this.data('hcStickyInit', true);
1529
1530
1531				// check if referring element is document
1532				var stickTo_document = options.stickTo && (options.stickTo == 'document' || (options.stickTo.nodeType && options.stickTo.nodeType == 9) || (typeof options.stickTo == 'object' && options.stickTo instanceof (typeof HTMLDocument != 'undefined' ? HTMLDocument : Document))) ? true : false;
1533
1534				// select container ;)
1535				var $container = options.stickTo
1536					? stickTo_document
1537						? $document
1538						: typeof options.stickTo == 'string'
1539							? $(options.stickTo)
1540							: options.stickTo
1541					: $wrapper.parent();
1542
1543				// clear sticky styles
1544				$this.css({
1545					top: 'auto',
1546					bottom: 'auto',
1547					left: 'auto',
1548					right: 'auto'
1549				});
1550
1551				// attach event on entire page load, maybe some images inside element has been loading, so chek height again
1552				$window.load(function(){
1553					if ($this.outerHeight(true) > $container.height()) {
1554						$wrapper.css('height', 'auto');
1555						$this.hcSticky('reinit');
1556					}
1557				});
1558
1559				// functions for attachiung and detaching sticky
1560				var _setFixed = function(args) {
1561						// check if already floating
1562						if ($this.hasClass(options.className)) return;
1563
1564						// apply styles
1565						args = args || {};
1566						$this.css({
1567							position: 'fixed',
1568							top: args.top || 0,
1569							left: args.left || $wrapper.offset().left
1570						}).addClass(options.className);
1571
1572						// start event
1573						options.onStart.apply($this[0]);
1574						// add class to wrpaeer
1575						$wrapper.addClass('sticky-active');
1576					},
1577					_reset = function(args) {
1578						args = args || {};
1579						args.position = args.position || 'relative';
1580						args.top = args.top || 0;
1581						args.left = args.left || 0;
1582
1583						// check if we should apply css
1584						if ($this.css('position') != 'fixed' && parseInt($this.css('top')) == args.top) return;
1585
1586						// apply styles
1587						$this.css({
1588							position: args.position,
1589							top: args.top,
1590							left: args.left
1591						}).removeClass(options.className);
1592
1593						// stop event
1594						options.onStop.apply($this[0]);
1595						// remove class from wrpaeer
1596						$wrapper.removeClass('sticky-active');
1597					};
1598
1599				// sticky scroll function
1600				var onScroll = function(init) {
1601
1602					// check if we need to run sticky
1603	        if (!options.on || !$this.is(':visible')) return;
1604
1605	        // if the element is the same height or larger than the container then let's reset it so that it returns to the original position
1606	        if ($this.outerHeight(true) >= $container.height()) {
1607	            _reset();
1608
1609	            return;
1610	        }
1611
1612					var top_spacing = (options.innerSticker) ? $(options.innerSticker).position().top : ((options.innerTop) ? options.innerTop : 0),
1613						wrapper_inner_top = $wrapper.offset().top,
1614						bottom_limit = $container.height() - options.bottomEnd + (stickTo_document ? 0 : wrapper_inner_top),
1615						top_limit = $wrapper.offset().top - options.top + top_spacing,
1616						this_height = $this.outerHeight(true) + options.bottom,
1617						window_height = $window.height(),
1618						offset_top = $window.scrollTop(),
1619						this_document_top = $this.offset().top,
1620						this_window_top = this_document_top - offset_top,
1621						bottom_distance;
1622
1623
1624					// if sticky has been restarted with on/off wait for it to reach top or bottom
1625					if (typeof options.remember != 'undefined' && options.remember) {
1626
1627						var position_top = this_document_top - options.top - top_spacing;
1628
1629						if (this_height - top_spacing > window_height && options.followScroll) { // element bigger than window with follow scroll on
1630
1631							if (position_top < offset_top && offset_top + window_height <= position_top + $this.height()) {
1632								// element is in the middle of the screen, let our primary calculations do the work
1633								options.remember = false;
1634							}
1635
1636						} else { // element smaller than window or follow scroll turned off
1637
1638							if (options.remember.offsetTop > position_top) {
1639								// slide up
1640								if (offset_top <= position_top) {
1641									_setFixed({
1642										top: options.top - top_spacing
1643									});
1644									options.remember = false;
1645								}
1646							} else {
1647								// slide down
1648								if (offset_top >= position_top) {
1649									_setFixed({
1650										top: options.top - top_spacing
1651									});
1652									options.remember = false;
1653								}
1654							}
1655
1656						}
1657
1658						return;
1659					}
1660
1661
1662					if (offset_top > top_limit) {
1663
1664						// http://geek-and-poke.com/geekandpoke/2012/7/27/simply-explained.html
1665
1666						if (bottom_limit + options.bottom - (options.followScroll && window_height < this_height ? 0 : options.top) <= offset_top + this_height - top_spacing - ((this_height - top_spacing > window_height - (top_limit - top_spacing) && options.followScroll) ? (((bottom_distance = this_height - window_height - top_spacing) > 0) ? bottom_distance : 0) : 0)) {
1667							// bottom reached end
1668							_reset({
1669								top: bottom_limit - this_height + options.bottom - wrapper_inner_top
1670							});
1671						} else if (this_height - top_spacing > window_height && options.followScroll) {
1672
1673							if (this_window_top + this_height <= window_height) { // element bigger than window with follow scroll on
1674
1675								if (getScroll.direction == 'down') {
1676									// scroll down
1677									_setFixed({
1678										top: window_height - this_height
1679									});
1680								} else {
1681									// scroll up
1682									if (this_window_top < 0 && $this.css('position') == 'fixed') {
1683										_reset({
1684											top: this_document_top - (top_limit + options.top - top_spacing) - getScroll.distanceY
1685										});
1686									}
1687								}
1688
1689							} else { // element smaller than window or follow scroll turned off
1690
1691								if (getScroll.direction == 'up' && this_document_top >= offset_top + options.top - top_spacing) {
1692									// scroll up
1693									_setFixed({
1694										top: options.top - top_spacing
1695									});
1696								} else if (getScroll.direction == 'down' && this_document_top + this_height > window_height && $this.css('position') == 'fixed') {
1697									// scroll down
1698									_reset({
1699										top: this_document_top - (top_limit + options.top - top_spacing) - getScroll.distanceY
1700									});
1701								}
1702
1703							}
1704						} else {
1705							// starting (top) fixed position
1706							_setFixed({
1707								top: options.top - top_spacing
1708							});
1709						}
1710					} else {
1711						// reset
1712						_reset();
1713					}
1714
1715				};
1716
1717
1718				// store resize data in case responsive is on
1719				var resize_timeout = false,
1720					$resize_clone = false;
1721
1722				var onResize = function() {
1723
1724					// check if sticky is attached to scroll event
1725					attachScroll();
1726
1727					// check for off resolutions
1728					checkResolutions();
1729
1730					// check if we need to run sticky
1731					if (!options.on) return;
1732
1733					var setLeft = function(){
1734						// set new left position
1735						if ($this.css('position') == 'fixed') {
1736							$this.css('left', $wrapper.offset().left);
1737						} else {
1738							$this.css('left', 0);
1739						}
1740					};
1741
1742					// check for width change (css media queries)
1743					if (options.responsive) {
1744						// clone element and make it invisible
1745						if (!$resize_clone) {
1746							$resize_clone = $this.clone().attr('style', '').css({
1747								visibility: 'hidden',
1748								height: 0,
1749								overflow: 'hidden',
1750								paddingTop: 0,
1751								paddingBottom: 0,
1752								marginTop: 0,
1753								marginBottom: 0
1754							});
1755							$wrapper.after($resize_clone);
1756						}
1757
1758						var wrapper_width = $wrapper.style('width');
1759						var resize_clone_width = $resize_clone.style('width');
1760
1761						if (resize_clone_width == 'auto' && wrapper_width != 'auto') {
1762							resize_clone_width = parseInt($this.css('width'));
1763						}
1764
1765						// recalculate wrpaeer width
1766						if (resize_clone_width != wrapper_width) {
1767							$wrapper.width(resize_clone_width);
1768						}
1769
1770						// clear previous timeout
1771						if (resize_timeout) {
1772							clearTimeout(resize_timeout);
1773						}
1774						// timedout destroing of cloned elements so we don't clone it again and again while resizing the window
1775						resize_timeout = setTimeout(function() {
1776							// clear timeout id
1777							resize_timeout = false;
1778							// destroy cloned element
1779							$resize_clone.remove();
1780							$resize_clone = false;
1781						}, 250);
1782					}
1783
1784					// set new left position
1785					setLeft();
1786
1787					// recalculate inner element width (maybe original width was in %)
1788					if ($this.outerWidth(true) != $wrapper.width()) {
1789						var this_w = ($this.css('box-sizing') == 'border-box' || $this.css('-moz-box-sizing') == 'border-box')
1790							? $wrapper.width()
1791							: $wrapper.width() - parseInt($this.css('padding-left')) - parseInt($this.css('padding-right'));
1792						// subtract margins
1793						this_w = this_w - parseInt($this.css('margin-left')) - parseInt($this.css('margin-right'));
1794						// set new width
1795						$this.css('width', this_w);
1796					}
1797				};
1798
1799
1800				// remember scroll and resize callbacks so we can attach and detach them
1801				$this.pluginOptions('hcSticky', {fn: {
1802					scroll: onScroll,
1803					resize: onResize
1804				}});
1805
1806
1807				// check for off resolutions
1808				var checkResolutions = function(){
1809					if (options.offResolutions) {
1810						// convert to array
1811						if (!$.isArray(options.offResolutions)) {
1812							options.offResolutions = [options.offResolutions];
1813						}
1814
1815						var isOn = true;
1816
1817						$.each(options.offResolutions, function(i, rez){
1818							if (rez < 0) {
1819								// below
1820								if ($window.width() < rez * -1) {
1821									isOn = false;
1822									$this.hcSticky('off');
1823								}
1824							} else {
1825								// abowe
1826								if ($window.width() > rez) {
1827									isOn = false;
1828									$this.hcSticky('off');
1829								}
1830							}
1831						});
1832
1833						// turn on again
1834						if (isOn && !options.on) {
1835							$this.hcSticky('on');
1836						}
1837					}
1838				};
1839				checkResolutions();
1840
1841
1842				// attach resize function to event
1843				$window.on('resize', onResize);
1844
1845
1846				// attaching scroll function to event
1847				var attachScroll = function(){
1848					var isAttached = false;
1849					if ($._data(window, 'events').scroll != undefined) {
1850						$.each($._data(window, 'events').scroll, function(i, f){
1851							if (f.handler == options.fn.scroll) {
1852								isAttached = true;
1853							}
1854						});
1855					}
1856					if (!isAttached) {
1857						// run it once to disable glitching
1858						options.fn.scroll(true);
1859						// attach function to scroll event only once
1860						$window.on('scroll', options.fn.scroll);
1861					}
1862				};
1863				attachScroll();
1864
1865			});
1866		}
1867	});
1868
1869})(jQuery, this);
1870
1871
1872
1873// jQuery HC-PluginOptions
1874// =============
1875// Version: 1.0
1876// Copyright: Some Web Media
1877// Author: Some Web Guy
1878// Author URL: http://twitter.com/some_web_guy
1879// Website: http://someweblog.com/
1880// License: Released under the MIT License www.opensource.org/licenses/mit-license.php
1881
1882(function($, undefined) {
1883	"use strict";
1884
1885	$.fn.extend({
1886
1887		pluginOptions: function(pluginName, defaultOptions, userOptions, commands) {
1888
1889			// create object to store data
1890			if (!this.data(pluginName)) this.data(pluginName, {});
1891
1892			// return options
1893			if (pluginName && typeof defaultOptions == 'undefined') return this.data(pluginName).options;
1894
1895			// update
1896			userOptions = userOptions || (defaultOptions || {});
1897
1898			if (typeof userOptions == 'object' || userOptions === undefined) {
1899
1900				// options
1901				return this.each(function(){
1902					var $this = $(this);
1903
1904					if (!$this.data(pluginName).options) {
1905						// init our options and attach to element
1906						$this.data(pluginName, {options: $.extend(defaultOptions, userOptions || {})});
1907						// attach commands if any
1908						if (commands) {
1909							$this.data(pluginName).commands = commands;
1910						}
1911					} else {
1912						// update existing options
1913						$this.data(pluginName, $.extend($this.data(pluginName), {options: $.extend($this.data(pluginName).options, userOptions || {})}));
1914					}
1915				});
1916
1917			} else if (typeof userOptions == 'string') {
1918
1919				return this.each(function(){
1920					$(this).data(pluginName).commands[userOptions].call(this);
1921				});
1922
1923			} else {
1924
1925				return this;
1926
1927			}
1928
1929		}
1930
1931	});
1932
1933})(jQuery);
1934/*
1935 * Date Format 1.2.3
1936 * (c) 2007-2009 Steven Levithan <stevenlevithan.com>
1937 * MIT license
1938 *
1939 * Includes enhancements by Scott Trenda <scott.trenda.net>
1940 * and Kris Kowal <cixar.com/~kris.kowal/>
1941 *
1942 * Accepts a date, a mask, or a date and a mask.
1943 * Returns a formatted version of the given date.
1944 * The date defaults to the current date/time.
1945 * The mask defaults to dateFormat.masks.default.
1946 *
1947 * From:
1948 * http://blog.stevenlevithan.com/archives/date-time-format
1949 *
1950 */
1951
1952var dateFormat = function () {
1953	var	token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,
1954		timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
1955		timezoneClip = /[^-+\dA-Z]/g,
1956		pad = function (val, len) {
1957			val = String(val);
1958			len = len || 2;
1959			while (val.length < len) val = "0" + val;
1960			return val;
1961		};
1962
1963	// Regexes and supporting functions are cached through closure
1964	return function (date, mask, utc) {
1965		var dF = dateFormat;
1966
1967		// You can't provide utc if you skip other args (use the "UTC:" mask prefix)
1968		if (arguments.length == 1 && Object.prototype.toString.call(date) == "[object String]" && !/\d/.test(date)) {
1969			mask = date;
1970			date = undefined;
1971		}
1972
1973		// Passing date through Date applies Date.parse, if necessary
1974		date = date ? new Date(date) : new Date;
1975		if (isNaN(date)) throw SyntaxError("invalid date");
1976
1977		mask = String(dF.masks[mask] || mask || dF.masks["default"]);
1978
1979		// Allow setting the utc argument via the mask
1980		if (mask.slice(0, 4) == "UTC:") {
1981			mask = mask.slice(4);
1982			utc = true;
1983		}
1984
1985		var	_ = utc ? "getUTC" : "get",
1986			d = date[_ + "Date"](),
1987			D = date[_ + "Day"](),
1988			m = date[_ + "Month"](),
1989			y = date[_ + "FullYear"](),
1990			H = date[_ + "Hours"](),
1991			M = date[_ + "Minutes"](),
1992			s = date[_ + "Seconds"](),
1993			L = date[_ + "Milliseconds"](),
1994			o = utc ? 0 : date.getTimezoneOffset(),
1995			flags = {
1996				d:    d,
1997				dd:   pad(d),
1998				ddd:  dF.i18n.dayNames[D],
1999				dddd: dF.i18n.dayNames[D + 7],
2000				m:    m + 1,
2001				mm:   pad(m + 1),
2002				mmm:  dF.i18n.monthNames[m],
2003				mmmm: dF.i18n.monthNames[m + 12],
2004				yy:   String(y).slice(2),
2005				yyyy: y,
2006				h:    H % 12 || 12,
2007				hh:   pad(H % 12 || 12),
2008				H:    H,
2009				HH:   pad(H),
2010				M:    M,
2011				MM:   pad(M),
2012				s:    s,
2013				ss:   pad(s),
2014				l:    pad(L, 3),
2015				L:    pad(L > 99 ? Math.round(L / 10) : L),
2016				t:    H < 12 ? "a"  : "p",
2017				tt:   H < 12 ? "am" : "pm",
2018				T:    H < 12 ? "A"  : "P",
2019				TT:   H < 12 ? "AM" : "PM",
2020				Z:    utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
2021				o:    (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
2022				S:    ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10]
2023			};
2024
2025		return mask.replace(token, function ($0) {
2026			return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
2027		});
2028	};
2029}();
2030
2031// Some common format strings
2032dateFormat.masks = {
2033	"default":      "ddd mmm dd yyyy HH:MM:ss",
2034	shortDate:      "m/d/yy",
2035	mediumDate:     "mmm d, yyyy",
2036	longDate:       "mmmm d, yyyy",
2037	fullDate:       "dddd, mmmm d, yyyy",
2038	shortTime:      "h:MM TT",
2039	mediumTime:     "h:MM:ss TT",
2040	longTime:       "h:MM:ss TT Z",
2041	isoDate:        "yyyy-mm-dd",
2042	isoTime:        "HH:MM:ss",
2043	isoDateTime:    "yyyy-mm-dd'T'HH:MM:ss",
2044	isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"
2045};
2046
2047// Internationalization strings
2048dateFormat.i18n = {
2049	dayNames: [
2050		"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat",
2051		"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
2052	],
2053	monthNames: [
2054		"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
2055		"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
2056	]
2057};
2058
2059
2060/*
2061Lightbox for Bootstrap 3 by @ashleydw
2062https://github.com/ashleydw/lightbox
2063
2064License: https://github.com/ashleydw/lightbox/blob/master/LICENSE
2065 */
2066
2067/*
2068Modified for SHC by fskaff on 1/26/17
2069 */
2070
2071(function() {
2072  "use strict";
2073  var $, EkkoLightbox;
2074
2075  $ = jQuery;
2076
2077  EkkoLightbox = function(element, options) {
2078    var content, footer, closeBtn;
2079    this.options = $.extend({
2080      title: null,
2081      footer: null,
2082      remote: null
2083    }, $.fn.ekkoLightbox.defaults, options || {});
2084    this.$element = $(element);
2085    content = '';
2086    this.modal_id = this.options.modal_id ? this.options.modal_id : 'ekkoLightbox-' + Math.floor((Math.random() * 1000) + 1);
2087    closeBtn = '<div class="modal-close"><button class="close" data-dismiss="modal" aria-hidden="true"></button></div>';
2088    footer = '<div class="modal-footer"' + (this.options.footer ? '' : ' style="display:none"') + '>' + this.options.footer + '</div>';
2089    $(document.body).append('<div id="' + this.modal_id + '" class="ekko-lightbox modal fade" tabindex="-1"><div class="modal-dialog"><div class="modal-content">' + closeBtn + '<div class="modal-body"><div class="ekko-lightbox-container"><div></div></div></div>' + footer + '</div></div></div>');
2090    this.modal = $('#' + this.modal_id);
2091    this.modal_dialog = this.modal.find('.modal-dialog').first();
2092    this.modal_content = this.modal.find('.modal-content').first();
2093    this.modal_body = this.modal.find('.modal-body').first();
2094    this.modal_header = this.modal.find('.modal-header').first();
2095    this.modal_footer = this.modal.find('.modal-footer').first();
2096    this.lightbox_container = this.modal_body.find('.ekko-lightbox-container').first();
2097    this.lightbox_body = this.lightbox_container.find('> div:first-child').first();
2098    this.showLoading();
2099    this.modal_arrows = null;
2100    this.border = {
2101      top: parseFloat(this.modal_dialog.css('border-top-width')) + parseFloat(this.modal_content.css('border-top-width')) + parseFloat(this.modal_body.css('border-top-width')),
2102      right: parseFloat(this.modal_dialog.css('border-right-width')) + parseFloat(this.modal_content.css('border-right-width')) + parseFloat(this.modal_body.css('border-right-width')),
2103      bottom: parseFloat(this.modal_dialog.css('border-bottom-width')) + parseFloat(this.modal_content.css('border-bottom-width')) + parseFloat(this.modal_body.css('border-bottom-width')),
2104      left: parseFloat(this.modal_dialog.css('border-left-width')) + parseFloat(this.modal_content.css('border-left-width')) + parseFloat(this.modal_body.css('border-left-width'))
2105    };
2106    this.padding = {
2107      top: parseFloat(this.modal_dialog.css('padding-top')) + parseFloat(this.modal_content.css('padding-top')) + parseFloat(this.modal_body.css('padding-top')),
2108      right: parseFloat(this.modal_dialog.css('padding-right')) + parseFloat(this.modal_content.css('padding-right')) + parseFloat(this.modal_body.css('padding-right')),
2109      bottom: parseFloat(this.modal_dialog.css('padding-bottom')) + parseFloat(this.modal_content.css('padding-bottom')) + parseFloat(this.modal_body.css('padding-bottom')),
2110      left: parseFloat(this.modal_dialog.css('padding-left')) + parseFloat(this.modal_content.css('padding-left')) + parseFloat(this.modal_body.css('padding-left'))
2111    };
2112    this.modal.on('show.bs.modal', this.options.onShow.bind(this)).on('shown.bs.modal', (function(_this) {
2113      return function() {
2114        _this.modal_shown();
2115        return _this.options.onShown.call(_this);
2116      };
2117    })(this)).on('hide.bs.modal', this.options.onHide.bind(this)).on('hidden.bs.modal', (function(_this) {
2118      return function() {
2119        if (_this.gallery) {
2120          $(document).off('keydown.ekkoLightbox');
2121        }
2122        _this.modal.remove();
2123        return _this.options.onHidden.call(_this);
2124      };
2125    })(this)).modal('show', options);
2126    return this.modal;
2127  };
2128
2129  EkkoLightbox.prototype = {
2130    modal_shown: function() {
2131      var video_id;
2132      if (!this.options.remote) {
2133        return this.error('No remote target given');
2134      } else {
2135        this.gallery = this.$element.data('gallery');
2136        if (this.gallery) {
2137          if (this.options.gallery_parent_selector === 'document.body' || this.options.gallery_parent_selector === '') {
2138            this.gallery_items = $(document.body).find('*[data-gallery="' + this.gallery + '"]');
2139          } else {
2140            this.gallery_items = this.$element.parents(this.options.gallery_parent_selector).first().find('*[data-gallery="' + this.gallery + '"]');
2141          }
2142          this.gallery_index = this.gallery_items.index(this.$element);
2143          $(document).on('keydown.ekkoLightbox', this.navigate.bind(this));
2144          if (this.options.directional_arrows && this.gallery_items.length > 1) {
2145            this.lightbox_container.append('<div class="ekko-lightbox-nav-overlay"><a href="#" class="' + this.strip_stops(this.options.left_arrow_class) + '"><div class="' + this.strip_stops(this.options.left_arrow_img_class) + '"></div></a><a href="#" class="' + this.strip_stops(this.options.right_arrow_class) + '"><div class="' + this.strip_stops(this.options.right_arrow_img_class) + '"></div></a></div>');
2146            this.modal_arrows = this.lightbox_container.find('div.ekko-lightbox-nav-overlay').first();
2147            this.lightbox_container.find('a' + this.strip_spaces(this.options.left_arrow_class)).on('click swiperight', (function(_this) {
2148              return function(event) {
2149                event.preventDefault();
2150                return _this.navigate_left();
2151              };
2152            })(this));
2153            this.lightbox_container.find('a' + this.strip_spaces(this.options.right_arrow_class)).on('click swipeleft', (function(_this) {
2154              return function(event) {
2155                event.preventDefault();
2156                return _this.navigate_right();
2157              };
2158            })(this));
2159            this.lightbox_container.find('a' + this.strip_spaces(this.options.left_arrow_class)).on('swipeleft', (function(_this) {
2160              return function(event) {
2161                event.preventDefault();
2162                return _this.navigate_right();
2163              };
2164            })(this));
2165            this.lightbox_container.find('a' + this.strip_spaces(this.options.right_arrow_class)).on('swiperight', (function(_this) {
2166              return function(event) {
2167                event.preventDefault();
2168                return _this.navigate_left();
2169              };
2170            })(this));
2171          }
2172        }
2173        if (this.options.type) {
2174          if (this.options.type === 'image') {
2175            return this.preloadImage(this.options.remote, true);
2176          } else if (this.options.type === 'youtube' && (video_id = this.getYoutubeId(this.options.remote))) {
2177            return this.showYoutubeVideo(video_id);
2178          } else if (this.options.type === 'vimeo') {
2179            return this.showVimeoVideo(this.options.remote);
2180          } else if (this.options.type === 'instagram') {
2181            return this.showInstagramVideo(this.options.remote);
2182          } else if (this.options.type === 'url') {
2183            return this.loadRemoteContent(this.options.remote);
2184          } else if (this.options.type === 'video') {
2185            return this.showVideoIframe(this.options.remote);
2186          } else {
2187            return this.error("Could not detect remote target type. Force the type using data-type=\"image|youtube|vimeo|instagram|url|video\"");
2188          }
2189        } else {
2190          return this.detectRemoteType(this.options.remote);
2191        }
2192      }
2193    },
2194    strip_stops: function(str) {
2195      return str.replace(/\./g, '');
2196    },
2197    strip_spaces: function(str) {
2198      return str.replace(/\s/g, '');
2199    },
2200    isImage: function(str) {
2201      return str.match(/(^data:image\/.*,)|(\.(jp(e|g|eg)|gif|png|bmp|webp|svg)((\?|#).*)?$)/i);
2202    },
2203    isSwf: function(str) {
2204      return str.match(/\.(swf)((\?|#).*)?$/i);
2205    },
2206    getYoutubeId: function(str) {
2207      var match;
2208      match = str.match(/^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=)([^#\&\?]*).*/);
2209      if (match && match[2].length === 11) {
2210        return match[2];
2211      } else {
2212        return false;
2213      }
2214    },
2215    getVimeoId: function(str) {
2216      if (str.indexOf('vimeo') > 0) {
2217        return str;
2218      } else {
2219        return false;
2220      }
2221    },
2222    getInstagramId: function(str) {
2223      if (str.indexOf('instagram') > 0) {
2224        return str;
2225      } else {
2226        return false;
2227      }
2228    },
2229    navigate: function(event) {
2230      event = event || window.event;
2231      if (event.keyCode === 39 || event.keyCode === 37) {
2232        if (event.keyCode === 39) {
2233          return this.navigate_right();
2234        } else if (event.keyCode === 37) {
2235          return this.navigate_left();
2236        }
2237      }
2238    },
2239    navigateTo: function(index) {
2240      var next, src;
2241      if (index < 0 || index > this.gallery_items.length - 1) {
2242        return this;
2243      }
2244      this.showLoading();
2245      this.gallery_index = index;
2246      this.$element = $(this.gallery_items.get(this.gallery_index));
2247      this.updateTitleAndFooter();
2248      src = this.$element.attr('data-remote') || this.$element.attr('href');
2249      this.detectRemoteType(src, this.$element.attr('data-type') || false);
2250      if (this.gallery_index + 1 < this.gallery_items.length) {
2251        next = $(this.gallery_items.get(this.gallery_index + 1), false);
2252        src = next.attr('data-remote') || next.attr('href');
2253        if (next.attr('data-type') === 'image' || this.isImage(src)) {
2254          return this.preloadImage(src, false);
2255        }
2256      }
2257    },
2258    navigate_left: function() {
2259      if (this.gallery_items.length === 1) {
2260        return;
2261      }
2262      if (this.gallery_index === 0) {
2263        this.gallery_index = this.gallery_items.length - 1;
2264      } else {
2265        this.gallery_index--;
2266      }
2267      this.options.onNavigate.call(this, 'left', this.gallery_index);
2268      return this.navigateTo(this.gallery_index);
2269    },
2270    navigate_right: function() {
2271      if (this.gallery_items.length === 1) {
2272        return;
2273      }
2274      if (this.gallery_index === this.gallery_items.length - 1) {
2275        this.gallery_index = 0;
2276      } else {
2277        this.gallery_index++;
2278      }
2279      this.options.onNavigate.call(this, 'right', this.gallery_index);
2280      return this.navigateTo(this.gallery_index);
2281    },
2282    detectRemoteType: function(src, type) {
2283      var video_id;
2284      type = type || false;
2285      if (type === 'image' || this.isImage(src)) {
2286        this.options.type = 'image';
2287        return this.preloadImage(src, true);
2288      } else if (type === 'youtube' || (video_id = this.getYoutubeId(src))) {
2289        this.options.type = 'youtube';
2290        return this.showYoutubeVideo(video_id);
2291      } else if (type === 'vimeo' || (video_id = this.getVimeoId(src))) {
2292        this.options.type = 'vimeo';
2293        return this.showVimeoVideo(video_id);
2294      } else if (type === 'instagram' || (video_id = this.getInstagramId(src))) {
2295        this.options.type = 'instagram';
2296        return this.showInstagramVideo(video_id);
2297      } else if (type === 'video') {
2298        this.options.type = 'video';
2299        return this.showVideoIframe(src);
2300      } else {
2301        this.options.type = 'url';
2302        return this.loadRemoteContent(src);
2303      }
2304    },
2305    updateTitleAndFooter: function() {
2306      var caption, footer, header, title;
2307      header = this.modal_content.find('.modal-header');
2308      footer = this.modal_content.find('.modal-footer');
2309      title = this.$element.data('title') || "";
2310      caption = this.$element.data('footer') || "";
2311      if (title || this.options.always_show_close) {
2312        header.css('display', '').find('.modal-title').html(title || "&nbsp;");
2313      } else {
2314        header.css('display', 'none');
2315      }
2316      if (caption) {
2317        footer.css('display', '').html(caption);
2318      } else {
2319        footer.css('display', 'none');
2320      }
2321      return this;
2322    },
2323    showLoading: function() {
2324      this.lightbox_body.html('<div class="modal-loading">' + this.options.loadingMessage + '</div>');
2325      return this;
2326    },
2327    showYoutubeVideo: function(id) {
2328      var height, rel, width;
2329      if ((this.$element.attr('data-norelated') != null) || this.options.no_related) {
2330        rel = "&rel=0";
2331      } else {
2332        rel = "";
2333      }
2334      width = this.checkDimensions(this.$element.data('width') || 560);
2335      height = width / (560 / 315);
2336      return this.showVideoIframe('//www.youtube.com/embed/' + id + '?badge=0&autoplay=1&html5=1' + rel, width, height);
2337    },
2338    showVimeoVideo: function(id) {
2339      var height, width;
2340      width = this.checkDimensions(this.$element.data('width') || 560);
2341      height = width / (500 / 281);
2342      return this.showVideoIframe(id + '?autoplay=1', width, height);
2343    },
2344    showInstagramVideo: function(id) {
2345      var height, width;
2346      width = this.checkDimensions(this.$element.data('width') || 612);
2347      this.resize(width);
2348      height = width + 80;
2349      this.lightbox_body.html('<iframe width="' + width + '" height="' + height + '" src="' + this.addTrailingSlash(id) + 'embed/" frameborder="0" allowfullscreen></iframe>');
2350      this.options.onContentLoaded.call(this);
2351      if (this.modal_arrows) {
2352        return this.modal_arrows.css('display', 'none');
2353      }
2354    },
2355    showVideoIframe: function(url, width, height) {
2356      height = height || width;
2357      this.resize(width);
2358      this.lightbox_body.html('<div class="embed-responsive embed-responsive-16by9"><iframe width="' + width + '" height="' + height + '" src="' + url + '" frameborder="0" allowfullscreen class="embed-responsive-item"></iframe></div>');
2359      this.options.onContentLoaded.call(this);
2360      if (this.modal_arrows) {
2361        this.modal_arrows.css('display', 'none');
2362      }
2363      return this;
2364    },
2365    loadRemoteContent: function(url) {
2366      var disableExternalCheck, width;
2367      width = this.$element.data('width') || 560;
2368      this.resize(width);
2369      disableExternalCheck = this.$element.data('disableExternalCheck') || false;
2370      if (!disableExternalCheck && !this.isExternal(url)) {
2371        this.lightbox_body.load(url, $.proxy((function(_this) {
2372          return function() {
2373            return _this.$element.trigger('loaded.bs.modal');
2374          };
2375        })(this)));
2376      } else {
2377        this.lightbox_body.html('<iframe width="' + width + '" height="' + width + '" src="' + url + '" frameborder="0" allowfullscreen></iframe>');
2378        this.options.onContentLoaded.call(this);
2379      }
2380      if (this.modal_arrows) {
2381        this.modal_arrows.css('display', 'none');
2382      }
2383      return this;
2384    },
2385    isExternal: function(url) {
2386      var match;
2387      match = url.match(/^([^:\/?#]+:)?(?:\/\/([^\/?#]*))?([^?#]+)?(\?[^#]*)?(#.*)?/);
2388      if (typeof match[1] === "string" && match[1].length > 0 && match[1].toLowerCase() !== location.protocol) {
2389        return true;
2390      }
2391      if (typeof match[2] === "string" && match[2].length > 0 && match[2].replace(new RegExp(":(" + {
2392        "http:": 80,
2393        "https:": 443
2394      }[location.protocol] + ")?$"), "") !== location.host) {
2395        return true;
2396      }
2397      return false;
2398    },
2399    error: function(message) {
2400      this.lightbox_body.html(message);
2401      return this;
2402    },
2403    preloadImage: function(src, onLoadShowImage) {
2404      var img;
2405      img = new Image();
2406      if ((onLoadShowImage == null) || onLoadShowImage === true) {
2407        img.onload = (function(_this) {
2408          return function() {
2409            var image;
2410            image = $('<img />');
2411            image.attr('src', img.src);
2412            image.addClass('img-responsive');
2413            _this.lightbox_body.html(image);
2414            if (_this.modal_arrows) {
2415              _this.modal_arrows.css('display', 'block');
2416            }
2417            return image.load(function() {
2418              if (_this.options.scale_height) {
2419                _this.scaleHeight(img.height, img.width);
2420              } else {
2421                _this.resize(img.width);
2422              }
2423              return _this.options.onContentLoaded.call(_this);
2424            });
2425          };
2426        })(this);
2427        img.onerror = (function(_this) {
2428          return function() {
2429            return _this.error('Failed to load image: ' + src);
2430          };
2431        })(this);
2432      }
2433      img.src = src;
2434      return img;
2435    },
2436    scaleHeight: function(height, width) {
2437      var border_padding, factor, footer_height, header_height, margins, max_height;
2438      header_height = this.modal_header.outerHeight(true) || 0;
2439      footer_height = this.modal_footer.outerHeight(true) || 0;
2440      if (!this.modal_footer.is(':visible')) {
2441        footer_height = 0;
2442      }
2443      if (!this.modal_header.is(':visible')) {
2444        header_height = 0;
2445      }
2446      border_padding = this.border.top + this.border.bottom + this.padding.top + this.padding.bottom;
2447      margins = parseFloat(this.modal_dialog.css('margin-top')) + parseFloat(this.modal_dialog.css('margin-bottom'));
2448      max_height = $(window).height() - border_padding - margins - header_height - footer_height;
2449      factor = Math.min(max_height / height, 1);
2450      this.modal_dialog.css('height', 'auto').css('max-height', max_height);
2451      return this.resize(factor * width);
2452    },
2453    resize: function(width) {
2454      var width_total;
2455      width_total = width + this.border.left + this.padding.left + this.padding.right + this.border.right + 120;
2456      this.modal_dialog.css('width', 'auto').css('max-width', width_total);
2457      this.lightbox_container.find('a').css('line-height', function() {
2458        return $(this).parent().height() + 'px';
2459      });
2460      return this;
2461    },
2462    checkDimensions: function(width) {
2463      var body_width, width_total;
2464      width_total = width + this.border.left + this.padding.left + this.padding.right + this.border.right;
2465      body_width = document.body.clientWidth;
2466      if (width_total > body_width) {
2467        width = this.modal_body.width();
2468      }
2469      return width;
2470    },
2471    close: function() {
2472      return this.modal.modal('hide');
2473    },
2474    addTrailingSlash: function(url) {
2475      if (url.substr(-1) !== '/') {
2476        url += '/';
2477      }
2478      return url;
2479    }
2480  };
2481
2482  $.fn.ekkoLightbox = function(options) {
2483    return this.each(function() {
2484      var $this;
2485      $this = $(this);
2486      options = $.extend({
2487        remote: $this.attr('data-remote') || $this.attr('href'),
2488        gallery_parent_selector: $this.attr('data-parent'),
2489        type: $this.attr('data-type')
2490      }, options, $this.data());
2491      new EkkoLightbox(this, options);
2492      return this;
2493    });
2494  };
2495
2496  $.fn.ekkoLightbox.defaults = {
2497    gallery_parent_selector: 'document.body',
2498    left_arrow_class: '.glyphicon .glyphicon-chevron-left',
2499    right_arrow_class: '.glyphicon .glyphicon-chevron-right',
2500    left_arrow_img_class: '.chevron .chevronleft',
2501    right_arrow_img_class: '.chevron .chevronright',
2502    directional_arrows: true,
2503    type: null,
2504    always_show_close: true,
2505    no_related: false,
2506    scale_height: true,
2507    loadingMessage: 'Loading...',
2508    onShow: function() {},
2509    onShown: function() {},
2510    onHide: function() {},
2511    onHidden: function() {},
2512    onNavigate: function() {},
2513    onContentLoaded: function() {}
2514  };
2515
2516}).call(this);
2517
2518/*
2519Version: 1.0.9
2520
2521Documentation: http://baymard.com/labs/country-selector#documentation
2522
2523Copyright (C) 2011 by Jamie Appleseed, Baymard Institute (baymard.com)
2524
2525Permission is hereby granted, free of charge, to any person obtaining a copy
2526of this software and associated documentation files (the "Software"), to deal
2527in the Software without restriction, including without limitation the rights
2528to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
2529copies of the Software, and to permit persons to whom the Software is
2530furnished to do so, subject to the following conditions:
2531
2532The above copyright notice and this permission notice shall be included in
2533all copies or substantial portions of the Software.
2534
2535THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
2536IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
2537FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
2538AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
2539LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
2540OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
2541THE SOFTWARE.
2542*/
2543(function($){
2544  var shcFilterObj;
2545  var settings = {
2546    'sort': false,
2547    'sort-attr': 'data-priority',
2548    'sort-desc': false,
2549    'autoselect': true,
2550    'alternative-spellings': true,
2551    'alternative-spellings-attr': 'data-alternative-spellings',
2552    'remove-valueless-options': true,
2553    'copy-attributes-to-text-field': true,
2554    'autocomplete-plugin': 'jquery_ui',
2555    'relevancy-sorting': true,
2556    'relevancy-sorting-partial-match-value': 1,
2557    'relevancy-sorting-strict-match-value': 5,
2558    'relevancy-sorting-booster-attr': 'data-relevancy-booster',
2559    'minLength': 0,
2560    'delay': 300,
2561    'autoFocus': false,
2562    handle_invalid_input: function( context ) {
2563      var selected_finder = 'option:selected:first';
2564      if ( context.settings['remove-valueless-options'] ) {
2565        selected_finder = 'option:selected[value!=""]:first';
2566      }
2567      context.$text_field.val( context.$select_field.find( selected_finder ).text() );
2568      var clearX = context.$text_field.parent().find('.trials-x-icon');
2569      if(context.$text_field.val() === '' && !clearX.hasClass('hidden')){
2570          clearX.addClass('hidden');
2571      }else if(context.$text_field.val() !== ""){
2572          clearX.removeClass('hidden');
2573      }
2574    },
2575    handle_select_field: function( $select_field ) {
2576      return $select_field.hide();
2577    },
2578    insert_text_field: function( context ) {
2579      var $text_field = $( '<input type="text"></input>' );
2580      if ( settings['copy-attributes-to-text-field'] ) {
2581        var attrs = {};
2582        var raw_attrs = context.$select_field[0].attributes;
2583        for (var i=0; i < raw_attrs.length; i++) {
2584          var key = raw_attrs[i].nodeName;
2585          var value = raw_attrs[i].nodeValue;
2586          if ( key !== 'name' && key !== 'id' && typeof context.$select_field.attr(key) !== 'undefined' ) {
2587            attrs[key] = value;
2588          }
2589        };
2590        $text_field.attr( attrs );
2591      }
2592      $text_field.blur(function() {
2593        var valid_values = context.$select_field.find('option').map(function(i, option) { return $(option).text(); });
2594        if ( ($.inArray($text_field.val(), valid_values) < 0)
2595              && typeof settings['handle_invalid_input'] === 'function'
2596              && !($(this).parent().hasClass('searchbar-container'))) {
2597          settings['handle_invalid_input'](context);
2598        }
2599      });
2600      // give the input box the ability to select all text on mouse click
2601      if ( context.settings['autoselect'] ) {
2602         $text_field.click( function() {
2603             this.select();
2604            });
2605      }
2606      var selected_finder = 'option:selected:first';
2607      if ( context.settings['remove-valueless-options'] ) {
2608        selected_finder = 'option:selected[value!=""]:first';
2609      }
2610      return $text_field.val( context.$select_field.find( selected_finder ).text() )
2611        .insertAfter( context.$select_field );
2612    },
2613    extract_options: function( $select_field ) {
2614      var options = [];
2615      var $options = $select_field.find('option');
2616      var number_of_options = $options.length;
2617      
2618      // go over each option in the select tag
2619      $options.each(function(){
2620        var $option = $(this);
2621        var option = {
2622          'real-value': $option.attr('value'),
2623          'label': $option.text()
2624        }
2625        if ( settings['remove-valueless-options'] && option['real-value'] === '') {
2626          // skip options without a value
2627        } else {
2628          // prepare the 'matches' string which must be filtered on later
2629          option['matches'] = option['label'];
2630          var alternative_spellings = $option.attr( settings['alternative-spellings-attr'] );
2631          if ( alternative_spellings ) {
2632            option['matches'] += ' ' + alternative_spellings;
2633          }
2634          // give each option a weight paramter for sorting
2635          if ( settings['sort'] ) {
2636            var weight = parseInt( $option.attr( settings['sort-attr'] ), 10 );
2637            if ( weight ) {
2638              option['weight'] = weight;
2639            } else {
2640              option['weight'] = number_of_options;
2641            }
2642          }
2643          // add relevancy score
2644          if ( settings['relevancy-sorting'] ) {
2645            option['relevancy-score'] = 0;
2646            option['relevancy-score-booster'] = 1;
2647            var boost_by = parseFloat( $option.attr( settings['relevancy-sorting-booster-attr'] ) );
2648            if ( boost_by ) {
2649              option['relevancy-score-booster'] = boost_by;
2650            }
2651          }
2652          // add option to combined array
2653          options.push( option );
2654        }
2655      });
2656      // sort the options based on weight
2657      if ( settings['sort'] ) {
2658        if ( settings['sort-desc'] ) {
2659          options.sort( function( a, b ) { return b['weight'] - a['weight']; } );
2660        } else {
2661          options.sort( function( a, b ) { return a['weight'] - b['weight']; } );
2662        }
2663      }
2664      
2665      // return the set of options, each with the following attributes: real-value, label, matches, weight (optional)
2666      return options;
2667    }
2668  };
2669  
2670  var public_methods = {
2671    init: function( customizations ) {
2672      
2673      if ( /msie/.test(navigator.userAgent.toLowerCase()) && parseInt(navigator.appVersion,10) <= 6) {
2674        
2675        return this;
2676        
2677      } else {
2678        
2679        settings = $.extend( settings, customizations );
2680
2681        return this.each(function(){
2682          var $select_field = $(this);
2683          
2684          var context = {
2685            '$select_field': $select_field,
2686            'options': settings['extract_options']( $select_field ),
2687            'settings': settings
2688          };
2689
2690          context['$text_field'] = settings['insert_text_field']( context );
2691          
2692          settings['handle_select_field']( $select_field );
2693          
2694          if ( typeof settings['autocomplete-plugin'] === 'string' ) {
2695            adapters[settings['autocomplete-plugin']]( context );
2696          } else {
2697            settings['autocomplete-plugin']( context );
2698          }
2699        });
2700        
2701      }
2702      
2703    }
2704  };
2705  
2706  var adapters = {
2707    jquery_ui: function( context ) {
2708      // loose matching of search terms
2709      var filter_options = function( term ) {
2710        var split_term = term.split(' ');
2711        var matchers = [];
2712        for (var i=0; i < split_term.length; i++) {
2713          if ( split_term[i].length > 0 ) {
2714            var matcher = {};
2715            matcher['partial'] = new RegExp( $.ui.autocomplete.escapeRegex( split_term[i] ), "i" );
2716            if ( context.settings['relevancy-sorting'] ) {
2717              matcher['strict'] = new RegExp( "^" + $.ui.autocomplete.escapeRegex( split_term[i] ), "i" );
2718            }
2719            matchers.push( matcher );
2720          }
2721        };
2722        
2723        return $.grep( context.options, function( option ) {
2724          var partial_matches = 0;
2725          if ( context.settings['relevancy-sorting'] ) {
2726            var strict_match = false;
2727            var split_option_matches = option.matches.split(' ');
2728          }
2729          for ( var i=0; i < matchers.length; i++ ) {
2730            if ( matchers[i]['partial'].test( option.matches ) ) {
2731              partial_matches++;
2732            }
2733            if ( context.settings['relevancy-sorting'] ) {
2734              for (var q=0; q < split_option_matches.length; q++) {
2735                if ( matchers[i]['strict'].test( split_option_matches[q] ) ) {
2736                  strict_match = true;
2737                  break;
2738                }
2739              };
2740            }
2741          };
2742          if ( context.settings['relevancy-sorting'] ) {
2743            var option_score = 0;
2744            option_score += partial_matches * context.settings['relevancy-sorting-partial-match-value'];
2745            if ( strict_match ) {
2746              option_score += context.settings['relevancy-sorting-strict-match-value'];
2747            }
2748            option_score = option_score * option['relevancy-score-booster'];
2749            option['relevancy-score'] = option_score;
2750          }
2751          return (!term || matchers.length === partial_matches );
2752        });
2753      }
2754      // update the select field value using either selected option or current input in the text field
2755      var update_select_value = function( option ) {
2756        if ( option ) {
2757          if ( context.$select_field.val() !== option['real-value'] ) {
2758            context.$select_field.val( option['real-value'] );
2759            context.$select_field.change();
2760          }
2761        } else {
2762          var option_name = context.$text_field.val().toLowerCase();
2763          var matching_option = { 'real-value': false };
2764          for (var i=0; i < context.options.length; i++) {
2765            if ( option_name === context.options[i]['label'].toLowerCase() ) {
2766              matching_option = context.options[i];
2767              break;
2768            }
2769          };
2770          if ( context.$select_field.val() !== matching_option['real-value'] ) {
2771            context.$select_field.val( matching_option['real-value'] || '' );
2772            context.$select_field.change();
2773          }
2774          if ( matching_option['real-value'] ) {
2775            context.$text_field.val( matching_option['label'] );
2776          }
2777          if ( typeof context.settings['handle_invalid_input'] === 'function' && context.$select_field.val() === '' ) {
2778            context.settings['handle_invalid_input']( context );
2779          }
2780        }
2781      }
2782      // jQuery UI autocomplete settings & behavior
2783      context.$text_field.autocomplete({
2784        'minLength': context.settings['minLength'],
2785        'delay': context.settings['delay'],
2786        'autoFocus': context.settings['autoFocus'],
2787        source: function( request, response ) {
2788          var filtered_options = filter_options( request.term );
2789          var dropdownMenu = null;
2790          if(this.bindings.length > 2 && $(this.bindings[0].parentElement).hasClass('searchbar-container')){
2791              var shcHealthLibrary = {'real-value' : 'Stanford Health Library',
2792                  'label' : 'Stanford Health Library',
2793                  'matches' : 'test',
2794                  'relevancy-score' : -10000,
2795                  'relevancy-score-booster' : -10000};
2796              dropdownMenu = $(this.bindings[1]);
2797              filtered_options[filtered_options.length] = shcHealthLibrary;
2798          }
2799
2800          if ( context.settings['relevancy-sorting'] ) {
2801            filtered_options = filtered_options.sort( function( a, b ) { 
2802            	if (b['relevancy-score'] == a['relevancy-score']) {
2803            		return b['label'] < a['label'] ? 1 : -1;	
2804            	} else {
2805            		return b['relevancy-score'] - a['relevancy-score']; 
2806            	}
2807            } );
2808          }
2809          response( filtered_options );
2810            if(dropdownMenu){
2811              $(dropdownMenu[0]).find('li:last').addClass('searchbar-line');
2812            }
2813        },
2814        select: function( event, ui ) {
2815          update_select_value( ui.item );
2816          $(this).val(ui.item.value);
2817            if(!$(this).parent().hasClass('searchbar-container')){
2818                //roundabout way of binding the select event for filters
2819                shcFilterObj.prepareAutoCompleteFilterRequest(this);
2820            }
2821        },
2822        change: function( event, ui ) {
2823          update_select_value( ui.item );
2824        },
2825        open: function( e, ui ) {
2826            var acData = $(this).data('uiAutocomplete');
2827            acData
2828                .menu
2829                .element
2830                .find('li')
2831                .each(function () {
2832                    var me = $(this);
2833                    var keywords = acData.term.split(' ').join('|');
2834                    me.html(me.text().replace(new RegExp("(" + keywords + ")", "gi"), '<b>$1</b>'));
2835                });
2836        }
2837      });
2838      // force refresh value of select field when form is submitted
2839      context.$text_field.parents('form:first').submit(function(){
2840        update_select_value();
2841      });
2842      // select current value
2843      update_select_value();
2844    }
2845  };
2846
2847  $.fn.selectToAutocomplete = function( method , thatShcFilterObj) {
2848    shcFilterObj = thatShcFilterObj; //roundabout way of binding the select event for filters
2849    if ( public_methods[method] ) {
2850      return public_methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
2851    } else if ( typeof method === 'object' || ! method ) {
2852      return public_methods.init.apply( this, arguments );
2853    } else {
2854      $.error( 'Method ' +  method + ' does not exist on jQuery.fn.selectToAutocomplete' );
2855    }    
2856  };
2857  
2858})(jQuery); 
2859
2860// Plugin @RokoCB :: Return the visible amount of px
2861// of any element currently in viewport.
2862// stackoverflow.com/questions/24768795/
2863;(function($, win) {
2864  $.fn.inViewport = function(cb) {
2865     return this.each(function(i,el){
2866       function visPx(){
2867         var H = $(this).height(),
2868             r = el.getBoundingClientRect(), t=r.top, b=r.bottom;
2869         return cb.call(el, Math.max(0, t>0? H-t : (b<H?b:H)));  
2870       } visPx();
2871       $(win).on("load resize scroll", visPx);
2872     });
2873  };
2874}(jQuery, window));
2875!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(
vendor: 18,994 bytes, line 2875
2875t):e.moment=t()}(this,function(){"use strict";var e,i;function c(){return e.apply(null,arguments)}function o(e){return e instanceof Array||"[object Array]"===Object.prototype.toString.call(e)}function u(e){return null!=e&&"[object Object]"===Object.prototype.toString.call(e)}function l(e){return void 0===e}function h(e){return"number"==typeof e||"[object Number]"===Object.prototype.toString.call(e)}function d(e){return e instanceof Date||"[object Date]"===Object.prototype.toString.call(e)}function f(e,t){var n,s=[];for(n=0;n<e.length;++n)s.push(t(e[n],n));return s}function m(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function _(e,t){for(var n in t)m(t,n)&&(e[n]=t[n]);return m(t,"toString")&&(e.toString=t.toString),m(t,"valueOf")&&(e.valueOf=t.valueOf),e}function y(e,t,n,s){return Tt(e,t,n,s,!0).utc()}function g(e){return null==e._pf&&(e._pf={empty:!1,unusedTokens:[],unusedInput:[],overflow:-2,charsLeftOver:0,nullInput:!1,invalidMonth:null,invalidFormat:!1,userInvalidated:!1,iso:!1,parsedDateParts:[],meridiem:null,rfc2822:!1,weekdayMismatch:!1}),e._pf}function v(e){if(null==e._isValid){var t=g(e),n=i.call(t.parsedDateParts,function(e){return null!=e}),s=!isNaN(e._d.getTime())&&t.overflow<0&&!t.empty&&!t.invalidMonth&&!t.invalidWeekday&&!t.weekdayMismatch&&!t.nullInput&&!t.invalidFormat&&!t.userInvalidated&&(!t.meridiem||t.meridiem&&n);if(e._strict&&(s=s&&0===t.charsLeftOver&&0===t.unusedTokens.length&&void 0===t.bigHour),null!=Object.isFrozen&&Object.isFrozen(e))return s;e._isValid=s}return e._isValid}function p(e){var t=y(NaN);return null!=e?_(g(t),e):g(t).userInvalidated=!0,t}i=Array.prototype.some?Array.prototype.some:function(e){for(var t=Object(this),n=t.length>>>0,s=0;s<n;s++)if(s in t&&e.call(this,t[s],s,t))return!0;return!1};var r=c.momentProperties=[];function w(e,t){var n,s,i;if(l(t._isAMomentObject)||(e._isAMomentObject=t._isAMomentObject),l(t._i)||(e._i=t._i),l(t._f)||(e._f=t._f),l(t._l)||(e._l=t._l),l(t._strict)||(e._strict=t._strict),l(t._tzm)||(e._tzm=t._tzm),l(t._isUTC)||(e._isUTC=t._isUTC),l(t._offset)||(e._offset=t._offset),l(t._pf)||(e._pf=g(t)),l(t._locale)||(e._locale=t._locale),0<r.length)for(n=0;n<r.length;n++)l(i=t[s=r[n]])||(e[s]=i);return e}var t=!1;function M(e){w(this,e),this._d=new Date(null!=e._d?e._d.getTime():NaN),this.isValid()||(this._d=new Date(NaN)),!1===t&&(t=!0,c.updateOffset(this),t=!1)}function k(e){return e instanceof M||null!=e&&null!=e._isAMomentObject}function S(e){return e<0?Math.ceil(e)||0:Math.floor(e)}function D(e){var t=+e,n=0;return 0!==t&&isFinite(t)&&(n=S(t)),n}function a(e,t,n){var s,i=Math.min(e.length,t.length),r=Math.abs(e.length-t.length),a=0;for(s=0;s<i;s++)(n&&e[s]!==t[s]||!n&&D(e[s])!==D(t[s]))&&a++;return a+r}function Y(e){!1===c.suppressDeprecationWarnings&&"undefined"!=typeof console&&console.warn&&console.warn("Deprecation warning: "+e)}function n(i,r){var a=!0;return _(function(){if(null!=c.deprecationHandler&&c.deprecationHandler(null,i),a){for(var e,t=[],n=0;n<arguments.length;n++){if(e="","object"==typeof arguments[n]){for(var s in e+="\n["+n+"] ",arguments[0])e+=s+": "+arguments[0][s]+", ";e=e.slice(0,-2)}else e=arguments[n];t.push(e)}Y(i+"\nArguments: "+Array.prototype.slice.call(t).join("")+"\n"+(new Error).stack),a=!1}return r.apply(this,arguments)},r)}var s,O={};function T(e,t){null!=c.deprecationHandler&&c.deprecationHandler(e,t),O[e]||(Y(t),O[e]=!0)}function b(e){return e instanceof Function||"[object Function]"===Object.prototype.toString.call(e)}function x(e,t){var n,s=_({},e);for(n in t)m(t,n)&&(u(e[n])&&u(t[n])?(s[n]={},_(s[n],e[n]),_(s[n],t[n])):null!=t[n]?s[n]=t[n]:delete s[n]);for(n in e)m(e,n)&&!m(t,n)&&u(e[n])&&(s[n]=_({},s[n]));return s}function P(e){null!=e&&this.set(e)}c.suppressDeprecationWarnings=!1,c.deprecationHandler=null,s=Object.keys?Object.keys:function(e){var t,n=[];for(t in e)m(e,t)&&n.push(t);return n};var W={};function C(e,t){var n=e.toLowerCase();W[n]=W[n+"s"]=W[t]=e}function H(e){return"string"==typeof e?W[e]||W[e.toLowerCase()]:void 0}function R(e){var t,n,s={};for(n in e)m(e,n)&&(t=H(n))&&(s[t]=e[n]);return s}var U={};function F(e,t){U[e]=t}function L(e,t,n){var s=""+Math.abs(e),i=t-s.length;return(0<=e?n?"+":"":"-")+Math.pow(10,Math.max(0,i)).toString().substr(1)+s}var N=/(\[[^\[]*\])|(\\)?([Hh]mm(ss)?|Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Qo?|YYYYYY|YYYYY|YYYY|YY|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|kk?|mm?|ss?|S{1,9}|x|X|zz?|ZZ?|.)/g,G=/(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g,V={},E={};function I(e,t,n,s){var i=s;"string"==typeof s&&(i=function(){return this[s]()}),e&&(E[e]=i),t&&(E[t[0]]=function(){return L(i.apply(this,arguments),t[1],t[2])}),n&&(E[n]=function(){return this.localeData().ordinal(i.apply(this,arguments),e)})}function A(e,t){return e.isValid()?(t=j(t,e.localeData()),V[t]=V[t]||function(s){var e,i,t,r=s.match(N);for(e=0,i=r.length;e<i;e++)E[r[e]]?r[e]=E[r[e]]:r[e]=(t=r[e]).match(/\[[\s\S]/)?t.replace(/^\[|\]$/g,""):t.replace(/\\/g,"");return function(e){var t,n="";for(t=0;t<i;t++)n+=b(r[t])?r[t].call(e,s):r[t];return n}}(t),V[t](e)):e.localeData().invalidDate()}function j(e,t){var n=5;function s(e){return t.longDateFormat(e)||e}for(G.lastIndex=0;0<=n&&G.test(e);)e=e.replace(G,s),G.lastIndex=0,n-=1;return e}var Z=/\d/,z=/\d\d/,$=/\d{3}/,q=/\d{4}/,J=/[+-]?\d{6}/,B=/\d\d?/,Q=/\d\d\d\d?/,X=/\d\d\d\d\d\d?/,K=/\d{1,3}/,ee=/\d{1,4}/,te=/[+-]?\d{1,6}/,ne=/\d+/,se=/[+-]?\d+/,ie=/Z|[+-]\d\d:?\d\d/gi,re=/Z|[+-]\d\d(?::?\d\d)?/gi,ae=/[0-9]{0,256}['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFF07\uFF10-\uFFEF]{1,256}|[\u0600-\u06FF\/]{1,256}(\s*?[\u0600-\u06FF]{1,256}){1,2}/i,oe={};function ue(e,n,s){oe[e]=b(n)?n:function(e,t){return e&&s?s:n}}function le(e,t){return m(oe,e)?oe[e](t._strict,t._locale):new RegExp(he(e.replace("\\","").replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g,function(e,t,n,s,i){return t||n||s||i})))}function he(e){return e.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&")}var de={};function ce(e,n){var t,s=n;for("string"==typeof e&&(e=[e]),h(n)&&(s=function(e,t){t[n]=D(e)}),t=0;t<e.length;t++)de[e[t]]=s}function fe(e,i){ce(e,function(e,t,n,s){n._w=n._w||{},i(e,n._w,n,s)})}var me=0,_e=1,ye=2,ge=3,ve=4,pe=5,we=6,Me=7,ke=8;function Se(e){return De(e)?366:365}function De(e){return e%4==0&&e%100!=0||e%400==0}I("Y",0,0,function(){var e=this.year();return e<=9999?""+e:"+"+e}),I(0,["YY",2],0,function(){return this.year()%100}),I(0,["YYYY",4],0,"year"),I(0,["YYYYY",5],0,"year"),I(0,["YYYYYY",6,!0],0,"year"),C("year","y"),F("year",1),ue("Y",se),ue("YY",B,z),ue("YYYY",ee,q),ue("YYYYY",te,J),ue("YYYYYY",te,J),ce(["YYYYY","YYYYYY"],me),ce("YYYY",function(e,t){t[me]=2===e.length?c.parseTwoDigitYear(e):D(e)}),ce("YY",function(e,t){t[me]=c.parseTwoDigitYear(e)}),ce("Y",function(e,t){t[me]=parseInt(e,10)}),c.parseTwoDigitYear=function(e){return D(e)+(68<D(e)?1900:2e3)};var Ye,Oe=Te("FullYear",!0);function Te(t,n){return function(e){return null!=e?(xe(this,t,e),c.updateOffset(this,n),this):be(this,t)}}function be(e,t){return e.isValid()?e._d["get"+(e._isUTC?"UTC":"")+t]():NaN}function xe(e,t,n){e.isValid()&&!isNaN(n)&&("FullYear"===t&&De(e.year())&&1===e.month()&&29===e.date()?e._d["set"+(e._isUTC?"UTC":"")+t](n,e.month(),Pe(n,e.month())):e._d["set"+(e._isUTC?"UTC":"")+t](n))}function Pe(e,t){if(isNaN(e)||isNaN(t))return NaN;var n,s=(t%(n=12)+n)%n;return e+=(t-s)/12,1===s?De(e)?29:28:31-s%7%2}Ye=Array.prototype.indexOf?Array.prototype.indexOf:function(e){var t;for(t=0;t<this.length;++t)if(this[t]===e)return t;return-1},I("M",["MM",2],"Mo",function(){return this.month()+1}),I("MMM",0,0,function(e){return this.localeData().monthsShort(this,e)}),I("MMMM",0,0,function(e){return this.localeData().months(this,e)}),C("month","M"),F("month",8),ue("M",B),ue("MM",B,z),ue("MMM",function(e,t){return t.monthsShortRegex(e)}),ue("MMMM",function(e,t){return t.monthsRegex(e)}),ce(["M","MM"],function(e,t){t[_e]=D(e)-1}),ce(["MMM","MMMM"],function(e,t,n,s){var i=n._locale.monthsParse(e,s,n._strict);null!=i?t[_e]=i:g(n).invalidMonth=e});var We=/D[oD]?(\[[^\[\]]*\]|\s)+MMMM?/,Ce="January_February_March_April_May_June_July_August_September_October_November_December".split("_");var He="Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_");function Re(e,t){var n;if(!e.isValid())return e;if("string"==typeof t)if(/^\d+$/.test(t))t=D(t);else if(!h(t=e.localeData().monthsParse(t)))return e;return n=Math.min(e.date(),Pe(e.year(),t)),e._d["set"+(e._isUTC?"UTC":"")+"Month"](t,n),e}function Ue(e){return null!=e?(Re(this,e),c.updateOffset(this,!0),this):be(this,"Month")}var Fe=ae;var Le=ae;function Ne(){function e(e,t){return t.length-e.length}var t,n,s=[],i=[],r=[];for(t=0;t<12;t++)n=y([2e3,t]),s.push(this.monthsShort(n,"")),i.push(this.months(n,"")),r.push(this.months(n,"")),r.push(this.monthsShort(n,""));for(s.sort(e),i.sort(e),r.sort(e),t=0;t<12;t++)s[t]=he(s[t]),i[t]=he(i[t]);for(t=0;t<24;t++)r[t]=he(r[t]);this._monthsRegex=new RegExp("^("+r.join("|")+")","i"),this._monthsShortRegex=this._monthsRegex,this._monthsStrictRegex=new RegExp("^("+i.join("|")+")","i"),this._monthsShortStrictRegex=new RegExp("^("+s.join("|")+")","i")}function Ge(e){var t;if(e<100&&0<=e){var n=Array.prototype.slice.call(arguments);n[0]=e+400,t=new Date(Date.UTC.apply(null,n)),isFinite(t.getUTCFullYear())&&t.setUTCFullYear(e)}else t=new Date(Date.UTC.apply(null,arguments));return t}function Ve(e,t,n){var s=7+t-n;return-((7+Ge(e,0,s).getUTCDay()-t)%7)+s-1}function Ee(e,t,n,s,i){var r,a,o=1+7*(t-1)+(7+n-s)%7+Ve(e,s,i);return a=o<=0?Se(r=e-1)+o:o>Se(e)?(r=e+1,o-Se(e)):(r=e,o),{year:r,dayOfYear:a}}function Ie(e,t,n){var s,i,r=Ve(e.year(),t,n),a=Math.floor((e.dayOfYear()-r-1)/7)+1;return a<1?s=a+Ae(i=e.year()-1,t,n):a>Ae(e.year(),t,n)?(s=a-Ae(e.year(),t,n),i=e.year()+1):(i=e.year(),s=a),{week:s,year:i}}function Ae(e,t,n){var s=Ve(e,t,n),i=Ve(e+1,t,n);return(Se(e)-s+i)/7}I("w",["ww",2],"wo","week"),I("W",["WW",2],"Wo","isoWeek"),C("week","w"),C("isoWeek","W"),F("week",5),F("isoWeek",5),ue("w",B),ue("ww",B,z),ue("W",B),ue("WW",B,z),fe(["w","ww","W","WW"],function(e,t,n,s){t[s.substr(0,1)]=D(e)});function je(e,t){return e.slice(t,7).concat(e.slice(0,t))}I("d",0,"do","day"),I("dd",0,0,function(e){return this.localeData().weekdaysMin(this,e)}),I("ddd",0,0,function(e){return this.localeData().weekdaysShort(this,e)}),I("dddd",0,0,function(e){return this.localeData().weekdays(this,e)}),I("e",0,0,"weekday"),I("E",0,0,"isoWeekday"),C("day","d"),C("weekday","e"),C("isoWeekday","E"),F("day",11),F("weekday",11),F("isoWeekday",11),ue("d",B),ue("e",B),ue("E",B),ue("dd",function(e,t){return t.weekdaysMinRegex(e)}),ue("ddd",function(e,t){return t.weekdaysShortRegex(e)}),ue("dddd",function(e,t){return t.weekdaysRegex(e)}),fe(["dd","ddd","dddd"],function(e,t,n,s){var i=n._locale.weekdaysParse(e,s,n._strict);null!=i?t.d=i:g(n).invalidWeekday=e}),fe(["d","e","E"],function(e,t,n,s){t[s]=D(e)});var Ze="Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_");var ze="Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_");var $e="Su_Mo_Tu_We_Th_Fr_Sa".split("_");var qe=ae;var Je=ae;var Be=ae;function Qe(){function e(e,t){return t.length-e.length}var t,n,s,i,r,a=[],o=[],u=[],l=[];for(t=0;t<7;t++)n=y([2e3,1]).day(t),s=this.weekdaysMin(n,""),i=this.weekdaysShort(n,""),r=this.weekdays(n,""),a.push(s),o.push(i),u.push(r),l.push(s),l.push(i),l.push(r);for(a.sort(e),o.sort(e),u.sort(e),l.sort(e),t=0;t<7;t++)o[t]=he(o[t]),u[t]=he(u[t]),l[t]=he(l[t]);this._weekdaysRegex=new RegExp("^("+l.join("|")+")","i"),this._weekdaysShortRegex=this._weekdaysRegex,this._weekdaysMinRegex=this._weekdaysRegex,this._weekdaysStrictRegex=new RegExp("^("+u.join("|")+")","i"),this._weekdaysShortStrictRegex=new RegExp("^("+o.join("|")+")","i"),this._weekdaysMinStrictRegex=new RegExp("^("+a.join("|")+")","i")}function Xe(){return this.hours()%12||12}function Ke(e,t){I(e,0,0,function(){return this.localeData().meridiem(this.hours(),this.minutes(),t)})}function et(e,t){return t._meridiemParse}I("H",["HH",2],0,"hour"),I("h",["hh",2],0,Xe),I("k",["kk",2],0,function(){return this.hours()||24}),I("hmm",0,0,function(){return""+Xe.apply(this)+L(this.minutes(),2)}),I("hmmss",0,0,function(){return""+Xe.apply(this)+L(this.minutes(),2)+L(this.seconds(),2)}),I("Hmm",0,0,function(){return""+this.hours()+L(this.minutes(),2)}),I("Hmmss",0,0,function(){return""+this.hours()+L(this.minutes(),2)+L(this.seconds(),2)}),Ke("a",!0),Ke("A",!1),C("hour","h"),F("hour",13),ue("a",et),ue("A",et),ue("H",B),ue("h",B),ue("k",B),ue("HH",B,z),ue("hh",B,z),ue("kk",B,z),ue("hmm",Q),ue("hmmss",X),ue("Hmm",Q),ue("Hmmss",X),ce(["H","HH"],ge),ce(["k","kk"],function(e,t,n){var s=D(e);t[ge]=24===s?0:s}),ce(["a","A"],function(e,t,n){n._isPm=n._locale.isPM(e),n._meridiem=e}),ce(["h","hh"],function(e,t,n){t[ge]=D(e),g(n).bigHour=!0}),ce("hmm",function(e,t,n){var s=e.length-2;t[ge]=D(e.substr(0,s)),t[ve]=D(e.substr(s)),g(n).bigHour=!0}),ce("hmmss",function(e,t,n){var s=e.length-4,i=e.length-2;t[ge]=D(e.substr(0,s)),t[ve]=D(e.substr(s,2)),t[pe]=D(e.substr(i)),g(n).bigHour=!0}),ce("Hmm",function(e,t,n){var s=e.length-2;t[ge]=D(e.substr(0,s)),t[ve]=D(e.substr(s))}),ce("Hmmss",function(e,t,n){var s=e.length-4,i=e.length-2;t[ge]=D(e.substr(0,s)),t[ve]=D(e.substr(s,2)),t[pe]=D(e.substr(i))});var tt,nt=Te("Hours",!0),st={calendar:{sameDay:"[Today at] LT",nextDay:"[Tomorrow at] LT",nextWeek:"dddd [at] LT",lastDay:"[Yesterday at] LT",lastWeek:"[Last] dddd [at] LT",sameElse:"L"},longDateFormat:{LTS:"h:mm:ss A",LT:"h:mm A",L:"MM/DD/YYYY",LL:"MMMM D, YYYY",LLL:"MMMM D, YYYY h:mm A",LLLL:"dddd, MMMM D, YYYY h:mm A"},invalidDate:"Invalid date",ordinal:"%d",dayOfMonthOrdinalParse:/\d{1,2}/,relativeTime:{future:"in %s",past:"%s ago",s:"a few seconds",ss:"%d seconds",m:"a minute",mm:"%d minutes",h:"an hour",hh:"%d hours",d:"a day",dd:"%d days",M:"a month",MM:"%d months",y:"a year",yy:"%d years"},months:Ce,monthsShort:He,week:{dow:0,doy:6},weekdays:Ze,weekdaysMin:$e,weekdaysShort:ze,meridiemParse:/[ap]\.?m?\.?/i},it={},rt={};function at(e){return e?e.toLowerCase().replace("_","-"):e}function ot(e){var t=null;if(!it[e]&&"undefined"!=typeof module&&module&&module.exports)try{t=tt._abbr,require("./locale/"+e),ut(t)}catch(e){}return it[e]}function ut(e,t){var n;return e&&((n=l(t)?ht(e):lt(e,t))?tt=n:"undefined"!=typeof console&&console.warn&&console.warn("Locale "+e+" not found. Did you forget to load it?")),tt._abbr}function lt(e,t){if(null===t)return delete it[e],null;var n,s=st;if(t.abbr=e,null!=it[e])T("defineLocaleOverride","use moment.updateLocale(localeName, config) to change an existing locale. moment.defineLocale(localeName, config) should only be used for creating a new locale See http://momentjs.com/guides/#/warnings/define-locale/ for more info."),s=it[e]._config;else if(null!=t.parentLocale)if(null!=it[t.parentLocale])s=it[t.parentLocale]._config;else{if(null==(n=ot(t.parentLocale)))return rt[t.parentLocale]||(rt[t.parentLocale]=[]),rt[t.parentLocale].push({name:e,config:t}),null;s=n._config}return it[e]=new P(x(s,t)),rt[e]&&rt[e].forEach(function(e){lt(e.name,e.config)}),ut(e),it[e]}function ht(e){var t;if(e&&e._locale&&e._locale._abbr&&(e=e._locale._abbr),!e)return tt;if(!o(e)){if(t=ot(e))return t;e=[e]}return function(e){for(var t,n,s,i,r=0;r<e.length;){for(t=(i=at(e[r]).split("-")).length,n=(n=at(e[r+1]))?n.split("-"):null;0<t;){if(s=ot(i.slice(0,t).join("-")))return s;if(n&&n.length>=t&&a(i,n,!0)>=t-1)break;t--}r++}return tt}(e)}function dt(e){var t,n=e._a;return n&&-2===g(e).overflow&&(t=n[_e]<0||11<n[_e]?_e:n[ye]<1||n[ye]>Pe(n[me],n[_e])?ye:n[ge]<0||24<n[ge]||24===n[ge]&&(0!==n[ve]||0!==n[pe]||0!==n[we])?ge:n[ve]<0||59<n[ve]?ve:n[pe]<0||59<n[pe]?pe:n[we]<0||999<n[we]?we:-1,g(e)._overflowDayOfYear&&(t<me||ye<t)&&(t=ye),g(e)._overflowWeeks&&-1===t&&(t=Me),g(e)._overflowWeekday&&-1===t&&(t=ke),g(e).overflow=t),e}function ct(e,t,n){return null!=e?e:null!=t?t:n}function ft(e){var t,n,s,i,r,a=[];if(!e._d){var o,u;for(o=e,u=new Date(c.now()),s=o._useUTC?[u.getUTCFullYear(),u.getUTCMonth(),u.getUTCDate()]:[u.getFullYear(),u.getMonth(),u.getDate()],e._w&&null==e._a[ye]&&null==e._a[_e]&&function(e){var t,n,s,i,r,a,o,u;if(null!=(t=e._w).GG||null!=t.W||null!=t.E)r=1,a=4,n=ct(t.GG,e._a[me],Ie(bt(),1,4).year),s=ct(t.W,1),((i=ct(t.E,1))<1||7<i)&&(u=!0);else{r=e._locale._week.dow,a=e._locale._week.doy;var l=Ie(bt(),r,a);n=ct(t.gg,e._a[me],l.year),s=ct(t.w,l.week),null!=t.d?((i=t.d)<0||6<i)&&(u=!0):null!=t.e?(i=t.e+r,(t.e<0||6<t.e)&&(u=!0)):i=r}s<1||s>Ae(n,r,a)?g(e)._overflowWeeks=!0:null!=u?g(e)._overflowWeekday=!0:(o=Ee(n,s,i,r,a),e._a[me]=o.year,e._dayOfYear=o.dayOfYear)}(e),null!=e._dayOfYear&&(r=ct(e._a[me],s[me]),(e._dayOfYear>Se(r)||0===e._dayOfYear)&&(g(e)._overflowDayOfYear=!0),n=Ge(r,0,e._dayOfYear),e._a[_e]=n.getUTCMonth(),e._a[ye]=n.getUTCDate()),t=0;t<3&&null==e._a[t];++t)e._a[t]=a[t]=s[t];for(;t<7;t++)e._a[t]=a[t]=null==e._a[t]?2===t?1:0:e._a[t];24===e._a[ge]&&0===e._a[ve]&&0===e._a[pe]&&0===e._a[we]&&(e._nextDay=!0,e._a[ge]=0),e._d=(e._useUTC?Ge:function(e,t,n,s,i,r,a){var o;return e<100&&0<=e?(o=new Date(e+400,t,n,s,i,r,a),isFinite(o.getFullYear())&&o.setFullYear(e)):o=new Date(e,t,n,s,i,r,a),o}).apply(null,a),i=e._useUTC?e._d.getUTCDay():e._d.getDay(),null!=e._tzm&&e._d.setUTCMinutes(e._d.getUTCMinutes()-e._tzm),e._nextDay&&(e._a[ge]=24),e._w&&void 0!==e._w.d&&e._w.d!==i&&(g(e).weekdayMismatch=!0)}}var mt=/^\s*((?:[+-]\d{6}|\d{4})-(?:\d\d-\d\d|W\d\d-\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?::\d\d(?::\d\d(?:[.,]\d+)?)?)?)([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?$/,_t=/^\s*((?:[+-]\d{6}|\d{4})(?:\d\d\d\d|W\d\d\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?:\d\d(?:\d\d(?:[.,]\d+)?)?)?)([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?$/,yt=/Z|[+-]\d\d(?::?\d\d)?/,gt=[["YYYYYY-MM-DD",/[+-]\d{6}-\d\d-\d\d/],["YYYY-MM-DD",/\d{4}-\d\d-\d\d/],["GGGG-[W]WW-E",/\d{4}-W\d\d-\d/],["GGGG-[W]WW",/\d{4}-W\d\d/,!1],["YYYY-DDD",/\d{4}-\d{3}/],["YYYY-MM",/\d{4}-\d\d/,!1],["YYYYYYMMDD",/[+-]\d{10}/],["YYYYMMDD",/\d{8}/],["GGGG[W]WWE",/\d{4}W\d{3}/],["GGGG[W]WW",/\d{4}W\d{2}/,!1],["YYYYDDD",/\d{7}/]],vt=[["HH:mm:ss.SSSS",/\d\d:\d\d:\d\d\.\d+/],["HH:mm:ss,SSSS",/\d\d:\d\d:\d\d,\d+/],["HH:mm:ss",/\d\d:\d\d:\d\d/],["HH:mm",/\d\d:\d\d/],["HHmmss.SSSS",/\d\d\d\d\d\d\.\d+/],["HHmmss,SSSS",/\d\d\d\d\d\d,\d+/],["HHmmss",/\d\d\d\d\d\d/],["HHmm",/\d\d\d\d/],["HH",/\d\d/]],pt=/^\/?Date\((\-?\d+)/i;function wt(e){var t,n,s,i,r,a,o=e._i,u=mt.exec(o)||_t.exec(o);if(u){for(g(e).iso=!0,t=0,n=gt.length;t<n;t++)if(gt[t][1].exec(u[1])){i=gt[t][0],s=!1!==gt[t][2];break}if(null==i)return void(e._isValid=!1);if(u[3]){for(t=0,n=vt.length;t<n;t++)if(vt[t][1].exec(u[3])){r=(u[2]||" ")+vt[t][0];break}if(null==r)return void(e._isValid=!1)}if(!s&&null!=r)return void(e._isValid=!1);if(u[4]){if(!yt.exec(u[4]))return void(e._isValid=!1);a="Z"}e._f=i+(r||"")+(a||""),Yt(e)}else e._isValid=!1}var Mt=/^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),?\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|([+-]\d{4}))$/;function kt(e,t,n,s,i,r){var a=[function(e){var t=parseInt(e,10);
vendor: 34,198 bytes, line 2875
2875{if(t<=49)return 2e3+t;if(t<=999)return 1900+t}return t}(e),He.indexOf(t),parseInt(n,10),parseInt(s,10),parseInt(i,10)];return r&&a.push(parseInt(r,10)),a}var St={UT:0,GMT:0,EDT:-240,EST:-300,CDT:-300,CST:-360,MDT:-360,MST:-420,PDT:-420,PST:-480};function Dt(e){var t,n,s,i=Mt.exec(e._i.replace(/\([^)]*\)|[\n\t]/g," ").replace(/(\s\s+)/g," ").replace(/^\s\s*/,"").replace(/\s\s*$/,""));if(i){var r=kt(i[4],i[3],i[2],i[5],i[6],i[7]);if(t=i[1],n=r,s=e,t&&ze.indexOf(t)!==new Date(n[0],n[1],n[2]).getDay()&&(g(s).weekdayMismatch=!0,!(s._isValid=!1)))return;e._a=r,e._tzm=function(e,t,n){if(e)return St[e];if(t)return 0;var s=parseInt(n,10),i=s%100;return(s-i)/100*60+i}(i[8],i[9],i[10]),e._d=Ge.apply(null,e._a),e._d.setUTCMinutes(e._d.getUTCMinutes()-e._tzm),g(e).rfc2822=!0}else e._isValid=!1}function Yt(e){if(e._f!==c.ISO_8601)if(e._f!==c.RFC_2822){e._a=[],g(e).empty=!0;var t,n,s,i,r,a,o,u,l=""+e._i,h=l.length,d=0;for(s=j(e._f,e._locale).match(N)||[],t=0;t<s.length;t++)i=s[t],(n=(l.match(le(i,e))||[])[0])&&(0<(r=l.substr(0,l.indexOf(n))).length&&g(e).unusedInput.push(r),l=l.slice(l.indexOf(n)+n.length),d+=n.length),E[i]?(n?g(e).empty=!1:g(e).unusedTokens.push(i),a=i,u=e,null!=(o=n)&&m(de,a)&&de[a](o,u._a,u,a)):e._strict&&!n&&g(e).unusedTokens.push(i);g(e).charsLeftOver=h-d,0<l.length&&g(e).unusedInput.push(l),e._a[ge]<=12&&!0===g(e).bigHour&&0<e._a[ge]&&(g(e).bigHour=void 0),g(e).parsedDateParts=e._a.slice(0),g(e).meridiem=e._meridiem,e._a[ge]=function(e,t,n){var s;if(null==n)return t;return null!=e.meridiemHour?e.meridiemHour(t,n):(null!=e.isPM&&((s=e.isPM(n))&&t<12&&(t+=12),s||12!==t||(t=0)),t)}(e._locale,e._a[ge],e._meridiem),ft(e),dt(e)}else Dt(e);else wt(e)}function Ot(e){var t,n,s,i,r=e._i,a=e._f;return e._locale=e._locale||ht(e._l),null===r||void 0===a&&""===r?p({nullInput:!0}):("string"==typeof r&&(e._i=r=e._locale.preparse(r)),k(r)?new M(dt(r)):(d(r)?e._d=r:o(a)?function(e){var t,n,s,i,r;if(0===e._f.length)return g(e).invalidFormat=!0,e._d=new Date(NaN);for(i=0;i<e._f.length;i++)r=0,t=w({},e),null!=e._useUTC&&(t._useUTC=e._useUTC),t._f=e._f[i],Yt(t),v(t)&&(r+=g(t).charsLeftOver,r+=10*g(t).unusedTokens.length,g(t).score=r,(null==s||r<s)&&(s=r,n=t));_(e,n||t)}(e):a?Yt(e):l(n=(t=e)._i)?t._d=new Date(c.now()):d(n)?t._d=new Date(n.valueOf()):"string"==typeof n?(s=t,null===(i=pt.exec(s._i))?(wt(s),!1===s._isValid&&(delete s._isValid,Dt(s),!1===s._isValid&&(delete s._isValid,c.createFromInputFallback(s)))):s._d=new Date(+i[1])):o(n)?(t._a=f(n.slice(0),function(e){return parseInt(e,10)}),ft(t)):u(n)?function(e){if(!e._d){var t=R(e._i);e._a=f([t.year,t.month,t.day||t.date,t.hour,t.minute,t.second,t.millisecond],function(e){return e&&parseInt(e,10)}),ft(e)}}(t):h(n)?t._d=new Date(n):c.createFromInputFallback(t),v(e)||(e._d=null),e))}function Tt(e,t,n,s,i){var r,a={};return!0!==n&&!1!==n||(s=n,n=void 0),(u(e)&&function(e){if(Object.getOwnPropertyNames)return 0===Object.getOwnPropertyNames(e).length;var t;for(t in e)if(e.hasOwnProperty(t))return!1;return!0}(e)||o(e)&&0===e.length)&&(e=void 0),a._isAMomentObject=!0,a._useUTC=a._isUTC=i,a._l=n,a._i=e,a._f=t,a._strict=s,(r=new M(dt(Ot(a))))._nextDay&&(r.add(1,"d"),r._nextDay=void 0),r}function bt(e,t,n,s){return Tt(e,t,n,s,!1)}c.createFromInputFallback=n("value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are discouraged and will be removed in an upcoming major release. Please refer to http://momentjs.com/guides/#/warnings/js-date/ for more info.",function(e){e._d=new Date(e._i+(e._useUTC?" UTC":""))}),c.ISO_8601=function(){},c.RFC_2822=function(){};var xt=n("moment().min is deprecated, use moment.max instead. http://momentjs.com/guides/#/warnings/min-max/",function(){var e=bt.apply(null,arguments);return this.isValid()&&e.isValid()?e<this?this:e:p()}),Pt=n("moment().max is deprecated, use moment.min instead. http://momentjs.com/guides/#/warnings/min-max/",function(){var e=bt.apply(null,arguments);return this.isValid()&&e.isValid()?this<e?this:e:p()});function Wt(e,t){var n,s;if(1===t.length&&o(t[0])&&(t=t[0]),!t.length)return bt();for(n=t[0],s=1;s<t.length;++s)t[s].isValid()&&!t[s][e](n)||(n=t[s]);return n}var Ct=["year","quarter","month","week","day","hour","minute","second","millisecond"];function Ht(e){var t=R(e),n=t.year||0,s=t.quarter||0,i=t.month||0,r=t.week||t.isoWeek||0,a=t.day||0,o=t.hour||0,u=t.minute||0,l=t.second||0,h=t.millisecond||0;this._isValid=function(e){for(var t in e)if(-1===Ye.call(Ct,t)||null!=e[t]&&isNaN(e[t]))return!1;for(var n=!1,s=0;s<Ct.length;++s)if(e[Ct[s]]){if(n)return!1;parseFloat(e[Ct[s]])!==D(e[Ct[s]])&&(n=!0)}return!0}(t),this._milliseconds=+h+1e3*l+6e4*u+1e3*o*60*60,this._days=+a+7*r,this._months=+i+3*s+12*n,this._data={},this._locale=ht(),this._bubble()}function Rt(e){return e instanceof Ht}function Ut(e){return e<0?-1*Math.round(-1*e):Math.round(e)}function Ft(e,n){I(e,0,0,function(){var e=this.utcOffset(),t="+";return e<0&&(e=-e,t="-"),t+L(~~(e/60),2)+n+L(~~e%60,2)})}Ft("Z",":"),Ft("ZZ",""),ue("Z",re),ue("ZZ",re),ce(["Z","ZZ"],function(e,t,n){n._useUTC=!0,n._tzm=Nt(re,e)});var Lt=/([\+\-]|\d\d)/gi;function Nt(e,t){var n=(t||"").match(e);if(null===n)return null;var s=((n[n.length-1]||[])+"").match(Lt)||["-",0,0],i=60*s[1]+D(s[2]);return 0===i?0:"+"===s[0]?i:-i}function Gt(e,t){var n,s;return t._isUTC?(n=t.clone(),s=(k(e)||d(e)?e.valueOf():bt(e).valueOf())-n.valueOf(),n._d.setTime(n._d.valueOf()+s),c.updateOffset(n,!1),n):bt(e).local()}function Vt(e){return 15*-Math.round(e._d.getTimezoneOffset()/15)}function Et(){return!!this.isValid()&&(this._isUTC&&0===this._offset)}c.updateOffset=function(){};var It=/^(\-|\+)?(?:(\d*)[. ])?(\d+)\:(\d+)(?:\:(\d+)(\.\d*)?)?$/,At=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/;function jt(e,t){var n,s,i,r=e,a=null;return Rt(e)?r={ms:e._milliseconds,d:e._days,M:e._months}:h(e)?(r={},t?r[t]=e:r.milliseconds=e):(a=It.exec(e))?(n="-"===a[1]?-1:1,r={y:0,d:D(a[ye])*n,h:D(a[ge])*n,m:D(a[ve])*n,s:D(a[pe])*n,ms:D(Ut(1e3*a[we]))*n}):(a=At.exec(e))?(n="-"===a[1]?-1:1,r={y:Zt(a[2],n),M:Zt(a[3],n),w:Zt(a[4],n),d:Zt(a[5],n),h:Zt(a[6],n),m:Zt(a[7],n),s:Zt(a[8],n)}):null==r?r={}:"object"==typeof r&&("from"in r||"to"in r)&&(i=function(e,t){var n;if(!e.isValid()||!t.isValid())return{milliseconds:0,months:0};t=Gt(t,e),e.isBefore(t)?n=zt(e,t):((n=zt(t,e)).milliseconds=-n.milliseconds,n.months=-n.months);return n}(bt(r.from),bt(r.to)),(r={}).ms=i.milliseconds,r.M=i.months),s=new Ht(r),Rt(e)&&m(e,"_locale")&&(s._locale=e._locale),s}function Zt(e,t){var n=e&&parseFloat(e.replace(",","."));return(isNaN(n)?0:n)*t}function zt(e,t){var n={};return n.months=t.month()-e.month()+12*(t.year()-e.year()),e.clone().add(n.months,"M").isAfter(t)&&--n.months,n.milliseconds=+t-+e.clone().add(n.months,"M"),n}function $t(s,i){return function(e,t){var n;return null===t||isNaN(+t)||(T(i,"moment()."+i+"(period, number) is deprecated. Please use moment()."+i+"(number, period). See http://momentjs.com/guides/#/warnings/add-inverted-param/ for more info."),n=e,e=t,t=n),qt(this,jt(e="string"==typeof e?+e:e,t),s),this}}function qt(e,t,n,s){var i=t._milliseconds,r=Ut(t._days),a=Ut(t._months);e.isValid()&&(s=null==s||s,a&&Re(e,be(e,"Month")+a*n),r&&xe(e,"Date",be(e,"Date")+r*n),i&&e._d.setTime(e._d.valueOf()+i*n),s&&c.updateOffset(e,r||a))}jt.fn=Ht.prototype,jt.invalid=function(){return jt(NaN)};var Jt=$t(1,"add"),Bt=$t(-1,"subtract");function Qt(e,t){var n=12*(t.year()-e.year())+(t.month()-e.month()),s=e.clone().add(n,"months");return-(n+(t-s<0?(t-s)/(s-e.clone().add(n-1,"months")):(t-s)/(e.clone().add(n+1,"months")-s)))||0}function Xt(e){var t;return void 0===e?this._locale._abbr:(null!=(t=ht(e))&&(this._locale=t),this)}c.defaultFormat="YYYY-MM-DDTHH:mm:ssZ",c.defaultFormatUtc="YYYY-MM-DDTHH:mm:ss[Z]";var Kt=n("moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.",function(e){return void 0===e?this.localeData():this.locale(e)});function en(){return this._locale}var tn=126227808e5;function nn(e,t){return(e%t+t)%t}function sn(e,t,n){return e<100&&0<=e?new Date(e+400,t,n)-tn:new Date(e,t,n).valueOf()}function rn(e,t,n){return e<100&&0<=e?Date.UTC(e+400,t,n)-tn:Date.UTC(e,t,n)}function an(e,t){I(0,[e,e.length],0,t)}function on(e,t,n,s,i){var r;return null==e?Ie(this,s,i).year:((r=Ae(e,s,i))<t&&(t=r),function(e,t,n,s,i){var r=Ee(e,t,n,s,i),a=Ge(r.year,0,r.dayOfYear);return this.year(a.getUTCFullYear()),this.month(a.getUTCMonth()),this.date(a.getUTCDate()),this}.call(this,e,t,n,s,i))}I(0,["gg",2],0,function(){return this.weekYear()%100}),I(0,["GG",2],0,function(){return this.isoWeekYear()%100}),an("gggg","weekYear"),an("ggggg","weekYear"),an("GGGG","isoWeekYear"),an("GGGGG","isoWeekYear"),C("weekYear","gg"),C("isoWeekYear","GG"),F("weekYear",1),F("isoWeekYear",1),ue("G",se),ue("g",se),ue("GG",B,z),ue("gg",B,z),ue("GGGG",ee,q),ue("gggg",ee,q),ue("GGGGG",te,J),ue("ggggg",te,J),fe(["gggg","ggggg","GGGG","GGGGG"],function(e,t,n,s){t[s.substr(0,2)]=D(e)}),fe(["gg","GG"],function(e,t,n,s){t[s]=c.parseTwoDigitYear(e)}),I("Q",0,"Qo","quarter"),C("quarter","Q"),F("quarter",7),ue("Q",Z),ce("Q",function(e,t){t[_e]=3*(D(e)-1)}),I("D",["DD",2],"Do","date"),C("date","D"),F("date",9),ue("D",B),ue("DD",B,z),ue("Do",function(e,t){return e?t._dayOfMonthOrdinalParse||t._ordinalParse:t._dayOfMonthOrdinalParseLenient}),ce(["D","DD"],ye),ce("Do",function(e,t){t[ye]=D(e.match(B)[0])});var un=Te("Date",!0);I("DDD",["DDDD",3],"DDDo","dayOfYear"),C("dayOfYear","DDD"),F("dayOfYear",4),ue("DDD",K),ue("DDDD",$),ce(["DDD","DDDD"],function(e,t,n){n._dayOfYear=D(e)}),I("m",["mm",2],0,"minute"),C("minute","m"),F("minute",14),ue("m",B),ue("mm",B,z),ce(["m","mm"],ve);var ln=Te("Minutes",!1);I("s",["ss",2],0,"second"),C("second","s"),F("second",15),ue("s",B),ue("ss",B,z),ce(["s","ss"],pe);var hn,dn=Te("Seconds",!1);for(I("S",0,0,function(){return~~(this.millisecond()/100)}),I(0,["SS",2],0,function(){return~~(this.millisecond()/10)}),I(0,["SSS",3],0,"millisecond"),I(0,["SSSS",4],0,function(){return 10*this.millisecond()}),I(0,["SSSSS",5],0,function(){return 100*this.millisecond()}),I(0,["SSSSSS",6],0,function(){return 1e3*this.millisecond()}),I(0,["SSSSSSS",7],0,function(){return 1e4*this.millisecond()}),I(0,["SSSSSSSS",8],0,function(){return 1e5*this.millisecond()}),I(0,["SSSSSSSSS",9],0,function(){return 1e6*this.millisecond()}),C("millisecond","ms"),F("millisecond",16),ue("S",K,Z),ue("SS",K,z),ue("SSS",K,$),hn="SSSS";hn.length<=9;hn+="S")ue(hn,ne);function cn(e,t){t[we]=D(1e3*("0."+e))}for(hn="S";hn.length<=9;hn+="S")ce(hn,cn);var fn=Te("Milliseconds",!1);I("z",0,0,"zoneAbbr"),I("zz",0,0,"zoneName");var mn=M.prototype;function _n(e){return e}mn.add=Jt,mn.calendar=function(e,t){var n=e||bt(),s=Gt(n,this).startOf("day"),i=c.calendarFormat(this,s)||"sameElse",r=t&&(b(t[i])?t[i].call(this,n):t[i]);return this.format(r||this.localeData().calendar(i,this,bt(n)))},mn.clone=function(){return new M(this)},mn.diff=function(e,t,n){var s,i,r;if(!this.isValid())return NaN;if(!(s=Gt(e,this)).isValid())return NaN;switch(i=6e4*(s.utcOffset()-this.utcOffset()),t=H(t)){case"year":r=Qt(this,s)/12;break;case"month":r=Qt(this,s);break;case"quarter":r=Qt(this,s)/3;break;case"second":r=(this-s)/1e3;break;case"minute":r=(this-s)/6e4;break;case"hour":r=(this-s)/36e5;break;case"day":r=(this-s-i)/864e5;break;case"week":r=(this-s-i)/6048e5;break;default:r=this-s}return n?r:S(r)},mn.endOf=function(e){var t;if(void 0===(e=H(e))||"millisecond"===e||!this.isValid())return this;var n=this._isUTC?rn:sn;switch(e){case"year":t=n(this.year()+1,0,1)-1;break;case"quarter":t=n(this.year(),this.month()-this.month()%3+3,1)-1;break;case"month":t=n(this.year(),this.month()+1,1)-1;break;case"week":t=n(this.year(),this.month(),this.date()-this.weekday()+7)-1;break;case"isoWeek":t=n(this.year(),this.month(),this.date()-(this.isoWeekday()-1)+7)-1;break;case"day":case"date":t=n(this.year(),this.month(),this.date()+1)-1;break;case"hour":t=this._d.valueOf(),t+=36e5-nn(t+(this._isUTC?0:6e4*this.utcOffset()),36e5)-1;break;case"minute":t=this._d.valueOf(),t+=6e4-nn(t,6e4)-1;break;case"second":t=this._d.valueOf(),t+=1e3-nn(t,1e3)-1;break}return this._d.setTime(t),c.updateOffset(this,!0),this},mn.format=function(e){e||(e=this.isUtc()?c.defaultFormatUtc:c.defaultFormat);var t=A(this,e);return this.localeData().postformat(t)},mn.from=function(e,t){return this.isValid()&&(k(e)&&e.isValid()||bt(e).isValid())?jt({to:this,from:e}).locale(this.locale()).humanize(!t):this.localeData().invalidDate()},mn.fromNow=function(e){return this.from(bt(),e)},mn.to=function(e,t){return this.isValid()&&(k(e)&&e.isValid()||bt(e).isValid())?jt({from:this,to:e}).locale(this.locale()).humanize(!t):this.localeData().invalidDate()},mn.toNow=function(e){return this.to(bt(),e)},mn.get=function(e){return b(this[e=H(e)])?this[e]():this},mn.invalidAt=function(){return g(this).overflow},mn.isAfter=function(e,t){var n=k(e)?e:bt(e);return!(!this.isValid()||!n.isValid())&&("millisecond"===(t=H(t)||"millisecond")?this.valueOf()>n.valueOf():n.valueOf()<this.clone().startOf(t).valueOf())},mn.isBefore=function(e,t){var n=k(e)?e:bt(e);return!(!this.isValid()||!n.isValid())&&("millisecond"===(t=H(t)||"millisecond")?this.valueOf()<n.valueOf():this.clone().endOf(t).valueOf()<n.valueOf())},mn.isBetween=function(e,t,n,s){var i=k(e)?e:bt(e),r=k(t)?t:bt(t);return!!(this.isValid()&&i.isValid()&&r.isValid())&&("("===(s=s||"()")[0]?this.isAfter(i,n):!this.isBefore(i,n))&&(")"===s[1]?this.isBefore(r,n):!this.isAfter(r,n))},mn.isSame=function(e,t){var n,s=k(e)?e:bt(e);return!(!this.isValid()||!s.isValid())&&("millisecond"===(t=H(t)||"millisecond")?this.valueOf()===s.valueOf():(n=s.valueOf(),this.clone().startOf(t).valueOf()<=n&&n<=this.clone().endOf(t).valueOf()))},mn.isSameOrAfter=function(e,t){return this.isSame(e,t)||this.isAfter(e,t)},mn.isSameOrBefore=function(e,t){return this.isSame(e,t)||this.isBefore(e,t)},mn.isValid=function(){return v(this)},mn.lang=Kt,mn.locale=Xt,mn.localeData=en,mn.max=Pt,mn.min=xt,mn.parsingFlags=function(){return _({},g(this))},mn.set=function(e,t){if("object"==typeof e)for(var n=function(e){var t=[];for(var n in e)t.push({unit:n,priority:U[n]});return t.sort(function(e,t){return e.priority-t.priority}),t}(e=R(e)),s=0;s<n.length;s++)this[n[s].unit](e[n[s].unit]);else if(b(this[e=H(e)]))return this[e](t);return this},mn.startOf=function(e){var t;if(void 0===(e=H(e))||"millisecond"===e||!this.isValid())return this;var n=this._isUTC?rn:sn;switch(e){case"year":t=n(this.year(),0,1);break;case"quarter":t=n(this.year(),this.month()-this.month()%3,1);break;case"month":t=n(this.year(),this.month(),1);break;case"week":t=n(this.year(),this.month(),this.date()-this.weekday());break;case"isoWeek":t=n(this.year(),this.month(),this.date()-(this.isoWeekday()-1));break;case"day":case"date":t=n(this.year(),this.month(),this.date());break;case"hour":t=this._d.valueOf(),t-=nn(t+(this._isUTC?0:6e4*this.utcOffset()),36e5);break;case"minute":t=this._d.valueOf(),t-=nn(t,6e4);break;case"second":t=this._d.valueOf(),t-=nn(t,1e3);break}return this._d.setTime(t),c.updateOffset(this,!0),this},mn.subtract=Bt,mn.toArray=function(){var e=this;return[e.year(),e.month(),e.date(),e.hour(),e.minute(),e.second(),e.millisecond()]},mn.toObject=function(){var e=this;return{years:e.year(),months:e.month(),date:e.date(),hours:e.hours(),minutes:e.minutes(),seconds:e.seconds(),milliseconds:e.milliseconds()}},mn.toDate=function(){return new Date(this.valueOf())},mn.toISOString=function(e){if(!this.isValid())return null;var t=!0!==e,n=t?this.clone().utc():this;return n.year()<0||9999<n.year()?A(n,t?"YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]":"YYYYYY-MM-DD[T]HH:mm:ss.SSSZ"):b(Date.prototype.toISOString)?t?this.toDate().toISOString():new Date(this.valueOf()+60*this.utcOffset()*1e3).toISOString().replace("Z",A(n,"Z")):A(n,t?"YYYY-MM-DD[T]HH:mm:ss.SSS[Z]":"YYYY-MM-DD[T]HH:mm:ss.SSSZ")},mn.inspect=function(){if(!this.isValid())return"moment.invalid(/* "+this._i+" */)";var e="moment",t="";this.isLocal()||(e=0===this.utcOffset()?"moment.utc":"moment.parseZone",t="Z");var n="["+e+'("]',s=0<=this.year()&&this.year()<=9999?"YYYY":"YYYYYY",i=t+'[")]';return this.format(n+s+"-MM-DD[T]HH:mm:ss.SSS"+i)},mn.toJSON=function(){return this.isValid()?this.toISOString():null},mn.toString=function(){return this.clone().locale("en").format("ddd MMM DD YYYY HH:mm:ss [GMT]ZZ")},mn.unix=function(){return Math.floor(this.valueOf()/1e3)},mn.valueOf=function(){return this._d.valueOf()-6e4*(this._offset||0)},mn.creationData=function(){return{input:this._i,format:this._f,locale:this._locale,isUTC:this._isUTC,strict:this._strict}},mn.year=Oe,mn.isLeapYear=function(){return De(this.year())},mn.weekYear=function(e){return on.call(this,e,this.week(),this.weekday(),this.localeData()._week.dow,this.localeData()._week.doy)},mn.isoWeekYear=function(e){return on.call(this,e,this.isoWeek(),this.isoWeekday(),1,4)},mn.quarter=mn.quarters=function(e){return null==e?Math.ceil((this.month()+1)/3):this.month(3*(e-1)+this.month()%3)},mn.month=Ue,mn.daysInMonth=function(){return Pe(this.year(),this.month())},mn.week=mn.weeks=function(e){var t=this.localeData().week(this);return null==e?t:this.add(7*(e-t),"d")},mn.isoWeek=mn.isoWeeks=function(e){var t=Ie(this,1,4).week;return null==e?t:this.add(7*(e-t),"d")},mn.weeksInYear=function(){var e=this.localeData()._week;return Ae(this.year(),e.dow,e.doy)},mn.isoWeeksInYear=function(){return Ae(this.year(),1,4)},mn.date=un,mn.day=mn.days=function(e){if(!this.isValid())return null!=e?this:NaN;var t,n,s=this._isUTC?this._d.getUTCDay():this._d.getDay();return null!=e?(t=e,n=this.localeData(),e="string"!=typeof t?t:isNaN(t)?"number"==typeof(t=n.weekdaysParse(t))?t:null:parseInt(t,10),this.add(e-s,"d")):s},mn.weekday=function(e){if(!this.isValid())return null!=e?this:NaN;var t=(this.day()+7-this.localeData()._week.dow)%7;return null==e?t:this.add(e-t,"d")},mn.isoWeekday=function(e){if(!this.isValid())return null!=e?this:NaN;if(null==e)return this.day()||7;var t,n,s=(t=e,n=this.localeData(),"string"==typeof t?n.weekdaysParse(t)%7||7:isNaN(t)?null:t);return this.day(this.day()%7?s:s-7)},mn.dayOfYear=function(e){var t=Math.round((this.clone().startOf("day")-this.clone().startOf("year"))/864e5)+1;return null==e?t:this.add(e-t,"d")},mn.hour=mn.hours=nt,mn.minute=mn.minutes=ln,mn.second=mn.seconds=dn,mn.millisecond=mn.milliseconds=fn,mn.utcOffset=function(e,t,n){var s,i=this._offset||0;if(!this.isValid())return null!=e?this:NaN;if(null==e)return this._isUTC?i:Vt(this);if("string"==typeof e){if(null===(e=Nt(re,e)))return this}else Math.abs(e)<16&&!n&&(e*=60);return!this._isUTC&&t&&(s=Vt(this)),this._offset=e,this._isUTC=!0,null!=s&&this.add(s,"m"),i!==e&&(!t||this._changeInProgress?qt(this,jt(e-i,"m"),1,!1):this._changeInProgress||(this._changeInProgress=!0,c.updateOffset(this,!0),this._changeInProgress=null)),this},mn.utc=function(e){return this.utcOffset(0,e)},mn.local=function(e){return this._isUTC&&(this.utcOffset(0,e),this._isUTC=!1,e&&this.subtract(Vt(this),"m")),this},mn.parseZone=function(){if(null!=this._tzm)this.utcOffset(this._tzm,!1,!0);else if("string"==typeof this._i){var e=Nt(ie,this._i);null!=e?this.utcOffset(e):this.utcOffset(0,!0)}return this},mn.hasAlignedHourOffset=function(e){return!!this.isValid()&&(e=e?bt(e).utcOffset():0,(this.utcOffset()-e)%60==0)},mn.isDST=function(){return this.utcOffset()>this.clone().month(0).utcOffset()||this.utcOffset()>this.clone().month(5).utcOffset()},mn.isLocal=function(){return!!this.isValid()&&!this._isUTC},mn.isUtcOffset=function(){return!!this.isValid()&&this._isUTC},mn.isUtc=Et,mn.isUTC=Et,mn.zoneAbbr=function(){return this._isUTC?"UTC":""},mn.zoneName=function(){return this._isUTC?"Coordinated Universal Time":""},mn.dates=n("dates accessor is deprecated. Use date instead.",un),mn.months=n("months accessor is deprecated. Use month instead",Ue),mn.years=n("years accessor is deprecated. Use year instead",Oe),mn.zone=n("moment().zone is deprecated, use moment().utcOffset instead. http://momentjs.com/guides/#/warnings/zone/",function(e,t){return null!=e?("string"!=typeof e&&(e=-e),this.utcOffset(e,t),this):-this.utcOffset()}),mn.isDSTShifted=n("isDSTShifted is deprecated. See http://momentjs.com/guides/#/warnings/dst-shifted/ for more information",function(){if(!l(this._isDSTShifted))return this._isDSTShifted;var e={};if(w(e,this),(e=Ot(e))._a){var t=e._isUTC?y(e._a):bt(e._a);this._isDSTShifted=this.isValid()&&0<a(e._a,t.toArray())}else this._isDSTShifted=!1;return this._isDSTShifted});var yn=P.prototype;function gn(e,t,n,s){var i=ht(),r=y().set(s,t);return i[n](r,e)}function vn(e,t,n){if(h(e)&&(t=e,e=void 0),e=e||"",null!=t)return gn(e,t,n,"month");var s,i=[];for(s=0;s<12;s++)i[s]=gn(e,s,n,"month");return i}function pn(e,t,n,s){t=("boolean"==typeof e?h(t)&&(n=t,t=void 0):(t=e,e=!1,h(n=t)&&(n=t,t=void 0)),t||"");var i,r=ht(),a=e?r._week.dow:0;if(null!=n)return gn(t,(n+a)%7,s,"day");var o=[];for(i=0;i<7;i++)o[i]=gn(t,(i+a)%7,s,"day");return o}yn.calendar=function(e,t,n){var s=this._calendar[e]||this._calendar.sameElse;return b(s)?s.call(t,n):s},yn.longDateFormat=function(e){var t=this._longDateFormat[e],n=this._longDateFormat[e.toUpperCase()];return t||!n?t:(this._longDateFormat[e]=n.replace(/MMMM|MM|DD|dddd/g,function(e){return e.slice(1)}),this._longDateFormat[e])},yn.invalidDate=function(){return this._invalidDate},yn.ordinal=function(e){return this._ordinal.replace("%d",e)},yn.preparse=_n,yn.postformat=_n,yn.relativeTime=function(e,t,n,s){var i=this._relativeTime[n];return b(i)?i(e,t,n,s):i.replace(/%d/i,e)},yn.pastFuture=function(e,t){var n=this._relativeTime[0<e?"future":"past"];return b(n)?n(t):n.replace(/%s/i,t)},yn.set=function(e){var t,n;for(n in e)b(t=e[n])?this[n]=t:this["_"+n]=t;this._config=e,this._dayOfMonthOrdinalParseLenient=new RegExp((this._dayOfMonthOrdinalParse.source||this._ordinalParse.source)+"|"+/\d{1,2}/.source)},yn.months=function(e,t){return e?o(this._months)?this._months[e.month()]:this._months[(this._months.isFormat||We).test(t)?"format":"standalone"][e.month()]:o(this._months)?this._months:this._months.standalone},yn.monthsShort=function(e,t){return e?o(this._monthsShort)?this._monthsShort[e.month()]:this._monthsShort[We.test(t)?"format":"standalone"][e.month()]:o(this._monthsShort)?this._monthsShort:this._monthsShort.standalone},yn.monthsParse=function(e,t,n){var s,i,r;if(this._monthsParseExact)return function(e,t,n){var s,i,r,a=e.toLocaleLowerCase();if(!this._monthsParse)for(this._monthsParse=[],this._longMonthsParse=[],this._shortMonthsParse=[],s=0;s<12;++s)r=y([2e3,s]),this._shortMonthsParse[s]=this.monthsShort(r,"").toLocaleLowerCase(),this._longMonthsParse[s]=this.months(r,"").toLocaleLowerCase();return n?"MMM"===t?-1!==(i=Ye.call(this._shortMonthsParse,a))?i:null:-1!==(i=Ye.call(this._longMonthsParse,a))?i:null:"MMM"===t?-1!==(i=Ye.call(this._shortMonthsParse,a))?i:-1!==(i=Ye.call(this._longMonthsParse,a))?i:null:-1!==(i=Ye.call(this._longMonthsParse,a))?i:-1!==(i=Ye.call(this._shortMonthsParse,a))?i:null}.call(this,e,t,n);for(this._monthsParse||(this._monthsParse=[],this._longMonthsParse=[],this._shortMonthsParse=[]),s=0;s<12;s++){if(i=y([2e3,s]),n&&!this._longMonthsParse[s]&&(this._longMonthsParse[s]=new RegExp("^"+this.months(i,"").replace(".","")+"$","i"),this._shortMonthsParse[s]=new RegExp("^"+this.monthsShort(i,"").replace(".","")+"$","i")),n||this._monthsParse[s]||(r="^"+this.months(i,"")+"|^"+this.monthsShort(i,""),this._monthsParse[s]=new RegExp(r.replace(".",""),"i")),n&&"MMMM"===t&&this._longMonthsParse[s].test(e))return s;if(n&&"MMM"===t&&this._shortMonthsParse[s].test(e))return s;if(!n&&this._monthsParse[s].test(e))return s}},yn.monthsRegex=function(e){return this._monthsParseExact?(m(this,"_monthsRegex")||Ne.call(this),e?this._monthsStrictRegex:this._monthsRegex):(m(this,"_monthsRegex")||(this._monthsRegex=Le),this._monthsStrictRegex&&e?this._monthsStrictRegex:this._monthsRegex)},yn.monthsShortRegex=function(e){return this._monthsParseExact?(m(this,"_monthsRegex")||Ne.call(this),e?this._monthsShortStrictRegex:this._monthsShortRegex):(m(this,"_monthsShortRegex")||(this._monthsShortRegex=Fe),this._monthsShortStrictRegex&&e?this._monthsShortStrictRegex:this._monthsShortRegex)},yn.week=function(e){return Ie(e,this._week.dow,this._week.doy).week},yn.firstDayOfYear=function(){return this._week.doy},yn.firstDayOfWeek=function(){return this._week.dow},yn.weekdays=function(e,t){var n=o(this._weekdays)?this._weekdays:this._weekdays[e&&!0!==e&&this._weekdays.isFormat.test(t)?"format":"standalone"];return!0===e?je(n,this._week.dow):e?n[e.day()]:n},yn.weekdaysMin=function(e){return!0===e?je(this._weekdaysMin,this._week.dow):e?this._weekdaysMin[e.day()]:this._weekdaysMin},yn.weekdaysShort=function(e){return!0===e?je(this._weekdaysShort,this._week.dow):e?this._weekdaysShort[e.day()]:this._weekdaysShort},yn.weekdaysParse=function(e,t,n){var s,i,r;if(this._weekdaysParseExact)return function(e,t,n){var s,i,r,a=e.toLocaleLowerCase();if(!this._weekdaysParse)for(this._weekdaysParse=[],this._shortWeekdaysParse=[],this._minWeekdaysParse=[],s=0;s<7;++s)r=y([2e3,1]).day(s),this._minWeekdaysParse[s]=this.weekdaysMin(r,"").toLocaleLowerCase(),this._shortWeekdaysParse[s]=this.weekdaysShort(r,"").toLocaleLowerCase(),this._weekdaysParse[s]=this.weekdays(r,"").toLocaleLowerCase();return n?"dddd"===t?-1!==(i=Ye.call(this._weekdaysParse,a))?i:null:"ddd"===t?-1!==(i=Ye.call(this._shortWeekdaysParse,a))?i:null:-1!==(i=Ye.call(this._minWeekdaysParse,a))?i:null:"dddd"===t?-1!==(i=Ye.call(this._weekdaysParse,a))?i:-1!==(i=Ye.call(this._shortWeekdaysParse,a))?i:-1!==(i=Ye.call(this._minWeekdaysParse,a))?i:null:"ddd"===t?-1!==(i=Ye.call(this._shortWeekdaysParse,a))?i:-1!==(i=Ye.call(this._weekdaysParse,a))?i:-1!==(i=Ye.call(this._minWeekdaysParse,a))?i:null:-1!==(i=Ye.call(this._minWeekdaysParse,a))?i:-1!==(i=Ye.call(this._weekdaysParse,a))?i:-1!==(i=Ye.call(this._shortWeekdaysParse,a))?i:null}.call(this,e,t,n);for(this._weekdaysParse||(this._weekdaysParse=[],this._minWeekdaysParse=[],this._shortWeekdaysParse=[],this._fullWeekdaysParse=[]),s=0;s<7;s++){if(i=y([2e3,1]).day(s),n&&!this._fullWeekdaysParse[s]&&(this._fullWeekdaysParse[s]=new RegExp("^"+this.weekdays(i,"").replace(".","\\.?")+"$","i"),this._shortWeekdaysParse[s]=new RegExp("^"+this.weekdaysShort(i,"").replace(".","\\.?")+"$","i"),this._minWeekdaysParse[s]=new RegExp("^"+this.weekdaysMin(i,"").replace(".","\\.?")+"$","i")),this._weekdaysParse[s]||(r="^"+this.weekdays(i,"")+"|^"+this.weekdaysShort(i,"")+"|^"+this.weekdaysMin(i,""),this._weekdaysParse[s]=new RegExp(r.replace(".",""),"i")),n&&"dddd"===t&&this._fullWeekdaysParse[s].test(e))return s;if(n&&"ddd"===t&&this._shortWeekdaysParse[s].test(e))return s;if(n&&"dd"===t&&this._minWeekdaysParse[s].test(e))return s;if(!n&&this._weekdaysParse[s].test(e))return s}},yn.weekdaysRegex=function(e){return this._weekdaysParseExact?(m(this,"_weekdaysRegex")||Qe.call(this),e?this._weekdaysStrictRegex:this._weekdaysRegex):(m(this,"_weekdaysRegex")||(this._weekdaysRegex=qe),this._weekdaysStrictRegex&&e?this._weekdaysStrictRegex:this._weekdaysRegex)},yn.weekdaysShortRegex=function(e){return this._weekdaysParseExact?(m(this,"_weekdaysRegex")||Qe.call(this),e?this._weekdaysShortStrictRegex:this._weekdaysShortRegex):(m(this,"_weekdaysShortRegex")||(this._weekdaysShortRegex=Je),this._weekdaysShortStrictRegex&&e?this._weekdaysShortStrictRegex:this._weekdaysShortRegex)},yn.weekdaysMinRegex=function(e){return this._weekdaysParseExact?(m(this,"_weekdaysRegex")||Qe.call(this),e?this._weekdaysMinStrictRegex:this._weekdaysMinRegex):(m(this,"_weekdaysMinRegex")||(this._weekdaysMinRegex=Be),this._weekdaysMinStrictRegex&&e?this._weekdaysMinStrictRegex:this._weekdaysMinRegex)},yn.isPM=function(e){return"p"===(e+"").toLowerCase().charAt(0)},yn.meridiem=function(e,t,n){return 11<e?n?"pm":"PM":n?"am":"AM"},ut("en",{dayOfMonthOrdinalParse:/\d{1,2}(th|st|nd|rd)/,ordinal:function(e){var t=e%10;return e+(1===D(e%100/10)?"th":1===t?"st":2===t?"nd":3===t?"rd":"th")}}),c.lang=n("moment.lang is deprecated. Use moment.locale instead.",ut),c.langData=n("moment.langData is deprecated. Use moment.localeData instead.",ht);var wn=Math.abs;function Mn(e,t,n,s){var i=jt(t,n);return e._milliseconds+=s*i._milliseconds,e._days+=s*i._days,e._months+=s*i._months,e._bubble()}function kn(e){return e<0?Math.floor(e):Math.ceil(e)}function Sn(e){return 4800*e/146097}function Dn(e){return 146097*e/4800}function Yn(e){return function(){return this.as(e)}}var On=Yn("ms"),Tn=Yn("s"),bn=Yn("m"),xn=Yn("h"),Pn=Yn("d"),Wn=Yn("w"),Cn=Yn("M"),Hn=Yn("Q"),Rn=Yn("y");function Un(e){return function(){return this.isValid()?this._data[e]:NaN}}var Fn=Un("milliseconds"),Ln=Un("seconds"),Nn=Un("minutes"),Gn=Un("hours"),Vn=Un("days"),En=Un("months"),In=Un("years");var An=Math.round,jn={ss:44,s:45,m:45,h:22,d:26,M:11};var Zn=Math.abs;function zn(e){return(0<e)-(e<0)||+e}function $n(){if(!this.isValid())return this.localeData().invalidDate();var e,t,n=Zn(this._milliseconds)/1e3,s=Zn(this._days),i=Zn(this._months);t=S((e=S(n/60))/60),n%=60,e%=60;var r=S(i/12),a=i%=12,o=s,u=t,l=e,h=n?n.toFixed(3).replace(/\.?0+$/,""):"",d=this.asSeconds();if(!d)return"P0D";var c=d<0?"-":"",f=zn(this._months)!==zn(d)?"-":"",m=zn(this._days)!==zn(d)?"-":"",_=zn(this._milliseconds)!==zn(d)?"-":"";return c+"P"+(r?f+r+"Y":"")+(a?f+a+"M":"")+(o?m+o+"D":"")+(u||l||h?"T":"")+(u?_+u+"H":"")+(l?_+l+"M":"")+(h?_+h+"S":"")}var qn=Ht.prototype;return qn.isValid=function(){return this._isValid},qn.abs=function(){var e=this._data;return this._milliseconds=wn(this._milliseconds),this._days=wn(this._days),this._months=wn(this._months),e.milliseconds=wn(e.milliseconds),e.seconds=wn(e.seconds),e.minutes=wn(e.minutes),e.hours=wn(e.hours),e.months=wn(e.months),e.years=wn(e.years),this},qn.add=function(e,t){return Mn(this,e,t,1)},qn.subtract=function(e,t){return Mn(this,e,t,-1)},qn.as=function(e){if(!this.isValid())return NaN;var t,n,s=this._milliseconds;if("month"===(e=H(e))||"quarter"===e||"year"===e)switch(t=this._days+s/864e5,n=this._months+Sn(t),e){case"month":return n;case"quarter":return n/3;case"year":return n/12}else switch(t=this._days+Math.round(Dn(this._months)),e){case"week":return t/7+s/6048e5;case"day":return t+s/864e5;case"hour":return 24*t+s/36e5;case"minute":return 1440*t+s/6e4;case"second":return 86400*t+s/1e3;case"millisecond":return Math.floor(864e5*t)+s;default:throw new Error("Unknown unit "+e)}},qn.asMilliseconds=On,qn.asSeconds=Tn,qn.asMinutes=bn,qn.asHours=xn,qn.asDays=Pn,qn.asWeeks=Wn,qn.asMonths=Cn,qn.asQuarters=Hn,qn.asYears=Rn,qn.valueOf=function(){return this.isValid()?this._milliseconds+864e5*this._days+this._months%12*2592e6+31536e6*D(this._months/12):NaN},qn._bubble=function(){var e,t,n,s,i,r=this._milliseconds,a=this._days,o=this._months,u=this._data;return 0<=r&&0<=a&&0<=o||r<=0&&a<=0&&o<=0||(r+=864e5*kn(Dn(o)+a),o=a=0),u.milliseconds=r%1e3,e=S(r/1e3),u.seconds=e%60,t=S(e/60),u.minutes=t%60,n=S(t/60),u.hours=n%24,o+=i=S(Sn(a+=S(n/24))),a-=kn(Dn(i)),s=S(o/12),o%=12,u.days=a,u.months=o,u.years=s,this},qn.clone=function(){return jt(this)},qn.get=function(e){return e=H(e),this.isValid()?this[e+"s"]():NaN},qn.milliseconds=Fn,qn.seconds=Ln,qn.minutes=Nn,qn.hours=Gn,qn.days=Vn,qn.weeks=function(){return S(this.days()/7)},qn.months=En,qn.years=In,qn.humanize=function(e){if(!this.isValid())return this.localeData().invalidDate();var t,n,s,i,r,a,o,u,l,h,d,c=this.localeData(),f=(n=!e,s=c,i=jt(t=this).abs(),r=An(i.as("s")),a=An(i.as("m")),o=An(i.as("h")),u=An(i.as("d")),l=An(i.as("M")),h=An(i.as("y")),(d=r<=jn.ss&&["s",r]||r<jn.s&&["ss",r]||a<=1&&["m"]||a<jn.m&&["mm",a]||o<=1&&["h"]||o<jn.h&&["hh",o]||u<=1&&["d"]||u<jn.d&&["dd",u]||l<=1&&["M"]||l<jn.M&&["MM",l]||h<=1&&["y"]||["yy",h])[2]=n,d[3]=0<+t,d[4]=s,function(e,t,n,s,i){return i.relativeTime(t||1,!!n,e,s)}.apply(null,d));return e&&(f=c.pastFuture(+this,f)),c.postformat(f)},qn.toISOString=$n,qn.toString=$n,qn.toJSON=$n,qn.locale=Xt,qn.localeData=en,qn.toIsoString=n("toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)",$n),qn.lang=Kt,I("X",0,0,"unix"),I("x",0,0,"valueOf"),ue("x",se),ue("X",/[+-]?\d+(\.\d{1,3})?/),ce("X",function(e,t,n){n._d=new Date(1e3*parseFloat(e,10))}),ce("x",function(e,t,n){n._d=new Date(D(e))}),c.version="2.24.0",e=bt,c.fn=mn,c.min=function(){return Wt("isBefore",[].slice.call(arguments,0))},c.max=function(){return Wt("isAfter",[].slice.call(arguments,0))},c.now=function(){return Date.now?Date.now():+new Date},c.utc=y,c.unix=function(e){return bt(1e3*e)},c.months=function(e,t){return vn(e,t,"months")},c.isDate=d,c.locale=ut,c.invalid=p,c.duration=jt,c.isMoment=k,c.weekdays=function(e,t,n){return pn(e,t,n,"weekdays")},c.parseZone=function(){return bt.apply(null,arguments).parseZone()},c.localeData=ht,c.isDuration=Rt,c.monthsShort=function(e,t){return vn(e,t,"monthsShort")},c.weekdaysMin=function(e,t,n){return pn(e,t,n,"weekdaysMin")},c.defineLocale=lt,c.updateLocale=function(e,t){if(null!=t){var n,s,i=st;null!=(s=ot(e))&&(i=s._config),(n=new P(t=x(i,t))).parentLocale=it[e],it[e]=n,ut(e)}else null!=it[e]&&(null!=it[e].parentLocale?it[e]=it[e].parentLocale:null!=it[e]&&delete it[e]);return it[e]},c.locales=function(){return s(it)},c.weekdaysShort=function(e,t,n){return pn(e,t,n,"weekdaysShort")},c.normalizeUnits=H,c.relativeTimeRounding=function(e){return void 0===e?An:"function"==typeof e&&(An=e,!0)},c.relativeTimeThreshold=function(e,t){return void 0!==jn[e]&&(void 0===t?jn[e]:(jn[e]=t,"s"===e&&(jn.ss=t-1),!0))},c.calendarFormat=function(e,t){var n=e.diff(t,"days",!0);return n<-6?"sameElse":n<-1?"lastWeek":n<0?"lastDay":n<1?"sameDay":n<2?"nextDay":n<7?"nextWeek":"sameElse"},c.prototype=mn,c.HTML5_FMT={DATETIME_LOCAL:"YYYY-MM-DDTHH:mm",DATETIME_LOCAL_SECONDS:"YYYY-MM-DDTHH:mm:ss",DATETIME_LOCAL_MS:"YYYY-MM-DDTHH:mm:ss.SSS",DATE:"YYYY-MM-DD",TIME:"HH:mm",TIME_SECONDS:"HH:mm:ss",TIME_MS:"HH:mm:ss.SSS",WEEK:"GGGG-[W]WW",MONTH:"YYYY-MM"},c});
2875
2876/*! lazysizes - v5.2.0 */
2877!function(a,b){var c=b(a,a.document,Date);a.lazySizes=c,"object"==typeof module&&module.exports&&(module.exports=c)}("undefined"!=typeof window?window:{},function(a,b,c){"use strict";var d,e;if(function(){var b,c={lazyClass:"lazyload",loadedClass:"lazyloaded",loadingClass:"lazyloading",preloadClass:"lazypreload",errorClass:"lazyerror",autosizesClass:"lazyautosizes",srcAttr:"data-src",srcsetAttr:"data-srcset",sizesAttr:"data-sizes",minSize:40,customMedia:{},init:!0,expFactor:1.5,hFac:.8,loadMode:2,loadHidden:!0,ricTimeout:0,throttleDelay:125};e=a.lazySizesConfig||a.lazysizesConfig||{};for(b in c)b in e||(e[b]=c[b])}(),!b||!b.getElementsByClassName)return{init:function(){},cfg:e,noSupport:!0};var f=b.documentElement,g=a.HTMLPictureElement,h="addEventListener",i="getAttribute",j=a[h].bind(a),k=a.setTimeout,l=a.requestAnimationFrame||k,m=a.requestIdleCallback,n=/^picture$/i,o=["load","error","lazyincluded","_lazyloaded"],p={},q=Array.prototype.forEach,r=function(a,b){return p[b]||(p[b]=new RegExp("(\\s|^)"+b+"(\\s|$)")),p[b].test(a[i]("class")||"")&&p[b]},s=function(a,b){r(a,b)||a.setAttribute("class",(a[i]("class")||"").trim()+" "+b)},t=function(a,b){var c;(c=r(a,b))&&a.setAttribute("class",(a[i]("class")||"").replace(c," "))},u=function(a,b,c){var d=c?h:"removeEventListener";c&&u(a,b),o.forEach(function(c){a[d](c,b)})},v=function(a,c,e,f,g){var h=b.createEvent("Event");return e||(e={}),e.instance=d,h.initEvent(c,!f,!g),h.detail=e,a.dispatchEvent(h),h},w=function(b,c){var d;!g&&(d=a.picturefill||e.pf)?(c&&c.src&&!b[i]("srcset")&&b.setAttribute("srcset",c.src),d({reevaluate:!0,elements:[b]})):c&&c.src&&(b.src=c.src)},x=function(a,b){return(getComputedStyle(a,null)||{})[b]},y=function(a,b,c){for(c=c||a.offsetWidth;c<e.minSize&&b&&!a._lazysizesWidth;)c=b.offsetWidth,b=b.parentNode;return c},z=function(){var a,c,d=[],e=[],f=d,g=function(){var b=f;for(f=d.length?e:d,a=!0,c=!1;b.length;)b.shift()();a=!1},h=function(d,e){a&&!e?d.apply(this,arguments):(f.push(d),c||(c=!0,(b.hidden?k:l)(g)))};return h._lsFlush=g,h}(),A=function(a,b){return b?function(){z(a)}:function(){var b=this,c=arguments;z(function(){a.apply(b,c)})}},B=function(a){var b,d=0,f=e.throttleDelay,g=e.ricTimeout,h=function(){b=!1,d=c.now(),a()},i=m&&g>49?function(){m(h,{timeout:g}),g!==e.ricTimeout&&(g=e.ricTimeout)}:A(function(){k(h)},!0);return function(a){var e;(a=!0===a)&&(g=33),b||(b=!0,e=f-(c.now()-d),e<0&&(e=0),a||e<9?i():k(i,e))}},C=function(a){var b,d,e=99,f=function(){b=null,a()},g=function(){var a=c.now()-d;a<e?k(g,e-a):(m||f)(f)};return function(){d=c.now(),b||(b=k(g,e))}},D=function(){var g,m,o,p,y,D,F,G,H,I,J,K,L=/^img$/i,M=/^iframe$/i,N="onscroll"in a&&!/(gle|ing)bot/.test(navigator.userAgent),O=0,P=0,Q=0,R=-1,S=function(a){Q--,(!a||Q<0||!a.target)&&(Q=0)},T=function(a){return null==K&&(K="hidden"==x(b.body,"visibility")),K||!("hidden"==x(a.parentNode,"visibility")&&"hidden"==x(a,"visibility"))},U=function(a,c){var d,e=a,g=T(a);for(G-=c,J+=c,H-=c,I+=c;g&&(e=e.offsetParent)&&e!=b.body&&e!=f;)(g=(x(e,"opacity")||1)>0)&&"visible"!=x(e,"overflow")&&(d=e.getBoundingClientRect(),g=I>d.left&&H<d.right&&J>d.top-1&&G<d.bottom+1);return g},V=function(){var a,c,h,j,k,l,n,o,q,r,s,t,u=d.elements;if((p=e.loadMode)&&Q<8&&(a=u.length)){for(c=0,R++;c<a;c++)if(u[c]&&!u[c]._lazyRace)if(!N||d.prematureUnveil&&d.prematureUnveil(u[c]))ba(u[c]);else if((o=u[c][i]("data-expand"))&&(l=1*o)||(l=P),r||(r=!e.expand||e.expand<1?f.clientHeight>500&&f.clientWidth>500?500:370:e.expand,d._defEx=r,s=r*e.expFactor,t=e.hFac,K=null,P<s&&Q<1&&R>2&&p>2&&!b.hidden?(P=s,R=0):P=p>1&&R>1&&Q<6?r:O),q!==l&&(D=innerWidth+l*t,F=innerHeight+l,n=-1*l,q=l),h=u[c].getBoundingClientRect(),(J=h.bottom)>=n&&(G=h.top)<=F&&(I=h.right)>=n*t&&(H=h.left)<=D&&(J||I||H||G)&&(e.loadHidden||T(u[c]))&&(m&&Q<3&&!o&&(p<3||R<4)||U(u[c],l))){if(ba(u[c]),k=!0,Q>9)break}else!k&&m&&!j&&Q<4&&R<4&&p>
28772&&(g[0]||e.preloadAfterLoad)&&(g[0]||!o&&(J||I||H||G||"auto"!=u[c][i](e.sizesAttr)))&&(j=g[0]||u[c]);j&&!k&&ba(j)}},W=B(V),X=function(a){var b=a.target;if(b._lazyCache)return void delete b._lazyCache;S(a),s(b,e.loadedClass),t(b,e.loadingClass),u(b,Z),v(b,"lazyloaded")},Y=A(X),Z=function(a){Y({target:a.target})},$=function(a,b){try{a.contentWindow.location.replace(b)}catch(c){a.src=b}},_=function(a){var b,c=a[i](e.srcsetAttr);(b=e.customMedia[a[i]("data-media")||a[i]("media")])&&a.setAttribute("media",b),c&&a.setAttribute("srcset",c)},aa=A(function(a,b,c,d,f){var g,h,j,l,m,p;(m=v(a,"lazybeforeunveil",b)).defaultPrevented||(d&&(c?s(a,e.autosizesClass):a.setAttribute("sizes",d)),h=a[i](e.srcsetAttr),g=a[i](e.srcAttr),f&&(j=a.parentNode,l=j&&n.test(j.nodeName||"")),p=b.firesLoad||"src"in a&&(h||g||l),m={target:a},s(a,e.loadingClass),p&&(clearTimeout(o),o=k(S,2500),u(a,Z,!0)),l&&q.call(j.getElementsByTagName("source"),_),h?a.setAttribute("srcset",h):g&&!l&&(M.test(a.nodeName)?$(a,g):a.src=g),f&&(h||l)&&w(a,{src:g})),a._lazyRace&&delete a._lazyRace,t(a,e.lazyClass),z(function(){var b=a.complete&&a.naturalWidth>1;p&&!b||(b&&s(a,"ls-is-cached"),X(m),a._lazyCache=!0,k(function(){"_lazyCache"in a&&delete a._lazyCache},9)),"lazy"==a.loading&&Q--},!0)}),ba=function(a){if(!a._lazyRace){var b,c=L.test(a.nodeName),d=c&&(a[i](e.sizesAttr)||a[i]("sizes")),f="auto"==d;(!f&&m||!c||!a[i]("src")&&!a.srcset||a.complete||r(a,e.errorClass)||!r(a,e.lazyClass))&&(b=v(a,"lazyunveilread").detail,f&&E.updateElem(a,!0,a.offsetWidth),a._lazyRace=!0,Q++,aa(a,b,f,d,c))}},ca=C(function(){e.loadMode=3,W()}),da=function(){3==e.loadMode&&(e.loadMode=2),ca()},ea=function(){if(!m){if(c.now()-y<999)return void k(ea,999);m=!0,e.loadMode=3,W(),j("scroll",da,!0)}};return{_:function(){y=c.now(),d.elements=b.getElementsByClassName(e.lazyClass),g=b.getElementsByClassName(e.lazyClass+" "+e.preloadClass),j("scroll",W,!0),j("resize",W,!0),j("pageshow",function(a){if(a.persisted){var c=b.querySelectorAll("."+e.loadingClass);c.length&&c.forEach&&l(function(){c.forEach(function(a){a.complete&&ba(a)})})}}),a.MutationObserver?new MutationObserver(W).observe(f,{childList:!0,subtree:!0,attributes:!0}):(f[h]("DOMNodeInserted",W,!0),f[h]("DOMAttrModified",W,!0),setInterval(W,999)),j("hashchange",W,!0),["focus","mouseover","click","load","transitionend","animationend"].forEach(function(a){b[h](a,W,!0)}),/d$|^c/.test(b.readyState)?ea():(j("load",ea),b[h]("DOMContentLoaded",W),k(ea,2e4)),d.elements.length?(V(),z._lsFlush()):W()},checkElems:W,unveil:ba,_aLSL:da}}(),E=function(){var a,c=A(function(a,b,c,d){var e,f,g;if(a._lazysizesWidth=d,d+="px",a.setAttribute("sizes",d),n.test(b.nodeName||""))for(e=b.getElementsByTagName("source"),f=0,g=e.length;f<g;f++)e[f].setAttribute("sizes",d);c.detail.dataAttr||w(a,c.detail)}),d=function(a,b,d){var e,f=a.parentNode;f&&(d=y(a,f,d),e=v(a,"lazybeforesizes",{width:d,dataAttr:!!b}),e.defaultPrevented||(d=e.detail.width)&&d!==a._lazysizesWidth&&c(a,f,e,d))},f=function(){var b,c=a.length;if(c)for(b=0;b<c;b++)d(a[b])},g=C(f);return{_:function(){a=b.getElementsByClassName(e.autosizesClass),j("resize",g)},checkElems:g,updateElem:d}}(),F=function(){!F.i&&b.getElementsByClassName&&(F.i=!0,E._(),D._())};return k(function(){e.init&&F()}),d={cfg:e,autoSizer:E,loader:D,init:F,uP:w,aC:s,rC:t,hC:r,fire:v,gW:y,rAF:z}});
2878/*! lazysizes - v4.0.3 */
2879!function(a,b){var c=function(){b(a.lazySizes),a.removeEventListener("lazyunveilread",c,!0)};b=b.bind(null,a,a.document),"object"==typeof module&&module.exports?b(require("lazysizes")):a.lazySizes?c():a.addEventListener("lazyunveilread",c,!0)}(window,function(a,b,c){"use strict";function d(a,c){if(!g[a]){var d=b.createElement(c?"link":"script"),e=b.getElementsByTagName("script")[0];c?(d.rel="stylesheet",d.href=a):d.src=a,g[a]=!0,g[d.src||d.href]=!0,e.parentNode.insertBefore(d,e)}}var e,f,g={};b.addEventListener&&(f=/\(|\)|\s|'/,e=function(a,c){var d=b.createElement("img");d.onload=function(){d.onload=null,d.onerror=null,d=null,c()},d.onerror=d.onload,d.src=a,d&&d.complete&&d.onload&&d.onload()}
2879,addEventListener("lazybeforeunveil",function(a){if(a.detail.instance==c){var b,g,h,i;a.defaultPrevented||("none"==a.target.preload&&(a.target.preload="auto"),b=a.target.getAttribute("data-link"),b&&d(b,!0),b=a.target.getAttribute("data-script"),b&&d(b),b=a.target.getAttribute("data-require"),b&&(c.cfg.requireJs?c.cfg.requireJs([b]):d(b)),h=a.target.getAttribute("data-bg"),h&&(a.detail.firesLoad=!0,g=function(){a.target.style.backgroundImage="url("+(f.test(h)?JSON.stringify(h):h)+")",a.detail.firesLoad=!1,c.fire(a.target,"_lazyloaded",{},!0,!0)},e(h,g)),i=a.target.getAttribute("data-poster"),i&&(a.detail.firesLoad=!0,g=function(){a.target.poster=i,a.detail.firesLoad=!1,c.fire(a.target,"_lazyloaded",{},!0,!0)},e(i,g)))}},!1))});
2880
2881/*
2882 * YoutubeBackground - A wrapper for the Youtube API - Great for fullscreen background videos or just regular videos.
2883 *
2884 * Licensed under the MIT license:
2885 *   http://www.opensource.org/licenses/mit-license.php
2886 *
2887 *
2888 * Version:  1.0.4
2889 *
2890 */
2891// Chain of Responsibility pattern. Creates base class that can be overridden.
2892if (typeof Object.create !== "function") {
2893  Object.create = function (obj) {
2894    function F() { }
2895    F.prototype = obj;
2896    return new F();
2897  };
2898}
2899
2900(function ($, window, document) {
2901  var
2902    loadAPI = function loadAPI(callback) {
2903
2904      // Load Youtube API
2905      var tag = document.createElement('script'),
2906        head = document.getElementsByTagName('head')[0];
2907
2908      if (window.location.origin == 'file://') {
2909        tag.src = 'http://www.youtube.com/iframe_api';
2910      } else {
2911        tag.src = '//www.youtube.com/iframe_api';
2912      }
2913
2914      head.appendChild(tag);
2915
2916      // Clean up Tags.
2917      head = null;
2918      tag = null;
2919
2920      iframeIsReady(callback);
2921    },
2922    iframeIsReady = function iframeIsReady(callback) {
2923      // Listen for Gobal YT player callback
2924      if (typeof YT === 'undefined' && typeof window.loadingPlayer === 'undefined') {
2925        // Prevents Ready Event from being called twice
2926        window.loadingPlayer = true;
2927
2928
2929        // Creates deferred so, other players know when to wait.
2930        window.dfd = $.Deferred();
2931        window.onYouTubeIframeAPIReady = function () {
2932          window.onYouTubeIframeAPIReady = null;
2933          window.dfd.resolve("done");
2934          callback();
2935        };
2936      } else if (typeof YT === 'object') {
2937        callback();
2938      } else {
2939        window.dfd.done(function (name) {
2940          callback();
2941        });
2942      }
2943    };
2944
2945  // initial state of getPlayhead function when videoData is not loaded
2946  function getPlayhead() {
2947    return {
2948      "playerID": '',
2949      "playhead": 0
2950    }
2951  }
2952  window.onbeforeunload = function() {
2953      if(this.YTPlayer && this.YTPlayer.defaults.events && this.YTPlayer.defaults.events.videoSessionStarted) {
2954          var playerId = this.YTPlayer.holderID != undefined ? this.YTPlayer.holderID : this.YTPlayer.options !== undefined? this.YTPlayer.options.player : $(".video-container > iframe:first").attr("id");
2955          stanford.analytics.send(stanford.analytics.videoTrackingSessionEnd(playerId));
2956      }
2957  }
2958
2959  window.getPlayhead = getPlayhead
2960
2961  // YTPlayer Object
2962  YTPlayer = {
2963    player: null,
2964
2965    // Defaults
2966    defaults: {
2967      ratio: 16 / 9,
2968      videoId: 'LSmgKRx5pBo',
2969      mute: true,
2970      repeat: false,
2971      width: $(window).width(),
2972      playButtonClass: 'YTPlayer-play',
2973      pauseButtonClass: 'YTPlayer-pause',
2974      muteButtonClass: 'YTPlayer-mute',
2975      volumeUpClass: 'YTPlayer-volume-up',
2976      volumeDownClass: 'YTPlayer-volume-down',
2977      start: 0,
2978      pauseOnScroll: false,
2979      fitToBackground: true,
2980      playerVars: {
2981        iv_load_policy: 3,
2982        modestbranding: 1,
2983        autoplay: 1,
2984        controls: 0,
2985        showinfo: 0,
2986        wmode: 'opaque',
2987        branding: 0,
2988        autohide: 0
2989      },
2990      events: null
2991    },
2992
2993    /**
2994     * @function init
2995     * Intializes YTPlayer object
2996     */
2997    init: function init(node, userOptions) {
2998      var self = this;
2999      console.log("Initializing YTPlayer");
3000
3001      // Assign user-provided options
3002      self.userOptions = userOptions;
3003
3004      // Cache references to the DOM elements
3005      self.$body = $('body');
3006      self.$node = $(node);
3007      self.$window = $(window);
3008
3009      // Setup event defaults
3010      self.defaults.events = {
3011        videoSessionStarted: false,
3012        'onReady': function (e) {
3013          self.onPlayerReady(e);
3014          console.log("YouTube Player is ready!");
3015
3016          // Pause on scroll if enabled
3017          if (self.options.pauseOnScroll) {
3018            self.pauseOnScroll();
3019          }
3020
3021          // Custom callback after player is ready
3022          if (typeof self.options.callback === 'function') {
3023            self.options.callback.call(this);
3024          }
3025        },
3026        'onStateChange': function (e) {
3027          var videoData = self.player != undefined? self.player.playerInfo.videoData : self.playerInfo.videoData;
3028          var videoId = videoData.video_id;
3029          var videoName = videoData.title;
3030          var videoLength = self.player != undefined? self.player.playerInfo.duration: self.playerInfo.duration;
3031          var playerId = self.holderID == undefined? self.id : self.holderID;
3032          var contentType = "video";
3033          var streamType = "vod";
3034          var playerType = "YouTube";
3035          if (e.data === 1) { // Video playing
3036            if (!self.defaults.events.videoSessionStarted) {
3037              self.defaults.events.videoSessionStarted = true;
3038              // Call analytics tracking for session start
3039              stanford.analytics.send(stanford.analytics.videoTrackingSessionStart(videoId, videoName, videoLength, playerId, contentType, streamType, playerType));
3040            }
3041            // Call analytics tracking for play
3042            stanford.analytics.send(stanford.analytics.videoTrackingPlay(playerId));
3043          }
3044          else if (e.data === 2) { // Video paused
3045            // Call analytics tracking for pause
3046            stanford.analytics.send(stanford.analytics.videoTrackingPause(playerId));
3047          } 
3048          else if (e.data === 0) { // Video ended/complete
3049            // Call analytics tracking for session complete
3050            stanford.analytics.send(stanford.analytics.videoTrackingSessionComplete(playerId));
3051            if (self.options.repeat) { // Video repeat enabled
3052              self.player.seekTo(self.options.start);
3053            }
3054          }
3055        }
3056      };
3057
3058      function getPlayhead() {
3059        var currentTime = self.player.playerInfo.currentTime ? self.player.playerInfo.currentTime : 0
3060        return {
3061          "playerID": self.holderID,
3062          "playhead": currentTime
3063        }
3064      }
3065
3066      window.getPlayhead = getPlayhead;
3067
3068      // Merge user options with defaults
3069      self.options = $.extend(true, {}, self.defaults, self.userOptions);
3070
3071      // Calculate height for maintaining aspect ratio
3072      self.options.height = Math.ceil(self.options.width / self.options.ratio);
3073
3074      // Use the provided iframe directly
3075      self.holderID = self.$node.attr('id'); // Use existing iframe's ID
3076
3077      // Load YouTube API and bind it to the existing iframe
3078      loadAPI(function () {
3079        if ($('#presentation-player').length > 0) {
3080            self.holderID = 'presentation-player';
3081        } else if ($('#content-player').length > 0) {
3082            self.holderID = 'content-player';
3083        }
3084        self.player = new YT.Player(self.holderID, self.options);
3085      });
3086
3087      return self;
3088    },
3089
3090
3091    /**
3092     * @function pauseOnScroll
3093     * Adds window events to pause video on scroll.
3094     */
3095    pauseOnScroll: function pauseOnScroll() {
3096      var self = this;
3097      self.$window.on('scroll.YTplayer' + self.ID, function () {
3098        var state = self.player.getPlayerState();
3099        if (state === 1) {
3100          self.player.pauseVideo();
3101        }
3102      });
3103      self.$window.scrollStopped(function () {
3104        var state = self.player.getPlayerState();
3105        if (state === 2) {
3106          self.player.playVideo();
3107        }
3108      });
3109    },
3110    /**
3111     * @function createContainerVideo
3112     * Adds HTML for video in a container
3113     */
3114    createContainerVideo: function createContainerVideo() {
3115      var self = this;
3116
3117      /*jshint multistr: true */
3118      var $YTPlayerString = $('<div id="ytplayer-container' + self.ID + '" >\
3119                                    <div id="' + self.holderID + '" class="ytplayer-player-inline"></div> \
3120                                    </div> \
3121                                    <div id="ytplayer-shield" class="ytplayer-shield"></div>');
3122
3123      self.$node.append($YTPlayerString);
3124      self.$YTPlayerString = $YTPlayerString;
3125      $YTPlayerString = null;
3126    },
3127
3128    /**
3129     * @function createBackgroundVideo
3130     * Adds HTML for video background
3131     */
3132    createBackgroundVideo: function createBackgroundVideo() {
3133      /*jshint multistr: true */
3134      var self = this,
3135        $YTPlayerString = $('<div id="ytplayer-container' + self.ID + '" class="ytplayer-container background">\
3136                                    <div id="' + self.holderID + '" class="ytplayer-player"></div>\
3137                                    </div>\
3138                                    <div id="ytplayer-shield" class="ytplayer-shield"></div>');
3139
3140      self.$node.append($YTPlayerString);
3141      self.$YTPlayerString = $YTPlayerString;
3142      $YTPlayerString = null;
3143    },
3144
3145    /**
3146     * @function onYouTubeIframeAPIReady
3147     * @ params {object} YTPlayer object for access to options
3148     * Youtube API calls this function when the player is ready.
3149     */
3150    onYouTubeIframeAPIReady: function onYouTubeIframeAPIReady() {
3151      var self = this;
3152      self.player = new window.YT.Player(self.holderID, self.options);
3153    },
3154
3155    /**
3156     * @function onPlayerReady
3157     * @ params {event} window event from youtube player
3158     */
3159    onPlayerReady: function onPlayerReady(e) {
3160      if (this.options.mute) {
3161        e.target.mute();
3162      }
3163      //e.target.playVideo();
3164    },
3165    /**
3166     * @function onPlayerEnd - push player id and session end to datalayer
3167     */
3168    onPlayerEnd: function onPlayerEnd() {
3169        var self = this;
3170        if(self.defaults.events.videoSessionStarted) {
3171            stanford.analytics.send(stanford.analytics.videoTrackingSessionEnd(self.holderID));
3172        }
3173   },
3174    /**
3175     * @function getPlayer
3176     * returns youtube player
3177     */
3178    getPlayer: function getPlayer() {
3179      return this.player;
3180    },
3181
3182    /**
3183     * @function destroy
3184     * destroys all!
3185     */
3186    destroy: function destroy() {
3187      var self = this;
3188
3189      self.$node
3190        .removeData('yt-init')
3191        .removeData('ytPlayer')
3192        .removeClass('loaded');
3193
3194      self.$YTPlayerString.remove();
3195
3196      $(window).off('resize.YTplayer' + self.ID);
3197      $(window).off('scroll.YTplayer' + self.ID);
3198      self.$body = null;
3199      self.$node = null;
3200      self.$YTPlayerString = null;
3201      self.player.destroy();
3202      self.player = null;
3203    }
3204  };
3205
3206  // Scroll Stopped event.
3207  $.fn.scrollStopped = function (callback) {
3208    var $this = $(this), self = this;
3209    $this.scroll(function () {
3210      if ($this.data('scrollTimeout')) {
3211        clearTimeout($this.data('scrollTimeout'));
3212      }
3213      $this.data('scrollTimeout', setTimeout(callback, 250, self));
3214    });
3215  };
3216
3217  // Create plugin
3218  $.fn.YTPlayer = function (options) {
3219
3220    return this.each(function () {
3221      var el = this;
3222
3223      $(el).data("yt-init", true);
3224      var player = Object.create(YTPlayer);
3225      player.init(el, options);
3226      $.data(el, "ytPlayer", player);
3227    });
3228  };
3229
3230})(jQuery, window, document);
3231
3232// Avoid `console` errors in browsers that lack a console.
3233(function() {
3234    var method;
3235    var noop = function () {};
3236    var methods = [
3237        'assert', 'clear', 'count', 'debug', 'dir', 'dirxml', 'error',
3238        'exception', 'group', 'groupCollapsed', 'groupEnd', 'info', 'log',
3239        'markTimeline', 'profile', 'profileEnd', 'table', 'time', 'timeEnd',
3240        'timeStamp', 'trace', 'warn'
3241    ];
3242    var length = methods.length;
3243    var console = (window.console = window.console || {});
3244
3245    while (length--) {
3246        method = methods[length];
3247
3248        // Only stub undefined methods.
3249        if (!console[method]) {
3250            console[method] = noop;
3251        }
3252    }
3253}());
3254
3255/*!
3256 * jQuery.localScroll
3257 * Copyright (c) 2007-2014 Ariel Flesler - aflesler<a>gmail<d>com | http://flesler.blogspot.com
3258 * Licensed under MIT
3259 * http://flesler.blogspot.com/2007/10/jquerylocalscroll-10.html
3260 * @author Ariel Flesler
3261 * @version 1.3.5
3262 */
3263 ;(function(plugin) {
3264    // AMD Support
3265    if (typeof define === 'function' && define.amd) {
3266        define(['jquery'], plugin);
3267    } else {
3268        plugin(jQuery);
3269    }
3270}(function($) {
3271	var URI = location.href.replace(/#.*/, ''); // local url without hash
3272
3273	var $localScroll = $.localScroll = function(settings) {
3274		$('body').localScroll(settings);
3275	};
3276
3277	// Many of these defaults, belong to jQuery.ScrollTo, check it's demo for an example of each option.
3278	// @see http://demos.flesler.com/jquery/scrollTo/
3279	// The defaults are public and can be overriden.
3280	$localScroll.defaults = {
3281		duration: 1000, // How long to animate.
3282		axis: 'y', // Which of top and left should be modified.
3283		event: 'click', // On which event to react.
3284		stop: true, // Avoid queuing animations
3285		target: window // What to scroll (selector or element). The whole window by default.
3286		/*
3287		lock: false, // ignore events if already animating
3288		lazy: false, // if true, links can be added later, and will still work.
3289		filter: null, // filter some anchors out of the matched elements.
3290		hash: false // if true, the hash of the selected link, will appear on the address bar.
3291		*/
3292	};
3293
3294	$.fn.localScroll = function(settings) {
3295		settings = $.extend({}, $localScroll.defaults, settings);
3296
3297		if (settings.hash && location.hash) {
3298			if (settings.target) window.scrollTo(0, 0);
3299			scroll(0, location, settings);
3300		}
3301
3302		return settings.lazy ?
3303			// use event delegation, more links can be added later.
3304			this.on(settings.event, 'a,area', function(e) {
3305				if (filter.call(this)) {
3306					scroll(e, this, settings);
3307				}
3308			}) :
3309			// bind concretely, to each matching link
3310			this.find('a,area')
3311				.filter(filter).bind(settings.event, function(e) {
3312					scroll(e, this, settings);
3313				}).end()
3314			.end();
3315
3316		function filter() {// is this a link that points to an anchor and passes a possible filter ? href is checked to avoid a bug in FF.
3317			return !!this.href && !!this.hash && this.href.replace(this.hash,'') == URI && (!settings.filter || $(this).is(settings.filter));
3318		};
3319	};
3320
3321	// Not needed anymore, kept for backwards compatibility
3322	$localScroll.hash = function() {};
3323
3324	function scroll(e, link, settings) {
3325		var id = link.hash.slice(1),
3326			elem = document.getElementById(id) || document.getElementsByName(id)[0];
3327
3328		if (!elem)
3329			return;
3330
3331		if (e)
3332			e.preventDefault();
3333
3334		var $target = $(settings.target);
3335
3336		if (settings.lock && $target.is(':animated') ||
3337			settings.onBefore && settings.onBefore(e, elem, $target) === false)
3338			return;
3339
3340		if (settings.stop)
3341			$target._scrollable().stop(true); // remove all its animations
3342
3343		if (settings.hash) {
3344			var attr = elem.id === id ? 'id' : 'name',
3345				$a = $('<a> </a>').attr(attr, id).css({
3346					position:'absolute',
3347					top: $(window).scrollTop(),
3348					left: $(window).scrollLeft()
3349				});
3350
3351			elem[attr] = '';
3352			$('body').prepend($a);
3353			location.hash = link.hash;
3354			$a.remove();
3355			elem[attr] = id;
3356		}
3357
3358		$target
3359			.scrollTo(elem, settings) // do scroll
3360			.trigger('notify.serialScroll',[elem]); // notify serialScroll about this change
3361	};
3362
3363	// AMD requirement
3364	return $localScroll;
3365
3366}));
3367
3368/*! viewportSize | Author: Tyson Matanich, 2013 | License: MIT */
3369(function(n){n.viewportSize={},n.viewportSize.getHeight=function(){return t("Height")},n.viewportSize.getWidth=function(){return t("Width")};var t=function(t){var f,o=t.toLowerCase(),e=n.document,i=e.documentElement,r,u;return n["inner"+t]===undefined?f=i["client"+t]:n["inner"+t]!=i["client"+t]?(r=e.createElement("body"),r.id="vpw-test-b",r.style.cssText="overflow:scroll",u=e.createElement("div"),u.id="vpw-test-d",u.style.cssText="position:absolute;top:-1000px",u.innerHTML="<style>@media("+o+":"+i["client"+t]+"px){body#vpw-test-b div#vpw-test-d{"+o+":7px!important}}<\/style>",r.appendChild(u),i.insertBefore(r,e.head),f=u["offset"+t]==7?i["client"+t]:n["inner"+t],i.removeChild(r)):f=n["inner"+t],f}})(this);
3370
3371
3372
3373/**!
3374 * trunk8 v1.3.2
3375 * https://github.com/rviscomi/trunk8
3376 *
3377 * Copyright 2012 Rick Viscomi
3378 * Released under the MIT License.
3379 *
3380 * Date: October 21, 2012
3381 */
3382
3383(function ($) {
3384	var methods,
3385		utils,
3386		SIDES = {
3387			/* cen...ter */
3388			center: 'center',
3389			/* ...left */
3390			left: 'left',
3391			/* right... */
3392			right: 'right'
3393		},
3394		WIDTH = {
3395			auto: 'auto'
3396		};
3397
3398	function trunk8(element) {
3399		this.$element = $(element);
3400		this.original_text = this.$element.html();
3401		this.settings = $.extend({}, $.fn.trunk8.defaults);
3402	}
3403
3404	trunk8.prototype.updateSettings = function (options) {
3405		this.settings = $.extend(this.settings, options);
3406	};
3407
3408	function truncate() {
3409		var data = this.data('trunk8'),
3410			settings = data.settings,
3411			width = settings.width,
3412			side = settings.side,
3413			fill = settings.fill,
3414			line_height = utils.getLineHeight(this) * settings.lines,
3415			str = data.original_text,
3416			length = str.length,
3417			max_bite = '',
3418			lower, upper,
3419			bite_size,
3420			bite;
3421
3422		/* Reset the field to the original string. */
3423		this.html(str);
3424
3425		if (width === WIDTH.auto) {
3426			/* Assuming there is no "overflow: hidden". */
3427			if (this.height() <= line_height) {
3428				/* Text is already at the optimal trunkage. */
3429				return;
3430			}
3431
3432			/* Binary search technique for finding the optimal trunkage. */
3433			/* Find the maximum bite without overflowing. */
3434			lower = 0;
3435			upper = length - 1;
3436
3437			while (lower <= upper) {
3438				bite_size = lower + ((upper - lower) >> 1);
3439
3440				bite = utils.eatStr(str, side, length - bite_size, fill);
3441
3442				this.html(bite);
3443
3444				/* Check for overflow. */
3445				if (this.height() > line_height) {
3446					upper = bite_size - 1;
3447				}
3448				else {
3449					lower = bite_size + 1;
3450
3451					/* Save the bigger bite. */
3452					max_bite = (max_bite.length > bite.length) ? max_bite : bite;
3453				}
3454			}
3455
3456			/* Reset the content to eliminate possible existing scroll bars. */
3457			this.html('');
3458
3459			/* Display the biggest bite. */
3460			this.html(max_bite);
3461
3462			if (settings.tooltip) {
3463				this.attr('title', str);
3464			}
3465		}
3466		else if (!isNaN(width)) {
3467			bite_size = length - width;
3468
3469			bite = utils.eatStr(str, side, bite_size, fill);
3470
3471			this.html(bite);
3472
3473			if (settings.tooltip) {
3474				this.attr('title', str);
3475			}
3476		}
3477		else {
3478			$.error('Invalid width "' + width + '".');
3479		}
3480	}
3481
3482	methods = {
3483		init: function (options) {
3484			return this.each(function () {
3485				var $this = $(this),
3486					data = $this.data('trunk8');
3487
3488				if (!data) {
3489					$this.data('trunk8', (data = new trunk8(this)));
3490				}
3491
3492				data.updateSettings(options);
3493
3494				truncate.call($this);
3495			});
3496		},
3497
3498		/** Updates the text value of the elements while maintaining truncation. */
3499		update: function (new_string) {
3500			return this.each(function () {
3501				var $this = $(this);
3502
3503				/* Update text. */
3504				if (new_string) {
3505					$this.data('trunk8').original_text = new_string;
3506				}
3507
3508				/* Truncate accordingly. */
3509				truncate.call($this);
3510			});
3511		},
3512
3513		revert: function () {
3514			return this.each(function () {
3515				/* Get original text. */
3516				var text = $(this).data('trunk8').original_text;
3517
3518				/* Revert element to original text. */
3519				$(this).html(text);
3520			});
3521		},
3522
3523		/** Returns this instance's settings object. NOT CHAINABLE. */
3524		getSettings: function () {
3525			return this.get(0).data('trunk8').settings;
3526		}
3527	};
3528
3529	utils = {
3530		/** Replaces [bite_size] [side]-most chars in [str] with [fill]. */
3531		eatStr: function (str, side, bite_size, fill) {
3532		    var length = str.length,
3533		    	key = utils.eatStr.generateKey.apply(null, arguments),
3534		        half_length,
3535		        half_bite_size;
3536
3537	        /* If the result is already in the cache, return it. */
3538	        if (utils.eatStr.cache[key]) {
3539				return utils.eatStr.cache[key];
3540	        }
3541
3542			/* Common error handling. */
3543		    if ((typeof str !== 'string') || (length === 0)) {
3544		    	$.error('Invalid source string "' + str + '".');
3545		    }
3546		    if ((bite_size < 0) || (bite_size > length)) {
3547		    	$.error('Invalid bite size "' + bite_size + '".');
3548		    }
3549		    else if (bite_size === 0) {
3550			    /* No bite should show no truncation. */
3551				return str;
3552		    }
3553		    if (typeof (fill + '') !== 'string') {
3554				$.error('Fill unable to be converted to a string.');
3555		    }
3556
3557			/* Compute the result, store it in the cache, and return it. */
3558		    switch (side) {
3559		        case SIDES.right:
3560			        /* str... */
3561		            return utils.eatStr.cache[key] =
3562			            	$.trim(str.substr(0, length - bite_size)) + fill;
3563
3564		        case SIDES.left:
3565			        /* ...str */
3566		            return utils.eatStr.cache[key] =
3567			            	fill + $.trim(str.substr(bite_size));
3568
3569		        case SIDES.center:
3570			        /* Bit-shift to the right by one === Math.floor(x / 2) */
3571		            half_length = length >> 1; // halve the length
3572		            half_bite_size = bite_size >> 1; // halve the bite_size
3573
3574			        /* st...r */
3575		            return utils.eatStr.cache[key] =
3576			            	$.trim(utils.eatStr(str.substr(0, length - half_length), SIDES.right, bite_size - half_bite_size, '')) +
3577		            		fill +
3578		            		$.trim(utils.eatStr(str.substr(length - half_length), SIDES.left, half_bite_size, ''));
3579
3580		        default:
3581		        	$.error('Invalid side "' + side + '".');
3582		    }
3583		},
3584
3585		getLineHeight: function (elem) {
3586	            var $elem = $(elem),
3587	            	floats = $elem.css('float'),
3588	            	position = $elem.css('position'),
3589	            	html = $elem.html(),
3590			        wrapper_id = 'line-height-test',
3591			        line_height;
3592
3593	            if (floats !== 'none') {
3594	            	$elem.css('float', 'none');
3595	            }
3596
3597	            if (position === 'absolute') {
3598	            	$elem.css('position', 'static');
3599	            }
3600
3601	            /* Set the content to a small single character and wrap. */
3602	            $elem.html('i').wrap('<div id="' + wrapper_id + '" />');
3603
3604	            /* Calculate the line height by measuring the wrapper.*/
3605	            line_height = $('#' + wrapper_id).innerHeight();
3606
3607	            /* Remove the wrapper and reset the style/content. */
3608	            $elem.html(html).css({
3609	            	'float': floats,
3610	            	'position': position
3611	            }).unwrap();
3612
3613	            return line_height;
3614	        }
3615	};
3616
3617	utils.eatStr.cache = {};
3618	utils.eatStr.generateKey = function () {
3619		return Array.prototype.join.call(arguments, '');
3620	};
3621
3622	$.fn.trunk8 = function (method) {
3623		if (methods[method]) {
3624			return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
3625		}
3626		else if (typeof method === 'object' || !method) {
3627			return methods.init.apply(this, arguments);
3628		}
3629		else {
3630			$.error('Method ' + method + ' does not exist on jQuery.trunk8');
3631		}
3632	};
3633
3634	/* Default trunk8 settings. */
3635	$.fn.trunk8.defaults = {
3636		fill: '&hellip;',
3637		lines: 1,
3638		side: SIDES.right,
3639		tooltip: true,
3640		width: WIDTH.auto
3641	};
3642})(jQuery);
3643
3644/*!
3645 * hoverIntent r7 // 2013.03.11 // jQuery 1.9.1+
3646 * http://cherne.net/brian/resources/jquery.hoverIntent.html
3647 *
3648 * You may use hoverIntent under the terms of the MIT license.
3649 * Copyright 2007, 2013 Brian Cherne
3650 */
3651(function(e){e.fn.hoverIntent=function(t,n,r){var i={interval:100,sensitivity:7,timeout:0};if(typeof t==="object"){i=e.extend(i,t)}else if(e.isFunction(n)){i=e.extend(i,{over:t,out:n,selector:r})}else{i=e.extend(i,{over:t,out:t,selector:n})}var s,o,u,a;var f=function(e){s=e.pageX;o=e.pageY};var l=function(t,n){n.hoverIntent_t=clearTimeout(n.hoverIntent_t);if(Math.abs(u-s)+Math.abs(a-o)<i.sensitivity){e(n).off("mousemove.hoverIntent",f);n.hoverIntent_s=1;return i.over.apply(n,[t])}else{u=s;a=o;n.hoverIntent_t=setTimeout(function(){l(t,n)},i.interval)}};var c=function(e,t){t.hoverIntent_t=clearTimeout(t.hoverIntent_t);t.hoverIntent_s=0;return i.out.apply(t,[e])};var h=function(t){var n=jQuery.extend({},t);var r=this;if(r.hoverIntent_t){r.hoverIntent_t=clearTimeout(r.hoverIntent_t)}if(t.type=="mouseenter"){u=n.pageX;a=n.pageY;e(r).on("mousemove.hoverIntent",f);if(r.hoverIntent_s!=1){r.hoverIntent_t=setTimeout(function(){l(n,r)},i.interval)}}else{e(r).off("mousemove.hoverIntent",f);if(r.hoverIntent_s==1){r.hoverIntent_t=setTimeout(function(){c(n,r)},i.timeout)}}};return this.on({"mouseenter.hoverIntent":h,"mouseleave.hoverIntent":h},i.selector)}})(jQuery)
3652
3653
3654/*! Extend easing to use easeOutCubic */
3655jQuery.extend( jQuery.easing,
3656{
3657	def: 'easeOutQuad',
3658	easeOutCubic: function (x, t, b, c, d) {
3659		return c*((t=t/d-1)*t*t + 1) + b;
3660	}
3661});
3662
3663/*! Bootstrap 3.0.3 Scrollspy customized to suit our needs. */
3664+function ($) { "use strict";
3665
3666  // SCROLLSPY CLASS DEFINITION
3667  // ==========================
3668
3669  function ScrollSpyCustom(element, options) {
3670    var href
3671    var process  = $.proxy(this.process, this)
3672
3673    this.$element       = $(element).is('body') ? $(window) : $(element)
3674    this.$body          = $('body')
3675    this.$scrollElement = this.$element.on('scroll.bs.scroll-spy.data-api', process)
3676    this.options        = $.extend({}, ScrollSpyCustom.DEFAULTS, options)
3677    this.selector       = (this.options.target
3678      || ((href = $(element).attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '')) //strip for ie7
3679      || '') + ' .nav li > a'
3680    this.offsets        = $([])
3681    this.targets        = $([])
3682    this.activeTarget   = null
3683
3684
3685    this.init()
3686    this.refresh()
3687  }
3688
3689  ScrollSpyCustom.DEFAULTS = {
3690    offset: 182
3691  }
3692
3693  ScrollSpyCustom.prototype.init = function () {
3694    var _this = this;
3695    var width = viewportSize.getWidth();
3696    if (width < 768) {
3697        _this.options.offset = 120;
3698    } else {
3699
3700        _this.options.offset = 182;
3701    }
3702
3703    var reTimer;
3704    jQuery(window).on('resize', function() {
3705        clearTimeout(reTimer);
3706        reTimer = setTimeout(function () {
3707            var width = viewportSize.getWidth();
3708
3709            if (width < 768) {
3710                _this.options.offset = 120;
3711            } else {
3712
3713                _this.options.offset = 182;
3714            }
3715        }, 1000);
3716    });
3717  }
3718
3719  ScrollSpyCustom.prototype.refresh = function () {
3720    var offsetMethod = this.$element[0] == window ? 'offset' : 'position'
3721
3722    this.offsets = $([])
3723    this.targets = $([])
3724
3725    var self     = this
3726    var $targets = this.$body
3727      .find(this.selector)
3728      .map(function () {
3729        var $el   = $(this)
3730        var href  = $el.data('target') || $el.attr('href')
3731        var $href = /^#\w/.test(href) && $(href)
3732        if (!$href.length) { // deal with the underscored anchor
3733            href = href + "_";
3734            $href = /^#\w/.test(href) && $(href)
3735        }
3736
3737        return ($href
3738          && $href.length
3739          && [[ $href[offsetMethod]().top + (!$.isWindow(self.$scrollElement.get(0)) && self.$scrollElement.scrollTop()), href ]]) || null
3740      })
3741      .sort(function (a, b) { return a[0] - b[0] })
3742      .each(function () {
3743        self.offsets.push(this[0])
3744        self.targets.push(this[1])
3745      })
3746  }
3747
3748  ScrollSpyCustom.prototype.process = function () {
3749    var scrollTop    = this.$scrollElement.scrollTop() + this.options.offset
3750    var scrollHeight = this.$scrollElement[0].scrollHeight || this.$body[0].scrollHeight
3751    var maxScroll    = scrollHeight - this.$scrollElement.height()
3752    var offsets      = this.offsets
3753    var targets      = this.targets
3754    var activeTarget = this.activeTarget
3755    var i
3756
3757    if (scrollTop >= maxScroll) {
3758      return activeTarget != (i = targets.last()[0]) && this.activate(i)
3759    }
3760
3761    for (i = offsets.length; i--;) {
3762      activeTarget != targets[i]
3763        && scrollTop >= offsets[i]
3764        && (!offsets[i + 1] || scrollTop <= offsets[i + 1])
3765        && this.activate( targets[i] )
3766    }
3767  }
3768
3769  ScrollSpyCustom.prototype.activate = function (target) {
3770    var _this = this;
3771    this.activeTarget = target
3772
3773    // do not do scrollspy handling on elements with 'nospy' class
3774    if($(target).length && !$(target).hasClass('nospy')) {
3775      if (target.charAt(target.length - 1) === '_') { // deal with the underscored anchor
3776          target = target.substring(0, target.length - 1);
3777      }
3778
3779      $(this.selector)
3780        .parents('.active')
3781        .removeClass('active');
3782
3783      var selector = this.selector
3784        + '[data-target="' + target + '"],'
3785        + this.selector + '[href="' + target + '"]';
3786
3787      var active = $(selector)
3788        .parents('li')
3789        .addClass('active');
3790
3791      if (active.parent('.dropdown-menu').length)  {
3792        active = active
3793          .closest('li.dropdown')
3794          .addClass('active');
3795      }
3796
3797      active.trigger('activate.bs.scrollspycustom');
3798    }
3799  }
3800
3801
3802  // SCROLLSPYCustom PLUGIN DEFINITION
3803  // ===========================
3804
3805  var old = $.fn.scrollspycustom
3806
3807  $.fn.scrollspycustom = function (option) {
3808    return this.each(function () {
3809      var $this   = $(this)
3810      var data    = $this.data('bs.scrollspycustom')
3811      var options = typeof option == 'object' && option
3812
3813      if (!data) $this.data('bs.scrollspycustom', (data = new ScrollSpyCustom(this, options)))
3814      if (typeof option == 'string') data[option]()
3815    })
3816  }
3817
3818  $.fn.scrollspycustom.Constructor = ScrollSpyCustom
3819
3820
3821  // SCROLLSPY NO CONFLICT
3822  // =====================
3823
3824  $.fn.scrollspycustom.noConflict = function () {
3825    $.fn.scrollspycustom = old
3826    return this
3827  }
3828
3829
3830  // SCROLLSPY DATA-API
3831  // ==================
3832
3833  $(window).on('load', function () {
3834    $('[data-spy-custom="scroll"]').each(function () {
3835      var $spy = $(this)
3836      $spy.scrollspycustom($spy.data())
3837    })
3838  })
3839
3840    $.fn.simpleSpinner = function(opts) {
3841        var conf = {
3842            animationInterval: 130,
3843            frameCount: 19,
3844            posShift: 30
3845        };
3846        if (opts) { $.extend(conf, opts); }
3847
3848        return this.each(function() {
3849            var spinner = $(this),
3850                frame = 0,
3851                newPos = 0;
3852
3853            // Loop through animation
3854            (function animate() {
3855                setTimeout(function() {
3856                    // Reset if we've hit our frameCount, otherwise shift
3857                    if (frame >= conf.frameCount - 1) {
3858                        newPos = 0;
3859                        frame = 0;
3860                    } else {
3861                        newPos = newPos + conf.posShift;
3862                        frame++;
3863                    }
3864
3865                    // Wouldn't mind adding an option to allow for left to right sprites.
3866                    spinner.css('background-position', '0 -' + newPos + 'px');
3867
3868                    animate();
3869                }, conf.animationInterval);
3870            })();
3871        });
3872    };
3873
3874}(jQuery);
3875
3876jQuery.fn.extend({
3877    ensureLoad: function(handler) {
3878        return this.each(function() {
3879            if(this.complete) {
3880                handler.call(this);
3881            } else {
3882                $(this).load(handler);
3883            }
3884        });
3885    }
3886});
3887
3888/**
3889 * Prevent double form submission.
3890 * -------------------------------
3891 * This plugin solves an MSIE quirk that prevents data from
3892 * being submitted whenever the submit button's state is disabled.
3893 * The solution is to attach a flag to the form instead and to check
3894 * that value before executing default behaviour on form submit.
3895 *
3896 * Discussion:
3897 * https://stackoverflow.com/questions/2830542/prevent-double-submission-of-forms-in-jquery
3898 *
3899 * Usage:
3900 * $('form').preventDoubleSubmission();
3901 *
3902 */
3903jQuery.fn.preventDoubleSubmission = function() {
3904  $(this).one('submit', function(e){
3905	
3906	console.log("form.submit event fired ..", new Date().valueOf());
3907
3908    var $form = $(this);
3909    if ($form.data('submitted') === true) {
3910      // Previously submitted - don't submit again
3911      console.log("shc-form already submitted. Preventing double submission.");
3912      $form.find('input[type=submit],button[type=submit]').prop('disabled',true);
3913      e.preventDefault();
3914    } else {
3915      // Mark it so that the next submit can be ignored
3916      $form.data('submitted', true);
3917    }
3918  });
3919  // Keep chainability
3920  return this;
3921};
3922
3923/*
3924 * Add Polyfills here.
3925 * At this time SHC is currently supporting MSIE8 users.
3926 *
3927 */
3928
3929// Production steps of ECMA-262, Edition 5, 15.4.4.19
3930// Reference: http://es5.github.com/#x15.4.4.19
3931// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
3932if (!Array.prototype.map) {
3933    Array.prototype.map = function (callback, thisArg) {
3934        var T, A, k;
3935        if (this == null) {
3936            throw new TypeError(" this is null or not defined");
3937        }
3938        var O = Object(this);
3939        var len = O.length >>> 0;
3940        if (typeof callback !== "function") {
3941            throw new TypeError(callback + " is not a function");
3942        }
3943        if (thisArg) {
3944            T = thisArg;
3945        }
3946        A
3946 = new Array(len);
3947        k = 0;
3948        while (k < len) {
3949            var kValue, mappedValue;
3950            if (k in O) {
3951                var Pk = k.toString();
3952                kValue = O[Pk];
3953                mappedValue = callback.call(T, kValue, k, O);
3954                A[Pk] = mappedValue;
3955            }
3956            k++;
3957        }
3958        return A;
3959    };
3960}
3961
3962//ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from
3963//Production steps of ECMA-262, Edition 6, 22.1.2.1
3964if (!Array.from) {
3965    Array.from = (function () {
3966        var toStr = Object.prototype.toString;
3967        var isCallable = function (fn) {
3968            return typeof fn === 'function' || toStr.call(fn) === '[object Function]';
3969        };
3970        var toInteger = function (value) {
3971            var number = Number(value);
3972            if (isNaN(number)) {
3973                return 0;
3974            }
3975            if (number === 0 || !isFinite(number)) {
3976                return number;
3977            }
3978            return (number > 0 ? 1 : -1) * Math.floor(Math.abs(number));
3979        };
3980        var maxSafeInteger = Math.pow(2, 53) - 1;
3981        var toLength = function (value) {
3982            var len = toInteger(value);
3983            return Math.min(Math.max(len, 0), maxSafeInteger);
3984        };
3985
3986        // The length property of the from method is 1.
3987        return function from(arrayLike/*, mapFn, thisArg */) {
3988            // 1. Let C be the this value.
3989            var C = this;
3990
3991            // 2. Let items be ToObject(arrayLike).
3992            var items = Object(arrayLike);
3993
3994            // 3. ReturnIfAbrupt(items).
3995            if (arrayLike == null) {
3996                throw new TypeError('Array.from requires an array-like object - not null or undefined');
3997            }
3998
3999            // 4. If mapfn is undefined, then let mapping be false.
4000            var mapFn = arguments.length > 1 ? arguments[1] : void undefined;
4001            var T;
4002            if (typeof mapFn !== 'undefined') {
4003                // 5. else
4004                // 5. a If IsCallable(mapfn) is false, throw a TypeError exception.
4005                if (!isCallable(mapFn)) {
4006                    throw new TypeError('Array.from: when provided, the second argument must be a function');
4007                }
4008
4009                // 5. b. If thisArg was supplied, let T be thisArg; else let T be undefined.
4010                if (arguments.length > 2) {
4011                    T = arguments[2];
4012                }
4013            }
4014
4015            // 10. Let lenValue be Get(items, "length").
4016            // 11. Let len be ToLength(lenValue).
4017            var len = toLength(items.length);
4018
4019            // 13. If IsConstructor(C) is true, then
4020            // 13. a. Let A be the result of calling the [[Construct]] internal method
4021            // of C with an argument list containing the single item len.
4022            // 14. a. Else, Let A be ArrayCreate(len).
4023            var A = isCallable(C) ? Object(new C(len)) : new Array(len);
4024
4025            // 16. Let k be 0.
4026            var k = 0;
4027            // 17. Repeat, while k < len… (also steps a - h)
4028            var kValue;
4029            while (k < len) {
4030                kValue = items[k];
4031                if (mapFn) {
4032                    A[k] = typeof T === 'undefined' ? mapFn(kValue, k) : mapFn.call(T, kValue, k);
4033                } else {
4034                    A[k] = kValue;
4035                }
4036                k += 1;
4037            }
4038            // 18. Let putStatus be Put(A, "length", len, true).
4039            A.length = len;
4040            // 20. Return A.
4041            return A;
4042        };
4043    }());
4044}
4045
4046//ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith
4047if (!String.prototype.endsWith) {
4048    String.prototype.endsWith = function(search, this_len) {
4049        if (this_len === undefined || this_len > this.length) {
4050            this_len = this.length;
4051        }
4052        return this.substring(this_len - search.length, this_len) === search;
4053    };
4054}
4055// The SHC NameSpace is a top-level global object in which other
4056// common JS classes can be attached to.
4057// -----------------------
4058// [email protected]
4059
4060/**
4061 * SHC.Namespace() is a utility function for safely declaring
4062 * JS namespaces for top level SHC object.
4063 *
4064 * usage:
4065 * SHC.package.SomeClass = SHC.Namespace(SHC, "SHC.package.SomeClass");
4066 *
4067 * @param ns the parent object (SHC).
4068 * @param ns_string the object's namespaced path (e.g. SHC.ui.ComponentName)
4069 * @returns {*}
4070 * @constructor
4071 */
4072SHC.Namespace = function( ns, ns_string ) {
4073    "use strict";
4074    var parts = ns_string.split('.'),
4075        parent = ns,
4076        pl, i;
4077    if (parts[0] === "SHC") {
4078        parts = parts.slice(1);
4079    }
4080    pl = parts.length;
4081    for (i = 0; i < pl; i++) {
4082        //create a property if it doesnt exist
4083        if (typeof parent[parts[i]] === 'undefined') {
4084            parent[parts[i]] = {};
4085        }
4086        parent = parent[parts[i]];
4087    }
4088    return parent;
4089};
4090
4091/**
4092 * SHC.Class() is a utility function for implementing prototype based
4093 * inheritance in javascript without hard dependencies from jQuery.
4094 *
4095 * usage:
4096 * SHC.package.SomeClass = new SHC.Class();
4097 *
4098 * SHC.package.SomeClass.include({
4099 *      // constructor
4100 *      init: function(something) {
4101 *          this.value = something;
4102 *      },
4103 *      hello: function() {
4104 *          console.log("Hello, ", this.value);
4105 *      }
4106 * });
4107 *
4108 * var obj = new SHC.package.SomeClass("world");
4109 * obj.hello();
4110 *
4111 * @param parent - which preexisting object to extend.
4112 * @returns {Function}
4113 * @constructor
4114 */
4115
4116SHC.Class = function(parent) {
4117    var klass = function() {
4118        this.init.apply(this,arguments);
4119        klass.parent = parent;
4120    };
4121    if (parent) {
4122        var subclass = function(){};
4123        subclass.prototype = parent.prototype;
4124        klass.prototype = new subclass();
4125    }
4126    klass.prototype.init = function(){};
4127    klass.fn = klass.prototype;
4128    klass.fn.parent = klass;
4129    // klass._super = klass.__proto__; // deprecated
4130
4131    klass.extend = function(obj) {
4132        var extended = obj.extended;
4133        for (var i in obj) {
4134            klass[i] = obj[i];
4135        }
4136        if (extended) {
4137            extended(klass);
4138        }
4139    };
4140
4141    klass.include = function(obj) {
4142        var included = obj.included;
4143        for(var i in obj) {
4144            klass.fn[i] = obj[i];
4145        }
4146        if (included) {
4147            included(klass);
4148        }
4149    };
4150	return klass;
4151};
4152
4153// Initialize config namespace.
4154SHC.Namespace(SHC,"SHC.config");
4155SHC.Namespace(SHC, 'SHC.util.WCM');
4156
4157(function(SHC) { "use strict";
4158	SHC.util.WCM = {
4159		/**
4160		 * Check if we're in edit mode
4161		 * @return boolean
4162		 */
4163		isEditMode: function() {
4164			return (CQ && CQ.WCM) ? CQ.WCM.isEditMode(true) : false;
4165		},
4166
4167		/**
4168		 * Check if we're in preview mode
4169		 * @return boolean
4170		 */
4171		isPreviewMode: function() {
4172			return (CQ && CQ.WCM) ? CQ.WCM.isPreviewMode(true) : false;
4173		},
4174
4175		/**
4176		 * Check if we're in design mode
4177		 * @return boolean
4178		 */
4179		isDesignMode: function() {
4180			return (CQ && CQ.WCM) ? CQ.WCM.isDesignMode(true) : false;
4181		},
4182
4183		/**
4184		 * Check if we're in disabled mode
4185		 * @return boolean
4186		 */
4187		isDisabledMode: function() {
4188			return (!CQ.WCM);
4189		},
4190
4191		/**
4192		 * Check if we're in either edit mode or design mode
4193		 * @return boolean
4194		 */
4195		isAuthorMode: function() {
4196			return this.isEditMode() || this.isDesignMode();
4197		},
4198
4199		/**
4200		 * Get the current mode back as a string
4201		 * @returns string
4202		 */
4203		getMode: function() {
4204			if (CQ && CQ.WCM) {
4205				return CQ.WCM.getMode();
4206			}
4207			return 'disabled';
4208		}
4209	};
4210})(SHC);
4211
4212SHC.Namespace(SHC, "SHC.util");
4213
4214/**
4215 * Function throttling utility.
4216 * @param callback
4217 * @param timeout
4218 * @returns {Function}
4219 * @constructor
4220 */
4221SHC.util.throttle = function(callback, timeout) {
4222    var timeoutID, to = timeout || 200;
4223    return function() {
4224        var scope = this, args = arguments;
4225        clearTimeout(timeoutID);
4226        timeoutID = setTimeout(function() {
4227            callback.apply(scope, Array.prototype.slice.call(args));
4228        }, to);
4229    };
4230};
4231
4232/**
4233 * swap references.
4234 * @param obj1
4235 * @param obj2
4236 * @returns new obj1
4237 */
4238SHC.util.swap = function(obj1, obj2) {
4239    var tmp = obj1;
4240    obj1 = obj2;
4241    obj2 = tmp;
4242    return obj1;
4243};
4244
4245/**
4246 * generate a number between min and max (inclusive).
4247 * generate a number greater than 0 when only max is passed
4248 * @param min
4249 * @param max
4250 * @returns {number|string}
4251 */
4252SHC.util.random = function(min, max) {
4253    if(max == null) {
4254        max = min;
4255        min = 0;
4256    }
4257    return Math.floor((Math.random() * max) + min);
4258};
4259
4260/**
4261 * Shuffle elements in an array.
4262 * @param list
4263 * @returns {*}
4264 */
4265SHC.util.shuffle = function(list) {
4266    if(!list) {
4267        return null;
4268    }
4269    var copy = [];
4270    var length = list.length;
4271    while(length) {
4272        var random = SHC.util.random(0, length);
4273        copy.push(list[random]);
4274        list.splice(random, 1);
4275        length--;
4276    }
4277    return copy;
4278};
4279
4280/**
4281 *Implement the Ellipsis
4282 * @param text
4283 * @param max number of character
4284 * @returns{truncated text}
4285 */
4286SHC.util.ellipsis = function(text, maxLength) {
4287    if(text && maxLength) {
4288        return (text.length > maxLength) ? text.substr(0, maxLength - 3) + "..." : text;
4289    }
4290    return "";
4291};
4292
4293/**
4294 * Return the substring located at index using delimiter.
4295 * @param text
4296 * @param delimiter
4297 * @param index
4298 * @returns {*}
4299 */
4300SHC.util.splitSelect = function(text, delimiter, index) {
4301    if(!text || !delimiter) {
4302        return "";
4303    }
4304    if(text.match(delimiter)) {
4305        var result = text.split(delimiter);
4306        if(result && result.length && result[index]) {
4307            return result[index];
4308        } else {
4309            return "";
4310        }
4311    }
4312    return text;
4313};
4314
4315/**
4316 * Highlight a specific line with a matching word.
4317 * @param line
4318 * @param word
4319 * @returns {XML|string|void}
4320 */
4321SHC.util.highlight = function(line, word) {
4322    var regex = new RegExp('\\b(' + word + ')', 'gi');
4323    return line.replace(regex, "<b>$1</b>");
4324};
4325
4326/**
4327 * Get keys from a hash.
4328 * @param map
4329 * @returns {Array}
4330 */
4331SHC.util.getKeys = function(map) {
4332    var keys = [], p;
4333    for(p in map) {
4334        if(Object.prototype.hasOwnProperty.call(map, p)) {
4335            keys.push(p);
4336        }
4337    }
4338    return keys;
4339};
4340
4341/**
4342 * Capitalize a given field in an array of objects.
4343 * @param list
4344 * @param keyProperty
4345 * @returns {*}
4346 */
4347SHC.util.capitalizeObjectList = function(list, keyProperty) {
4348    if (!list) {
4349        return null;
4350    }
4351    for (var i = 0, n = list.length; i < n; i++) {
4352        var str = list[i][keyProperty];
4353        list[i][keyProperty] = (str) ? SHC.util.capitalize(str) : "";
4354    }
4355    return list;
4356};
4357
4358/**
4359 * Find object with regexp matching property in ObjectList.
4360 * @param list
4361 * @param keyProperty
4362 * @param regexp
4363 * @returns {number}
4364 */
4365SHC.util.findFirstMatch = function(list, keyProperty, regexp) {
4366    if(!list) {
4367        return -1;
4368    }
4369    for(var i = 0, n = list.length; i < n; i++) {
4370        if(regexp.test(list[i][keyProperty])) {
4371            return i;
4372        }
4373    }
4374    return -1;
4375};
4376
4377/**
4378 * rebalance a map of arrays but limit the total
4379 * elements to targetCount. Pushes items in sequence with priority given to all items
4380 * @param queues
4381 * @param targetCount
4382 * @returns {*}
4383 */
4384SHC.util.balancedTruncate = function (queues, targetCount) {
4385    var result = {};
4386    var keys = SHC.util.getKeys(queues);
4387    var total = 0;
4388    //calculate the total number of elements in the queues object
4389    for (var a = 0;
4389 a < keys.length; a++) {
4390      if (queues[keys[a]]) {
4391        total = total + queues[keys[a]].length;
4392      }
4393    }
4394    if (total > targetCount) {
4395        var i = 0;
4396        var k = 0;
4397        while (k < targetCount) {
4398            for (var j = 0; j < keys.length; j++) {
4399                var currentKey = keys[j];
4400                if (queues[currentKey] && queues[currentKey][k]) {
4401                    if (!result[currentKey]) {
4402                        result[currentKey] = [];
4403                        result[currentKey].push(queues[currentKey][k]);
4404                    }
4405                    else {
4406                        result[currentKey].push(queues[currentKey][k]);
4407                    }
4408                    i++;
4409                    if (i === targetCount) {
4410                        return result;
4411                    }
4412                }
4413            }
4414            k++;
4415        }
4416        return result;
4417    }
4418    else {
4419        return queues;
4420    }
4421};
4422
4423/**
4424 * rebalance a map of arrays based on passed in searchTerm and pull results that exactly matches with search term to the beginning
4425 * @param queues
4426 * @param pred
4427 * @returns {*}
4428 */
4429SHC.util.exactMatchRebalance = function (queues, pred) {
4430    var searchTerm = pred.toString().toUpperCase();
4431    for (var pr in queues) {
4432        var prop = queues[pr];
4433        if (prop.length > 1) {
4434            for (var i = 0; i < prop.length; i++) {
4435                var exactMatch;
4436                if (prop[i].title && prop[i].title.toUpperCase() === searchTerm) {
4437                    exactMatch = prop.splice(i, 1);
4438                    prop.unshift(exactMatch[0]);
4439                    break;
4440                }
4441                else if (prop[i].displayName && prop[i].displayName.toUpperCase() === searchTerm) {
4442                    exactMatch = prop.splice(i, 1);
4443                    prop.unshift(exactMatch[0]);
4444                    break;
4445                }
4446            }
4447        }
4448    }
4449    return queues;
4450};
4451
4452SHC.util.countProperties = function(obj) {
4453    var count = 0;
4454    for(var prop in obj) {
4455        if(obj.hasOwnProperty(prop)) {
4456            ++count;
4457        }
4458    }
4459    return count;
4460};
4461
4462/**
4463 * Convert a list to a map using keyProperty as the key
4464 * and dataProperty as the data source.
4465 * @param list
4466 * @param keyProperty
4467 * @param dataProperty
4468 * @returns {*}
4469 */
4470SHC.util.arrayToMapOfLists = function(list, keyProperty, dataProperty) {
4471    var result = {};
4472    for(var i = 0, n = list.length; i < n; i++) {
4473        var listItem = list[i];
4474        if(listItem[keyProperty]) {
4475            result[listItem[keyProperty]]
4476                = (listItem[dataProperty]) ? listItem[dataProperty] : [];
4477        }
4478    }
4479    return result;
4480};
4481
4482/**
4483 * Find a term in a list.
4484 * @param list
4485 * @param term
4486 * @returns {boolean}
4487 */
4488SHC.util.inArray = function(list, term) {
4489    if(!list) {
4490        return false;
4491    } else if(list.length) {
4492        for(var i = 0, n = list.length; i < n; i++) {
4493            if(list[i] === term) {
4494                return true;
4495            }
4496        }
4497        return false;
4498    }
4499};
4500
4501/**
4502 * Filter a list based on an array of regexp patterns.
4503 * If attributeName is provided, use that object attribute
4504 * for pattern matching.
4505 * @param list
4506 * @param regexArray
4507 * @param attributeName
4508 * @returns {Array}
4509 */
4510SHC.util.filterListMulti = function(list, regexArray, attributeName) {
4511    var result = [];
4512    if(!list || !regexArray) {
4513        return [];
4514    }
4515    for(var i = 0, n = list.length; i < n; i++) {
4516        for(var j = 0, arrLen = regexArray.length; j < arrLen; j++) {
4517            // If attribute name is provided, match by attribute name
4518            // otherwise treat list as an array of strings.
4519            if(attributeName && regexArray[j].test(list[i][attributeName]) ||
4520                regexArray[j].test(list[i])) {
4521                result.push(list[i]);
4522                break;
4523            }
4524        }
4525    }
4526    return result;
4527};
4528
4529/**
4530 * Capitalize each first character of words in a string.
4531 * @param text
4532 * @returns {XML|string|void}
4533 */
4534SHC.util.capitalize = function(text) {
4535    return text.replace(/(^|\s)([a-z])/g, function(m, p1, p2) {
4536        return p1 + p2.toUpperCase();
4537    });
4538};
4539
4540/**
4541 * Given an array of browser specific css properties,
4542 * return the one supported by current browser.
4543 * @param propArray
4544 * @returns {*}
4545 */
4546SHC.util.getCssProperty = function(propArray) {
4547    var root = document.documentElement;
4548    for(var i = 0; i < propArray.length; i++) {
4549        if(propArray[i] in root.style) {
4550            return propArray[i];
4551        }
4552    }
4553};
4554
4555/**
4556 * Balance a list into colCount number of columns.
4557 * @param list
4558 * @param colCount
4559 * @returns {{}}
4560 */
4561SHC.util.listToColumns = function(list, colCount) {
4562    if(!list || !colCount) {
4563        return {};
4564    }
4565    // firstpass
4566    var scratch = {};
4567    for(var i = 0, n = list.length, col = 1; i <= n; i++) {
4568        if(!scratch["col" + col]) {
4569            scratch["col" + col] = [];
4570        }
4571        if(list[i]) {
4572            scratch["col" + col].push(list[i]);
4573        }
4574        if(col < colCount) {
4575            col++;
4576        } else {
4577            col = 1;
4578        }
4579    }
4580    var columns = {};
4581    for(i = 1; i <= colCount; i++) {
4582        var column = "col" + i,
4583            len = (scratch[column] && scratch[column].length) ? scratch[column].length : 0,
4584            sublist = list.splice(0, len);
4585        columns[column] = sublist;
4586    }
4587    return columns;
4588};
4589
4590/**
4591 * Return the version number of IE detected
4592 * @returns {Number}
4593 */
4594SHC.util.msieVersion = function() {
4595    var myNav = navigator.userAgent.toLowerCase();
4596    var ie = myNav.split('msie ');
4597    if (ie.length === 2) {
4598        var ieVersion = ie[1].substring(0, 2);
4599        return parseInt(ieVersion);
4600    }
4601    return null;
4602};
4603
4604/**
4605 * Return false if not IE
4606 * else true
4607 */
4608SHC.util.isIE = function() {
4609    var ua = window.navigator.userAgent;
4610    var msie = ua.indexOf("MSIE ");
4611
4612    if(msie > 0 || !!ua.match(/Trident.*rv\:11\./)) {
4613        return true;
4614    } else {
4615        return false;
4616    }
4617    return false;
4618};
4619
4620/**
4621 * Returns true when device is iPad, iPhone, or iPod
4622 * @returns {boolean}
4623 */
4624SHC.util.isIOS = function() {
4625    var i = 0,
4626        iOS = false,
4627        iDevice = ['iPad', 'iPhone', 'iPod'];
4628
4629    for(; i < iDevice.length; i++) {
4630        if(navigator.platform === iDevice[i]) {
4631            iOS = true;
4632            break;
4633        }
4634    }
4635    if(navigator.platform.indexOf("iPod") !== -1) {
4636        iOS = true;
4637    }
4638    return iOS;
4639};
4640
4641/**
4642 * Returns true when device is an android device
4643 * @returns {boolean}
4644 */
4645SHC.util.isAndroid = function() {
4646    return (navigator.userAgent.toLowerCase().indexOf('android') > -1);
4647};
4648
4649/**
4650 * Polyfill for placeholder text for IE8 and 9
4651 * @param id
4652 * @param placeholder
4653 */
4654SHC.util.addPlaceholder = function(id, placeholder) {
4655    var el = document.getElementById(id);
4656    el.placeholder = placeholder;
4657    el.onfocus = function() {
4658        if(this.value === this.placeholder) {
4659            this.value = '';
4660            el.style.cssText = '';
4661        }
4662    };
4663    el.onblur = function() {
4664        if(this.value.length === 0) {
4665            this.value = this.placeholder;
4666            el.style.cssText = 'color:#A9A9A9;';
4667        }
4668    };
4669    el.onblur();
4670};
4671
4672/**
4673 *
4674 */
4675SHC.util.getURLSearchTerm = function(pathName) {
4676    var searchChunk = pathName.match(/\.html\/(.*)/);
4677    if(searchChunk && searchChunk[1]) {
4678        var searchterm = searchChunk[1].split(/&(.+)/);
4679        var passthrough;
4680        if (searchterm [1]) {
4681            passthrough = decodeURIComponent(searchterm[1]).split("|");
4682        }
4683        if (searchterm[0]) {
4684            return decodeURIComponent(searchterm[0]);
4685        } else if (passthrough && passthrough.length === 4) {
4686            return decodeURIComponent(passthrough[3]);
4687        }
4688    }
4689    return "";
4690};
4691
4692/**
4693 * Reliable checking for loaded images
4694 * @author Remington Reed
4695 * @param imgs Various formats of images, could be a string, Image object, element, jQuery element, or an array of the preceeding
4696 * @returns {Array} List of loaded images as jQuery elements
4697 */
4698SHC.util.imgLoadCheck = function(imgs, opts) {
4699    var unloadedImgs = [],
4700        loadedImgs = [],
4701        workArea = $('#image-load-workarea'),
4702        conf = {
4703            onStart: null,
4704            onCheck: null,
4705            onComplete: null
4706        };
4707
4708
4709    // Check if the staging area already exists
4710    if(!workArea.length) {
4711        // create invisible stage for reliably checking width
4712        workArea = $('<div></div>', {
4713            id: 'image-load-workarea',
4714            width: 1,
4715            height: 1,
4716            css: { // let's hide this sucker
4717                'visibility': 'hidden',
4718                'position': 'absoulte',
4719                'right': '100%',
4720                'clip': 'rect(0 0 0 0)',
4721                'overflow': 'hidden',
4722                'z-index': '-1000'
4723            }
4724        })
4725            .appendTo('body');
4726    }
4727
4728    // if options are passed in, merge them with conf
4729    if(opts) {
4730        $.extend(conf, opts);
4731    }
4732
4733    // run a start callback function if provided
4734    if(typeof conf.onStart === 'function') {
4735        conf.onStart(imgs);
4736    }
4737
4738    // create a proper array of jQuery images
4739    if($.type(imgs) !== 'array') {
4740        // create an array out of our single item
4741        imgs = new Array(imgs);
4742    }
4743
4744    $.each(imgs, function(idx, img) {
4745        var jImg = null;
4746        if($.type(img) === 'string') {
4747            jImg = $('<img />', {src: img});
4748        } else {
4749            jImg = $(img);
4750        }
4751        // throw image into invisible staging area
4752        jImg.appendTo(workArea);
4753        unloadedImgs.push(jImg);
4754    });
4755
4756    // self executing loop every 50 ms
4757    (function imgCheckLoop() {
4758        // if everything is loaded, then move on
4759        if(unloadedImgs.length === 0) {
4760            // run a complete callback function if provided
4761            if(typeof conf.onComplete === 'function') {
4762                conf.onComplete(loadedImgs);
4763            }
4764
4765            // once all images are done loading, return the set
4766            return loadedImgs;
4767        }
4768
4769        setTimeout(function() {
4770            // run through each item
4771            $.each(unloadedImgs, function(idx, image) {
4772                // run a check callback function if provided
4773
4774                if(typeof conf.onCheck === 'function') {
4775                    conf.onCheck(image);
4776                }
4777
4778                var jsImg = image[0];
4779                // check if image is loaded
4780                if(jsImg.complete || (typeof jsImg.naturalWidth !== 'undefined' && jsImg.naturalWidth > 0)) {
4781                    // if it has a width or is complete, pop and push into loadedImgs
4782                    loadedImgs.push(image.remove());
4783                    unloadedImgs.splice(idx, 1);
4784                }
4785            });
4786            imgCheckLoop();
4787        }, 50);
4788    })();
4789};
4790
4791/**
4792 * javascript method for obfuscating /content/shc/en from end users while maintaining functionality in author and publish
4793 * @author James Collier
4794 * @param path A full or partial path that may or may not contain /content/shc/en
4795 * @param addPrefix if true (or another non-undefined value) then "/content/shc/en" will be prepended to the path (if necessary)
4796 * @returns {String} appropriately adjusted path
4797 */
4798SHC.util.adjustPath = function(path, addPrefix) {
4799    if(typeof path !== 'string') {
4800        return "";
4801    }
4802
4803    var authorPort = ":4502",
4804        publishPort = ":4503",
4805        aemqa = "aut1.aemqa";
4806    if ( window.location.toString().indexOf(authorPort) === -1 &&
4807         window.location.toString().indexOf(publishPort) === -1 &&
4808         window.location.toString().indexOf(aemqa) === -1 ) {
4809        // remove the /content/shc/en from non-author and non-publish environments
4810        path = path.replace("/content/shc/en", "");
4811        path = path.replace("/content/shca/en", "");
4812        path = path.replace("/content/valleycare/en", "/tri-valley");
4813        path = path.replace("/content/stanfordlab/en", "");
4814    } else if(addPrefix) {
4815        if(window.location.toString().indexOf('search-results.doctors') > 1) {
4816            path = "/content/shc/en/v2" + path;
4817        }
4818        else {
4819            path = "/content/shc/en" + path;
4820        }
4821    }
4822    return path;
4823};
4824
4825/**
4826 * Console utility function for viewing effective JS and CSS declarations.
4827 */
4828SHC.util.scanlib = function() {
4829    var i = 0;
4830    console.log("============ head css ============");
4831    $("head link[rel=stylesheet][href]").each(function(idx, el) {
4832        var source = $(el).attr("href");
4833        if(source.indexOf("http") !== 0) {
4834            console.log("head stylesheet:", ++i, source);
4835        }
4836    });
4837    i = 0;
4838    console.log("============ head js ==============");
4839    $("head script[src]").each(function(idx, el) {
4840        var source = $(el).attr("src");
4841        if(source.indexOf("http") !== 0) {
4842            console.log("head script:", ++i, source);
4843        }
4844    });
4845    i = 0;
4846    console.log("------------ body js -------------");
4847    $("body script[src]").each(function(idx, el) {
4848        var source = $(el).attr("src");
4849        if(source.indexOf("http") !== 0) {
4850            console.log("body script:", ++i, source);
4851        }
4852    });
4853};
4854
4855/**
4856 * Check if a string ends with suffix.
4857 * @param str
4858 * @param suffix
4859 * @returns {boolean}
4860 */
4861SHC.util.endsWith = function(str, suffix) {
4862    return str.indexOf(suffix, str.length - suffix.length) !== -1;
4863};
4864
4865/**
4866 * Adjust path then append ".html"
4867 * @param url
4868 * @returns {String}
4869 */
4870SHC.util.adjustUrl = function(url) {
4871    var newUrl = SHC.util.adjustPath(url);
4872    if(newUrl && !SHC.util.endsWith(newUrl, ".html")) {
4873        newUrl = newUrl + ".html";
4874    }
4875    return newUrl;
4876};
4877
4878/**
4879 * Global search and replace with proper character escaping.
4880 *
4881 * http://stackoverflow.com/questions/1144783/replacing-all-occurrences-of-a-string-in-javascript
4882 *
4883 * @param str string to process
4884 * @param txt text to look for
4885 * @param newTxt text to replace with
4886 * @returns {*|XML|string|void}
4887 */
4888SHC.util.replaceAll = function(str, txt, newTxt) {
4889    var escapeRegExp = function(fixStr) {
4890        return fixStr.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
4891    };
4892    return str.replace(new RegExp(escapeRegExp(txt), 'g'), newTxt);
4893};
4894
4895SHC.util.getPathFromUrl = function(url) {
4896    if(url) {
4897        url = url.replace(/^.*\/\/[^\/]+/, '');
4898    }
4899    return url;
4900};
4901
4902/**
4903 * Check if the current URL has the specified JCR selector.
4904 */
4905SHC.util.hasSelector = function(jcrSelector, pathName) {
4906    var subpaths = pathName.split("/"),
4907        last = subpaths[subpaths.length - 1];
4908    if(!last) {
4909        return false;
4910    }
4911    return (last.indexOf("." + jcrSelector + ".") > -1);
4912};
4913
4914/**
4915 * Detect if the URL has a search-term and accordingly check if the current URL has the specified JCR selector.
4916 */
4917SHC.util.hasSelectorAndSearchTerm = function(jcrSelector, pathName) {
4918    //Shows in the predictive search menu only what is selected by the search controller on pass-through pages
4919    if(pathName.indexOf('/&sp_trialLocks') > 0){
4920        pathName = pathName.split('&sp_trialLocks')[0] + 'pass';
4921    }
4922    if(pathName.indexOf('/&sp_clinics') > 0){
4923        pathName = pathName.split('&sp_clinics')[0] + 'pass';
4924    }
4925    if(pathName.indexOf('/&sp_conditions') > 0){
4926        pathName = pathName.split('&sp_conditions')[0] + 'pass';
4927    }
4928
4929    var subpaths = pathName.split("/"),
4930        last = subpaths[subpaths.length - 1];
4931
4932    if(last.indexOf(".html") === -1) {
4933        last = subpaths[subpaths.length - 2];
4934    }
4935
4936    if(!last) {
4937        return false;
4938    }
4939    return (last.indexOf("." + jcrSelector + ".") > -1);
4940};
4941
4942/**
4943 * Check if str exists in pathName
4944 *
4945 * @param str string to process
4946 * @param pathName text to replace with
4947 * @returns boolean
4948 */
4949SHC.util.pathContains = function(str, pathName) {
4950    return (pathName !== undefined && pathName.indexOf(str) > -1);
4951};
4952
4953SHC.util.getPathFromUrl = function(url) {
4954    if(url && url.indexOf('#') !== 0) {
4955        var a = document.createElement('a');
4956        a.href = url;
4957        return a.pathname;
4958    }
4959    return url;
4960};
4961
4962SHC.util.getClinicPassThroughInfo = function() {
4963    var pathname = decodeURIComponent(window.location.pathname),
4964        clinicUrl = null,
4965        clinicName = null,
4966        groupName = null;
4967
4968    if(pathname) {
4969        var split = pathname.split('|');
4970        if (split && split.length > 2) {
4971            var isClinicLocation = split[0].split('&');
4972            clinicUrl = isClinicLocation[1] === 'sp_clinicLocations' ? pathname : split[1];
4973            clinicName = split[2];
4974            groupName = clinicUrl.replace(/\.html?$/, '').split('/').pop();
4975        }
4976    }
4977
4978    return {"clinicUrl": clinicUrl, "clinicName": clinicName, "groupName": groupName};
4979};
4980
4981SHC.util.getMultiClinicPassThroughInfo = function(groupName) {
4982    var l3ServletRequestPath = "/bin/api/v1/content/shcmap.clinic.";
4983    var targetUrl = l3ServletRequestPath + groupName + ".json";
4984
4985    // hit our servlet to give us our info about related l3 clinics
4986    return jQuery.ajax({
4987        url: targetUrl,
4988        async: false,
4989        contentType: "application/json"
4990    });
4991};
4992
4993SHC.util.arrayContains = function(needle, arrhaystack) {
4994    return arrhaystack.indexOf(needle) > -1;
4995};
4996
4997SHC.util.getLocationPassThroughInfo = function() {
4998    var pathname = window.location.pathname;
4999    var location = null;
5000    var address = null;
5001
5002    if(pathname) {
5003        var regexResult = new RegExp(".*html/&sp_clinicLocations%7C(.*)%7C(.*)&?").exec(pathname);
5004        if(regexResult && regexResult.length > 2) {
5005            location = decodeURIComponent(regexResult[1]);
5006            address = decodeURIComponent(regexResult[2]);
5007        }
5008    }
5009
5010    return {"location": location, "address": address};
5011};
5012
5013/**
5014 * The location filter vars can have different numbers at the end of them, so we need
5015 * to just grab the key using the text of the key before the number, followed by equal, followed by numbers,
5016 * to get the zip code or the proximity from it.
5017 * @param attr - either sp_q_location or sp_q_max
5018 */
5019SHC.util.getNumericalDistanceVarsFromURL = function(attr) {
5020    var hash = window.location.hash;
5021
5022    if(hash && hash.indexOf(attr) > -1) {
5023        var regexResult = new RegExp(attr + '_[1-9]=[0-9]*').exec(window.location.hash);
5024        var value = regexResult[0].split('=')[1];
5025        return value;
5026    }
5027    return null;
5028};
5029
5030/**
5031 *
5032 * @param Q - Query string being sent to S&P, use this when you can't depend on the URL.
5033 * @returns {*} zip code
5034 */
5035SHC.util.getZipCodeFromQuery = function(Q) {
5036    var zipCodeTermRE = /sp_q_location_[0-9]=\b\d{5}\b/;
5037    var zipCodeTermMatches = zipCodeTermRE.exec(Q);
5038    var zipCodeTermString = zipCodeTermMatches[0];
5039    var zipCodeRE = /\b\d{5}\b/;
5040    var zipCodeMatches = zipCodeRE.exec(zipCodeTermString);
5041    return zipCodeMatches[0];
5042};
5043
5044/**
5045 * Returns the zip code radius term from a query string
5046 * @param Q
5047 * @returns something like sp_q_max_2=50
5048 */
5049SHC.util.getZipCodeRadiusTerm = function(Q) {
5050    var radiusRE = /sp_q_max_[0-9]=\b(5|10|25|50)\b/;
5051    var radiusStringMatches = radiusRE.exec(Q);
5052    return radiusStringMatches[0];
5053};
5054
5055/**
5056 * Replaces 5, 10, 25, or 50 from a radius term to 10000
5057 * @param radiusString something like sp_q_max_2=50
5058 * @returns sp_q_max_2=10000
5059 */
5060SHC.util.replaceRadiusWithAnyDistance = function(radiusString) {
5061    var radiusNumberRE = /\b(5|10|25|50)\b/;
5062    var radiusNumberMatches = radiusNumberRE.exec(radiusString);
5063    var radiusNumberString = radiusNumberMatches[0];
5064    var anyRadiusString = radiusString.replace(radiusNumberString, "10000");
5065    return anyRadiusString;
5066};
5067
5068SHC.util.formatDistance = function(distance) {
5069    if(distance === '0.00') {
5070        return 0;
5071    } else if(distance < 10) {
5072        return Math.round(distance * 10) / 10;
5073    } else {
5074        return parseInt(distance);
5075    }
5076};
5077
5078SHC.util.setCookie = function(cname, cvalue, exdays, path) {
5079    var d = new Date();
5080    d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
5081    var expires = "expires=" + d.toUTCString();
5082    document.cookie = cname + "=" + cvalue + "; " + expires + "; path=" + path + ";";
5083};
5084
5085SHC.util.setCookieWithTimeInSeconds = function(cname, cvalue, exseconds, path) {
5086    var d = new Date();
5087    d.setTime(d.getTime() + (exseconds * 1000));
5088    var expires = "expires=" + d.toUTCString();
5089    document.cookie = cname + "=" + cvalue + "; " + expires + "; path=" + path + ";";
5090};
5091
5092SHC.util.getCookie = function(cname) {
5093    var name = cname + "=";
5094    var ca = document.cookie.split(';');
5095    for(var i = 0; i < ca.length; i++) {
5096        var c = ca[i];
5097        while(c.charAt(0) === ' ') {
5098            c = c.substring(1);
5099        }
5100        if(c.indexOf(name) === 0) {
5101            return c.substring(name.length, c.length);
5102        }
5103    }
5104    return "";
5105};
5106
5107/**
5108 * Depending on which specialty toggle is selected (specialty or primary care) determines physician short title displayed
5109 * if there is no toggle present and there are values it will return the first title available, if there are no titles
5110 * it will return blank
5111 * @param attr - from S&P pass in data.groupsToTiles
5112 * @return string - short title
5113 */
5114SHC.util.setPhysicianShortTitle = function(groupsToTitles) {
5115    var shortTitle = "";
5116
5117    if(groupsToTitles && groupsToTitles.length && groupsToTitles[0]) {
5118        var showPrimaryCareTitles = false,
5119            useMedCategoryTitle = false,
5120            useTitleGroups = false,
5121            useAreaOfExpertise = false,
5122            medCatValue = '',
5123            drTitleGroups = '',
5124            areaOfExpertise = '',
5125            primaryCareType = '',
5126            primaryCareTitles = {
5127                'Adults': ['Internal medicine doctor', 'Family medicine doctor'],
5128                'Adults and Children': ['Family medicine doctor'],
5129                'Children': ['Family medicine doctor', 'Pediatrician', 'Pediatric/adolescent gynecologist'],
5130                'Seniors': ['Internal medicine doctor', 'Family medicine doctor', 'Geriatrician'],
5131                'Women Only': ['Obstetrician/gynecologist', 'Gynecologist']
5132            };
5133
5134        //This first one is to check for if we are on Primary or Sepcialty
5135        var urlHash = window.location.hash.toLowerCase();
5136
5137        if(GLOBAL_SEARCH_RESULTS_TEMPLATE.indexOf('shca') > -1 &&
5138            (urlHash.indexOf('sp_prim_care_phy') > -1 || window.location.hash === '')) {
5139            //SHCA
5140            showPrimaryCareTitles = true;
5141        } else if(GLOBAL_SEARCH_RESULTS_TEMPLATE.indexOf('shc') > -1 && urlHash.indexOf('sp_prim_care_phy') > -1 || window.location.hash === '') {
5142            //SHC
5143            showPrimaryCareTitles = true;
5144        }
5145
5146        if(GLOBAL_SEARCH_RESULTS_TEMPLATE.indexOf('shc') > -1 && urlHash.indexOf('sp_prim_care_phy') > -1 || window.location.hash === '') {
5147            //SHC
5148            showPrimaryCareTitles = true;
5149        } else if(GLOBAL_SEARCH_RESULTS_TEMPLATE.indexOf('shca') > -1 &&
5150            (urlHash.indexOf('sp_prim_care_phy') > -1 || window.location.hash === '')) {
5151            //SHCA
5152            showPrimaryCareTitles = true;
5153        }
5154
5155        //We need to check the hash for which filters have been selected.
5156        var splitHash = window.location.hash.split('&');
5157        if(splitHash.length > 0) {
5158            var currentX = 0;
5159            var currentXQuery = '';
5160            var currentQ = 0;
5161            var currentQValue = '';
5162            for(var a = 0; a < splitHash.length; a++) {
5163                var hash = splitHash[a];
5164                if(hash.charAt(0) === 'x') {
5165                    currentX = hash.charAt(1);
5166                    currentXQuery = hash.split('=')[1];
5167                } else if(hash.charAt(0) === 'q') {
5168                    currentQ = hash.charAt(1);
5169                    currentQValue = hash.split('=')[1];
5170                }
5171                if(currentX === currentQ) {// We are on the same value / query.
5172                    if(currentXQuery === 'sp_med_categories') {
5173                        medCatValue = decodeURIComponent(currentQValue);
5174                        useMedCategoryTitle = true;
5175                    }
5176                    if(currentXQuery === 'sp_dr_title_groups') {
5177                        drTitleGroups = decodeURIComponent(currentQValue);
5178                        useTitleGroups = true;
5179                    }
5180                    if(currentXQuery === 'sp_dr_titles') {
5181                        areaOfExpertise = decodeURIComponent(currentQValue);
5182                        useAreaOfExpertise = true;
5183                    }
5184                    if(currentXQuery === "sp_prim_care_types") {
5185                        primaryCareType = decodeURIComponent(currentQValue);
5186                    }
5187                }
5188            }
5189        }
5190
5191        if((useAreaOfExpertise || useMedCategoryTitle || useTitleGroups) && !SHC.util.ClinicalTitles) {
5192            jQuery.ajax({
5193                async: false,
5194                method: "GET",
5195                url: '/bin/api/v1/content/titlesconditionstojson',
5196                dataType: "json",
5197                contentType: "application/json",
5198                timeout: 3000,
5199                success: function(data) {
5200                    SHC.util.ClinicalTitles = data;
5201                }
5202            });
5203        }
5204
5205        var foundTitle = false,
5206            foundGroupTitle = false,
5207            matchingGroupTitle;
5208
5209        titleCheck:
5210            for(var i = 0; i < groupsToTitles.length; i++) {
5211                shortTitle = SHC.util.splitSelect(groupsToTitles[i].groupToTitle, "_", 1);
5212                if(showPrimaryCareTitles) {//We are on Primary Care Toggle
5213                    if(primaryCareType) {
5214                        //We have chosen to use a dr primary Type.
5215                        if(useAreaOfExpertise) {
5216                            shortTitle = areaOfExpertise;
5217                            foundTitle = true;
5218                            break titleCheck;
5219                        } else {
5220                            var primaryCareObject = primaryCareTitles[primaryCareType];
5221                            if(primaryCareObject) {
5222                                if(SHC.util.inArray(primaryCareObject, shortTitle)) {
5223                                    foundTitle = true;
5224                                    break titleCheck;
5225                                }
5226                            }
5227                        }
5228                    } else {
5229                        if(useAreaOfExpertise) {
5230                            shortTitle = areaOfExpertise;
5231                            foundTitle = true;
5232                            break titleCheck;
5233                        } else {
5234                            if(SHC.util.isPrimaryCareObject(primaryCareTitles, shortTitle)) {
5235                                foundTitle = true;
5236                                break titleCheck;
5237                            }
5238                        }
5239                    }
5240                } else {
5241                    if(SHC.util.ClinicalTitles) {
5242                        var fullTitle,
5243                            groupTitle,
5244                            titleObject;
5245
5246                        if(useAreaOfExpertise) {
5247                            //Here we need to find which title goes along with the selected area of expertise.
5248                            shortTitle = areaOfExpertise;
5249                            foundTitle = true;
5250                            break titleCheck;
5251                        } else {
5252                            if(useMedCategoryTitle && useTitleGroups) {
5253                                fullTitle = groupsToTitles[i].groupToTitle;
5254                                groupTitle = SHC.util.splitSelect(groupsToTitles[i].groupToTitle, "_", 0);
5255                                if(groupTitle === drTitleGroups) {
5256                                    foundGroupTitle = true;
5257                                    if(!matchingGroupTitle) {
5258                                        //Only going to set this to be the first title in the list as per requirements of the ticket RSW-6762
5259                                        matchingGroupTitle = shortTitle;
5260                                    }
5261                                    //Do following to add another check to see if we have the category in the title group also!
5262                                    titleObject = SHC.util.ClinicalTitles[fullTitle];
5263                                    if(titleObject) {
5264                                        if(SHC.util.inArray(titleOb
5264ject["Medical-Categories"], medCatValue)) {
5265                                            foundTitle = true;
5266                                            break titleCheck;
5267                                        }
5268                                    }
5269                                }
5270                            } else if(useMedCategoryTitle) {
5271                                fullTitle = groupsToTitles[i].groupToTitle;
5272                                titleObject = SHC.util.ClinicalTitles[fullTitle];
5273                                if(titleObject) {
5274                                    if(SHC.util.inArray(titleObject["Medical-Categories"], medCatValue)) {
5275                                        foundTitle = true;
5276                                        break titleCheck;
5277                                    }
5278                                }
5279                            } else if(useTitleGroups) {
5280                                groupTitle = SHC.util.splitSelect(groupsToTitles[i].groupToTitle, "_", 0);
5281                                if(groupTitle === drTitleGroups) {
5282                                    foundTitle = true;
5283                                    break titleCheck;//We have the ful title here
5284                                }
5285                            }
5286                        }
5287                    } else {
5288                        if(!SHC.util.isPrimaryCareObject(primaryCareTitles, shortTitle)) {
5289                            foundTitle = true;
5290                            break titleCheck;
5291                        } else {
5292                            if(shortTitle.indexOf('Obstetrician') > -1 || shortTitle.indexOf('obstetrician') > -1 ||
5293                                shortTitle.indexOf('gynecologist') > -1 || shortTitle.indexOf('Gynecologist') > -1) {
5294                                foundTitle = true;
5295                                break titleCheck;
5296                            }
5297                        }
5298                    }
5299                }
5300            }
5301        if(!foundTitle) {
5302            if(useMedCategoryTitle && useTitleGroups && foundGroupTitle) {
5303                shortTitle = matchingGroupTitle;
5304            } else {
5305                shortTitle = SHC.util.splitSelect(groupsToTitles[0].groupToTitle, "_", 1);
5306            }
5307        }
5308        // Checks doctor titles for OB/GYN on Intel and chooses a different title that is not OB/GYN
5309        if(SHC.ui.Search.DirectoryUtil.isPrimaryCareToggleActive() && SHC.ui.Search.DirectoryUtil.isMicrosite() &&
5310            GLOBAL_MICROSITE_SRC === 'intel' && (shortTitle.toLowerCase().indexOf('obstetrician') > -1 ||
5311            shortTitle.toLowerCase().indexOf('gynecologist') > -1)) {
5312            for(var f = 0; f < groupsToTitles.length; f++) {
5313                var currentTitle = SHC.util.splitSelect(groupsToTitles[f].groupToTitle, "_", 1);
5314                if(currentTitle.toLowerCase().indexOf('obstetrician') < 0 || currentTitle.toLowerCase().indexOf('gynecologist') < 0) {
5315                    shortTitle = currentTitle;
5316                }
5317            }
5318        }
5319    }
5320    return SHC.util.ellipsis(shortTitle, 50);
5321};
5322
5323SHC.util.isPrimaryCareObject = function(primaryCareTitles, shortTitle) {
5324    var isPrimaryCare = false;
5325    $.each(primaryCareTitles, function(index, value) {
5326        var primaryCareObject = value;
5327        if(SHC.util.inArray(primaryCareObject, shortTitle)) {
5328            isPrimaryCare = true;
5329            return false;
5330        }
5331    });
5332    return isPrimaryCare;
5333};
5334
5335SHC.util.getCookieValueByName = function(name) {
5336    var re = new RegExp(name + "=([^;]+)");
5337    var value = re.exec(document.cookie);
5338    return (value != null) ? unescape(value[1]) : null;
5339};
5340
5341/**
5342 * Returns decoded text string to format special characters in Display Name
5343 * @param name
5344 */
5345SHC.util.formatNameText = function(nameText) {
5346    return decodeURIComponent(escape(nameText));
5347};
5348
5349SHC.util.getCompleteAddress = function(address) {
5350    var returnVal = "";
5351    if(address) {
5352        var splitVals = address.split("|");
5353        for(var i = 0; i < splitVals.length; i++) {
5354            if(splitVals[i] !== "") {
5355                returnVal += splitVals[i].trim();
5356                if(i !== splitVals.length - 1) {
5357                    returnVal += ", ";
5358                }
5359            }
5360        }
5361    }
5362    return returnVal;
5363};
5364
5365SHC.util.getNormalUrlParameter = function(name) {
5366    var url = window.location.href;
5367    name = name.replace(/[\[\]]/g, "\\$&");
5368    var regex = new RegExp("[#?&]" + name + "(=([^&#]*)|&|#|$)"),
5369        results = regex.exec(url);
5370    if(!results) {
5371        return null;
5372    }
5373    if(!results[2]) {
5374        return '';
5375    }
5376    return decodeURIComponent(results[2].replace(/\+/g, " "));
5377};
5378
5379/**
5380 * Parses the current S&P filters being used (as stored in the URL's hash) and
5381 * fetches the value for a given attribute. For example, if the hash is:
5382 *     #&x1=sp_spec_care_phy&q1=true
5383 * and the value of 'attr' passed in is 'sp_spec_care_phy' then the 'true' will
5384 * be returned to the caller. If there is no match, then null is returned.
5385 **/
5386SHC.util.getAttrValueFromURL = function(attr) {
5387    var hash = window.location.hash;
5388    if(hash && hash.indexOf(attr) > -1) {
5389        var regexResult = new RegExp('[?#&]x([1-9]*)=' + attr).exec(hash);
5390        if(regexResult !== null) {
5391            var queryIndex = regexResult[1];
5392            var attrValue = new RegExp('[?#&]q' + queryIndex + '=([^&#]*)').exec(hash);
5393            if(attrValue && attrValue.length > 1) {
5394                return decodeURIComponent(attrValue[1]);
5395            }
5396        }
5397    }
5398
5399    return null;
5400};
5401
5402/**
5403 * will split by comma and return the first and last two terms,
5404 *
5405 * so street 123, room 5, suite 5, sacramento, ca will return
5406 * street 123, sacramento, ca
5407 * @param address
5408 * @returns {*}
5409 */
5410SHC.util.getMainAddress = function(address) {
5411    var splitAddress = address.split(",");
5412    var generalAddress = "";
5413    for(var i = 0; i < splitAddress.length; i++) {
5414        var isLastTerm = (i === splitAddress.length - 1);
5415        if(i === 0) {
5416            generalAddress += splitAddress[i] + ",";
5417        }
5418        else if(i === splitAddress.length - 2) {
5419            generalAddress += splitAddress[i] + ",";
5420        }
5421        else if(i === splitAddress.length - 1) {
5422            generalAddress += splitAddress[i];
5423        }
5424    }
5425    return generalAddress;
5426};
5427
5428//The expected format from S&P for the address is {address}|{address2}|{city}|{state}
5429SHC.util.getAddressValue = function(address, index) {
5430    var returnVal = "";
5431    if(address) {
5432        var splitVals = address.split("|");
5433        if(splitVals.length > index) {
5434            returnVal = splitVals[index];
5435        }
5436    }
5437    return returnVal;
5438};
5439
5440SHC.util.clearMapCookiesOnDirectoryClick = function() {
5441    // clear last info bubble visited when user brings up default directory view
5442    $('.directory-link').click(SHC.ui.Search.DirectoryUtil.clearMapCookies);
5443};
5444
5445SHC.util.isDoctorProfilePage = function() {
5446    var path = window.location.pathname;
5447    return path.indexOf("/doctors/") > -1 || path.indexOf("/uha-doctors/") > -1 || path.indexOf("/pcha-doctors/") > -1;
5448};
5449
5450SHC.util.isClinicPage = function() {
5451    var path = window.location.pathname;
5452    return path.indexOf("/medical-clinics/") > -1;
5453};
5454
5455SHC.util.clickAnchorTab = function() {
5456    var parseHashValue = function(str) {
5457        if (str.indexOf('&')>-1||str.indexOf('=')>-1) {
5458            var pair = str.split('&')[0];
5459            if (pair && pair.indexOf('=')>-1) {
5460                return pair.split('=')[0];
5461            } else {
5462                return pair;
5463            }
5464        }
5465        return str;
5466    };
5467    if (!SHC.ui.Search.DirectoryUtil.isDirectoryPage() &&
5468        window.location.href.indexOf("findcare.") < 0) {
5469        var parsedHash = parseHashValue(window.location.hash);
5470        if (parsedHash) {
5471            var targetAnchor = $(parsedHash);
5472            $('#main').ready(function() {
5473                if(targetAnchor.length && targetAnchor.hasClass('anchor-tab-link') && !targetAnchor.hasClass('active')) {
5474                    targetAnchor.click();
5475                }
5476            });
5477        }
5478    }
5479};
5480
5481// set up the function hashScroll to be used onLoad, and on same page anchor link
5482SHC.util.hashScroll = function (scrollTime) {
5483    // get adjustments because we afix the search bar
5484    var searchHeight;
5485    var padding = 20; // a constant to help whitespace look nice
5486    if (!jQuery('#checkBootStrapXS').is(':visible')) {
5487        searchHeight = 0; // small doesn't afix the search, so it doesn't need offsetting
5488    } else {
5489        searchHeight = jQuery('#search-inpagenav').outerHeight() + padding;
5490    }
5491    // get the hash from url and sanitize
5492    var hash = location.hash;
5493    hash = hash.replace("#", "");
5494
5495    // handle onload with hash in url.
5496    // ensure hash does not contain parameters
5497    if (hash && hash.indexOf('&') === -1 && hash.indexOf('=') === -1 ) {
5498        // get all the anchor tags, and
5499        var inPageNavAnchorString = hash + "_[data-nav-show='true']";
5500        var anchorLinks = jQuery("[name=" + hash + "], #" + hash);
5501        anchorLinks.add(inPageNavAnchorString);
5502
5503        // loop through all anchors and find the one that matches the hash
5504        anchorLinks.each(function() {
5505            var thisAnchor = jQuery(this);
5506            if ((thisAnchor.closest(".desktop-tab-details-container, .desktop-circle-content, .clone-content").length === 1 && SHC.ui.screenMode === "small") ||
5507                (thisAnchor.closest(".mobile-tab-details-container, .mobile-circle-content, .clone-content").length === 1 && SHC.ui.screenMode !== "small")) {
5508                return true;
5509            }
5510            if (thisAnchor.attr('name') === hash || thisAnchor.attr('id') === hash) {
5511                // scroll to this element after scrollTime
5512                setTimeout(function() {
5513                    if ( SHC.ui.RevealBoxExpert.hashScroll && SHC.ui.screenMode !== "small"){
5514                        searchHeight +=  SHC.ui.RevealBoxExpert.hashScroll;
5515                    }
5516                    var animation;
5517                    // do a different offset for IOS
5518                    if (SHC.util.isIOS() && SHC.ui.screenMode !== "small") {
5519                        var searchInPageNav = jQuery("#search-inpagenav").height();
5520                        animation = {scrollTop: thisAnchor.offset().top - searchHeight + searchInPageNav};
5521                    } else {
5522                        animation = {scrollTop: thisAnchor.offset().top - searchHeight};
5523                    }
5524
5525                    jQuery('html, body').animate(animation, 500, 'swing', function() {});
5526                }, scrollTime);
5527            }
5528        });
5529    }
5530};
5531
5532SHC.util.regexIndexOf = function(str, regex, startpos) {
5533    var indexOf = str.substring(startpos || 0).search(regex);
5534    return (indexOf >= 0) ? (indexOf + (startpos || 0)) : indexOf;
5535};
5536
5537/**
5538 * Create a URL query string based on key value pairs in a map.
5539 * @param map
5540 */
5541SHC.util.toQueryString = function(map) {
5542    if (!map) {
5543        return "";
5544    }
5545    var pairs = [];
5546    for (var key in map) {
5547        if (map[key]) {
5548            pairs.push(key+"="+map[key]);
5549        }
5550    }
5551    if (pairs.length>0) {
5552        return pairs.join("&");
5553    }
5554    return "";
5555};
5556
5557/**
5558 * Remove a parameter attribute that _starts_with_ key name
5559 * from a query string of the form:
5560 *
5561 * var str = "?a=1&b=2&c=3";
5562 * var result = removeParam("?","b",str); // a=1&c=3
5563 *
5564 * @param prefix - could be '?' (query string) or '#' (url hash)
5565 * @param key
5566 * @param str
5567 * @returns {string}
5568 */
5569SHC.util.removeParam = function(prefix, key, str) {
5570    str = str.replace(prefix,"");
5571    var pair, pairs = str.split("&");
5572    for (var i = pairs.length - 1; i >= 0; i--) {
5573        pair = pairs[i].split("=")[0];
5574        if (pair.indexOf(key) === 0) {
5575            pairs.splice(i, 1);
5576        }
5577    }
5578    return prefix + pairs.join("&");
5579};
5580
5581/**
5582 * Parse current window.location and check for saved parameters in
5583 * SHC.exports.savedParams (stashed in MegaSearch.js).
5584 *
5585 */
5586SHC.util.appendSavedParams = function() {
5587    var oldHash = window.location.hash.valueOf();
5588    oldHash = oldHash.replace(/#/g,"").replace(/\?/g,"");
5589    var pairs = oldHash.split(/&/);
5590    var newHash = {};
5591    for (var i=0,n=pairs.length; i<n; i++) {
5592        if (pairs[i] && pairs[i].indexOf("=")>-1) {
5593            var kv = pairs[i].split(/=/);
5594            newHash[kv[0]] = kv[1];
5595        }
5596    }
5597    if (SHC.exports && SHC.exports.savedParams) {
5598        for (var key in SHC.exports.savedParams) {
5599            newHash[key] = SHC.exports.savedParams[key];
5600        }
5601    }
5602    var newHashStr = "#" + SHC.util.toQueryString(newHash);
5603    window.location.hash = newHashStr;
5604};
5605
5606SHC.util.clickInternalAnchorTab = function() {
5607    $(window).on('hashchange', function() {
5608        try {
5609            var newHash = $(window.location.hash);
5610            if(newHash.length && newHash.hasClass('anchor-tab-link') && !newHash.hasClass('active')) {
5611                newHash.click();
5612                setTimeout(function() {
5613                    $('html,body').animate({
5614                        scrollTop: newHash.offset().top
5615                    }, 100);
5616                }, 401); //this timeout length needs to match the navAnimateSpeed in ProcessCircles.js
5617            }
5618        } catch(e) {
5619            // not ALL window.location.hash values are anchor targets.
5620        }
5621    });
5622    $(window).on('anchorclick', function(e) {
5623        try {
5624            var newHash = $(e.target.location.hash);
5625            if(newHash.length && newHash.hasClass('anchor-tab-link') && !newHash.hasClass('active')) {
5626                newHash.click();
5627            }
5628        } catch(ex) {
5629            // not ALL window.location.hash values are anchor targets.
5630        }
5631    });
5632};
5633
5634/**
5635 * will deduplicate an array of objects by passed in object key and returns unique array
5636 *
5637 * SHC.util.dedupeArrayOfObj([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x');
5638 * => [{ 'x': 1 }, { 'x': 2 }]
5639 * @param address
5640 * @returns {*}
5641 */
5642SHC.util.dedupeArrayOfObj = function(arr, prop) {
5643    var new_arr = [];
5644    var lookup = {};
5645
5646    for(var i = 0; i < arr.length; i++) {
5647        lookup[arr[i][prop]] = arr[i];
5648    }
5649
5650    for(i in lookup) {
5651        new_arr.push(lookup[i]);
5652    }
5653
5654    return new_arr;
5655};
5656
5657/**
5658 * truncate the field in an array of objects with a certain length
5659 * @param arr -- a list of objects
5660 * @param field -- the field to truncate
5661 * @param limit -- size limit
5662 * @returns {Array}
5663 */
5664SHC.util.truncateField = function(arr, field, limit) {
5665    var newList = [];
5666    if (arr && arr.length>0 && limit) {
5667        for (var i=0,n=arr.length; i<n; i++) {
5668            var item = arr[i];
5669            item[field] = SHC.util.ellipsis(item[field], limit);
5670            newList.push(item);
5671        }
5672    }
5673    return newList;
5674};
5675
5676/**
5677 * Looks at the URL on a clinical trials passthrough and returns if its recruiting, not recruiting,
5678 * or recruting AND not recruiting
5679 * @returns {string}
5680 */
5681SHC.util.clinicalTrialsPassthroughGetRecruitingStatusFromUrl = function(){
5682    var url = window.location.href;
5683    if(url.indexOf('/&sp_trialLocks%7C') > -1){
5684        var conditionAndStatus = url.split('/&sp_trialLocks%7C')[1].split('.html')[0].split('%7C/')[0];
5685        if(conditionAndStatus.indexOf('&RECRUITING|NOT_RECRUITING') > -1){
5686            return 'RECRUITING|NOT_RECRUITING';
5687        }else if(conditionAndStatus.indexOf('&NOT_RECRUITING') > -1){
5688            return 'NOT_RECRUITING';
5689        }else if(conditionAndStatus.indexOf('&RECRUITING') > -1){
5690            return 'RECRUITING';
5691        }else{
5692            return '';
5693        }
5694    }else{
5695        return '';
5696    }
5697};
5698
5699/**
5700 * Clinical Trials = checks the condition and trial ID field and returns true if both are empty
5701 * @returns {boolean}
5702 */
5703SHC.util.clinicalTrialsConditionsAndIdAreEmpty = function(){
5704    var condition = $('#trials-condition-filter-target .trials-condition.trial-filter input');
5705    var trialId = $('#trials-id-filter-target .trials-ids.trial-filter input');
5706    if( (condition && condition.val() === '') && (trialId && trialId.val() === '')){
5707        return true;
5708    }else{
5709        return false;
5710    }
5711};
5712
5713SHC.util.mobileSearchResultsCloseFilterAndOverlay = function(){
5714    $('.search-results-filters.trials-filter-rail.visible').removeClass('visible');
5715    $('.search-results-list-overlay.active').removeClass('active');
5716};
5717
5718SHC.util.clinicalTrialsMobileExactMatchOverlayHeight = function(){
5719    var totalHeight = 0;
5720    var resultsList = $('.trials-condition-results');
5721    if(resultsList && resultsList.size() > 0){
5722        resultsList.each(function(){
5723            totalHeight += $(this).height();
5724        });
5725    }
5726    totalHeight += $('.trials_view_more_btn').outerHeight();
5727    return totalHeight;
5728};
5729
5730SHC.util.clinicalTrialsMobileNonExactMatchOverlayHeight = function(){
5731    var totalHeight = $('.search-results-list').height() + 25 + $('.trials_cond_view_more_btn').outerHeight();
5732    return totalHeight;
5733};
5734
5735/**
5736 * Converts S&P's syntax using ; + ~ to & %20 %, respectively
5737 * for use in our directory url param format
5738 * @param link
5739 */
5740SHC.util.convertSpSyntax = function(link) {
5741    var newLink = link.replace(/;/g, '&').replace(/\+/g, '%20').replace(/~/g, '%');
5742    return newLink;
5743};
5744
5745/**
5746 * Compares equality after html entities removed
5747 * @param v1
5748 * @param v2
5749 * @returns {boolean} isEqual
5750 */
5751SHC.util.isEqualWithEntitiesRemoved = function (v1, v2) {
5752
5753    v1 = (v1+"").replace(/&#\d+;/gm, function(s) {
5754        return String.fromCharCode(s.match(/\d+/gm)[0]);
5755    });
5756    v1 = v1.replace(/&amp;/g, '&');
5757    v2 = (v2+"").replace(/&#\d+;/gm, function(s) {
5758        return String.fromCharCode(s.match(/\d+/gm)[0]);
5759    });
5760    v2 = v2.replace(/&amp;/g, '&');
5761    if (v1 === v2) {
5762        return true;
5763    }
5764    return false;
5765};
5766
5767SHC.util.escapeCharactersForRegEx = function(textString){
5768    var escapedString = textString;
5769    if (textString && textString.length > 0 ){
5770        var stringArray = textString.split('');
5771        var escapeChars = "(){}?*+[]";
5772        for(var i=0; i < stringArray.length; i++){
5773            if(escapeChars.indexOf(stringArray[i]) !== -1){
5774                stringArray[i] = "\\" + stringArray[i];
5775            }
5776        }
5777        escapedString = stringArray.join('');
5778    }
5779    return escapedString;
5780};
5781
5782/**
5783 * Rotates an array in the forward or backward direction in steps
5784 * @param array
5785 * @param step
5786 * @returns rotated array
5787 */
5788SHC.util.rotate = function (array, step) {
5789    step = (step || 0) % array.length;
5790    if (step < 0) {
5791        step += array.length;
5792    }
5793    var removed = array.splice(0, step);
5794    array.push.apply(array, removed);
5795    return array;
5796};
5797
5798/**
5799 * Create a unique UUID
5800 * @returns String UUID
5801 */
5802SHC.util.guid = function () {
5803    function s4() {
5804        return Math.floor((1 + Math.random()) * 0x10000)
5805            .toString(16)
5806            .substring(1);
5807    }
5808    return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4();
5809};
5810
5811/**
5812 * Converts a Hash from a search-results page to a Map of key value pairs
5813 * ex. #x1=sp_prim_care_phy&q1=true => {sp_prim_care_phy: "true"}
5814 * @param hash
5815 * @returns {{}}
5816 */
5817SHC.util.getMapFromHash = function (hash) {
5818    var keys = {};
5819    var map = {};
5820    var arr = hash.split(/[#, &]/);
5821    for (var val in arr){
5822        if (arr.hasOwnProperty(val)) {
5823            var el = arr[val];
5824            if (el && el.length > 4) {
5825                var key;
5826                if (el.match(/x[0-9]=/)) {
5827                    key = el.substr(1, 2);
5828                    keys[key] = el.substr(3);
5829                }
5830                else if (el.match(/q[0-9]=/)) {
5831                    key = el.substr(1, 2);
5832                    map[keys[key]] = decodeURIComponent(el.substr(3));
5833                }
5834            }
5835        }
5836    }
5837    return map;
5838};
5839
5840/**
5841 * updates SHC.savedSearch for all toggles based on the contents of savedFilters map
5842 *
5843 * @param savedFilters
5844 * @constructor
5845 */
5846SHC.util.saveSearch = function (savedFilters) {
5847
5848    //populate the SHC.savedSearch variable
5849    if (!SHC.savedSearch) {
5850        SHC.savedSearch = {};
5851    }
5852
5853    // Default values for each of the directory toggles
5854    // To carry over a filter add it to the directory toggle of all directories with the filter and use '' as the value
5855    var directoryFilters = {
5856        organic_phys: {
5857            'doctors-filter-toggle-specialist': {
5858                sp_spec_care_phy: 'true',
5859                sp_med_categories: '',
5860                sp_dr_title_groups: ''
5861            },
5862            'doctors-filter-toggle-primary-care': {
5863                sp_prim_care_phy: 'true'
5864            }
5865        },
5866        organic_clinics: {
5867            'clinics-filter-toggle-specialty-care': {
5868                sp_spec_care_clinic: 'true',
5869                sp_med_categories: '',
5870                sp_dr_title_groups: ''
5871            },
5872            'clinics-filter-toggle-primary-care': {
5873                sp_prim_care_clinic: 'true'
5874            },
5875            'clinics-filter-toggle-other-service': {
5876                sp_other_service: 'true'
5877            }
5878        },
5879        organic_conds_txs: {
5880            'conditions-filter-toggle-all': {
5881                sp_med_categories: ''
5882            },
5883            'conditions-filter-toggle-conditions': {
5884                sp_type: 'condition',
5885                sp_med_categories: ''
5886            },
5887            'conditions-filter-toggle-treatments': {
5888                sp_type: 'treatment',
5889                sp_med_categories: ''
5890            }
5891        }
5892    };
5893
5894    if (typeof savedFilters === 'object'){
5895        // populate the SHC.savedSearch variable
5896        var toggleFilters = directoryFilters[GLOBAL_DIRECTORY_OBJECT];
5897        for (var tab in toggleFilters) {
5898            var tempMap = toggleFilters[tab];
5899            // update the values for all filters from saved map
5900            for (var filter in savedFilters) {
5901                if (toggleFilters[tab].hasOwnProperty(filter) && filter !== 'sp_type') {
5902                    tempMap[filter] = savedFilters[filter];
5903                }
5904            }
5905
5906            // add the filters to the SHC variable
5907            if (!SHC.savedSearch[tab]){
5908                SHC.savedSearch[tab] = {};
5909            }
5910            for (filter in tempMap){
5911                if (tempMap[filter]) {
5912                    (SHC.savedSearch[tab])[filter] = tempMap[filter];
5913                }
5914            }
5915        }
5916    }
5917};
5918
5919/**
5920 * Removes a specific filter from all SHC.savedSearch toggles
5921 * @param filterName
5922 */
5923SHC.util.removeFilter = function(filterName){
5924    for (var toggle in SHC.savedSearch){
5925        if (SHC.savedSearch[toggle].hasOwnProperty(filterName)){
5926            delete (SHC.savedSearch[toggle])[filterName];
5927        }
5928    }
5929};
5930SHC.util.primaryCareKeywords = ['express care', 'primary care', 'family medicine', 'family', 'family medicine in los altos',
5931    'family medicine associates of san jose', 'internal medicine in los altos', 'internal medicine',
5932    'primary care', 'alameda family physicians', 'urgent', 'express', 'internal', 'primary', 'urgent care', 'pediatrician', 'pediatrics'];
5933
5934SHC.util.getGoogleAPIKey = function() {
5935    var envs = ['aemqa', 'aemstage', 'aemreview', 'localhost'];
5936    var hostName = window.location.hostname;
5937    for (var env in envs) {
5938        if (hostName.indexOf(envs[env]) !== -1) {
5939            return 'AIzaSyBab8Bcwo6HsEk0t0zos1j315PBgRdNr1o';
5940        }
5941    }
5942    return 'AIzaSyAYK4Jkp63Ux_yN08GQLTx55DYx_b3HXkc';
5943};
5944
5945SHC.util.isValleycare = function() {
5946    return window.location.pathname.indexOf('/tri-valley') !== -1
5947        || window.location.hostname.indexOf('trivalley.stanfordhealthcare.org') !== -1;
5948};
5949
5950SHC.util.isStanfordlab = function() {
5951  return window.location.pathname.indexOf('/stanfordlab/') !== -1
5952      || window.location.hostname.indexOf('stanfordlab.com') !== -1;
5953};
5954
5955SHC.Namespace(SHC, "SHC.ui.Search.DirectoryUtil");
5956
5957
5958SHC.ui.Search.DirectoryUtil.searchResultsUrl = SHC.util.adjustPath("/content/shc/en/search-results.html");
5959SHC.ui.Search.DirectoryUtil.conditionsDirectoryUrl = SHC.util.adjustPath(CONDITION_DIRECTORY_PATH);
5960SHC.ui.Search.DirectoryUtil.clinicsDirectoryUrl = SHC.util.adjustPath(CLINIC_DIRECTORY_PATH);
5961SHC.ui.Search.DirectoryUtil.doctorsDirectoryUrl = SHC.util.adjustPath(DOCTOR_DIRECTORY_PATH);
5962SHC.ui.Search.DirectoryUtil.trialsDirectoryUrl = SHC.util.adjustPath(TRIAL_DIRECTORY_PATH);
5963SHC.ui.Search.DirectoryUtil.newsroomDirectoryUrl = SHC.util.adjustPath(NEWSROOM_DIRECTORY_PATH);
5964SHC.ui.Search.DirectoryUtil.guidedDirectoryURL = SHC.util.adjustPath(GUIDED_SEARCH_DIRECTORY_PATH);
5965SHC.ui.Search.DirectoryUtil.guidedDirectoryPage = SHC.util.adjustPath(GUIDED_SEARCH_DIRECTORY_PAGE);
5966SHC.ui.Search.DirectoryUtil.reactGuidedDirectoryPage = SHC.util.adjustPath(REACT_GUIDED_SEARCH_DIRECTORY_PAGE);
5967SHC.ui.Search.DirectoryUtil.valleyCareResultsUrl = SHC.util.adjustPath("/content/valleycare/en/search-results.html");
5968SHC.ui.Search.DirectoryUtil.valleyCareDirectory = SHC.util.adjustPath("/content/valleycare/en/directory/directory.html");
5969SHC.ui.Search.DirectoryUtil.stanfordLabResultsUrl = SHC.util.adjustPath("/content/stanfordlab/en/search-results.html");
5970
5971SHC.ui.Search.DirectoryUtil.processedFilter = false;
5972
5973/**
5974 * Returns current search results directory
5975 */
5976SHC.ui.Search.DirectoryUtil.getCurrentDirectory = function () {
5977    var url = window.location.href;
5978
5979    if(SHC.ui.Search.DirectoryUtil.isDoctorDirectoryPage()) {
5980        return "doctors";
5981    }
5982    else if(SHC.ui.Search.DirectoryUtil.isClinicDirectoryPage()) {
5983        return "clinics";
5984    }
5985    else if(SHC.ui.Search.DirectoryUtil.isTrialDirectoryPage()) {
5986        return "trials";
5987    }
5988    else if(SHC.ui.Search.DirectoryUtil.isConditionDirectoryPage()) {
5989        return "conditions";
5990    }
5991    else if (SHC.ui.Search.DirectoryUtil.isTrialsDirectoryPage()) {
5992        return "trials";
5993    }
5994    else if (SHC.ui.Search.DirectoryUtil.isNewsroomDirectoryPage()) {
5995        return "newsroom";
5996    }
5997    else if (SHC.ui.Search.DirectoryUtil.isNewsroomLandingPage()) {
5998        return "newsroomlanding";
5999    }
6000    else if (SHC.ui.Search.DirectoryUtil.isNewsroomListingPage()) {
6001        return "newsroom";
6002    } else {
6003        return "all";
6004    }
6005};
6006SHC.ui.Search.DirectoryUtil.getDirectoryControlTitleForDoer = function(doer) {
6007    switch(doer) {
6008        case "organic_clinical_trials":
6009            return "trials";
6010        case "organic_stories":
6011            return "stories";
6012        case "organic_events":
6013        case "vc_events":
6014            return "events";
6015        case "organic":
6016            return "all";
6017    }
6018};
6019SHC.ui.Search.DirectoryUtil.getQueryVariable = function(variable) {
6020    var query = window.location.search.substring(1);
6021    var vars = query.split("&");
6022    for (var i = 0; i < vars.length; i++) {
6023        var pair = vars[i].split("=");
6024        if (pair[0] === variable) {
6025            return pair[1];
6026        }
6027    }
6028    return false;
6029};
6030/**
6031 * Also in ResultsBinder.js, we should probably delete that one eventually, since this
6032 * functionality is needed on more than just Results Binder.
6033 */
6034SHC.ui.Search.DirectoryUtil.getSearchTerm = function() {
6035    var searchterm = location.pathname.match(/\.html\/(.*)/);
6036    if (searchterm !== null && searchterm.length > 1) {
6037        // remove trailing "&&" as this is not part of the search term
6038        if (searchterm[1].indexOf("&&") > -1) {
6039            return searchterm[1].substr(0, searchterm[1].indexOf("&&"));
6040        }
6041
6042        return searchterm[1];
6043    }
6044
6045    return null;
6046};
6047
6048SHC.ui.Search.DirectoryUtil.isDoctorDirectoryPage = function() {
6049    return SHC.util.pathContains(DOCTOR_DIRECTORY_PAGE, window.location.pathname);
6050};
6051
6052SHC.ui.Search.DirectoryUtil.isClinicDirectoryPage = function() {
6053    return SHC.util.pathContains(CLINIC_DIRECTORY_PAGE, window.location.pathname);
6054};
6055
6056SHC.ui.Search.DirectoryUtil.isTrialDirectoryPage = function() {
6057    return SHC.util.pathContains(TRIAL_DIRECTORY_PAGE, window.location.pathname);
6058};
6059
6060SHC.ui.Search.DirectoryUtil.isConditionDirectoryPage = function() {
6061    return SHC.util.pathContains(CONDITION_DIRECTORY_PAGE, window.location.pathname);
6062};
6063
6064SHC.ui.Search.DirectoryUtil.isTrialsDirectoryPage = function() {
6065    return SHC.util.pathContains("search-results.trials.html", window.location.pathname);
6066};
6067
6068SHC.ui.Search.DirectoryUtil.isNewsroomDirectoryPage = function() {
6069    return SHC.util.pathContains(NEWSROOM_DIRECTORY_PAGE, window.location.pathname);
6070};
6071
6072SHC.ui.Search.DirectoryUtil.isNewsroomLandingPage = function () {
6073    var isNewsroomLanding = false;
6074    var template = $('#shc-search-title').attr('data-page-template');
6075    if(typeof template !== 'undefined' && template !== null && template === '/apps/shc/templates/newsroomlanding'){
6076        isNewsroomLanding = true;
6077    }
6078    return isNewsroomLanding;
6079};
6080
6081SHC.ui.Search.DirectoryUtil.isNewsroomListingPage = function () {
6082    var template = $('#shc-search-title').attr('data-page-template');
6083    if(typeof template !== 'undefined' && template !== null && template === '/apps/shc/templates/newsroomlisting'){
6084        return true;
6085    }
6086    return false;
6087};
6088
6089SHC.ui.Search.DirectoryUtil.isTrialDirectoryPage = function() {
6090    var isClinicalTrial = SHC.util.pathContains(TRIAL_DIRECTORY_PAGE, window.location.pathname);
6091    //we are treating the search bar on clinical trials as a search page, we need to overwrite the behavior
6092        if(isClinicalTrial === false){
6093            var template = $('#shc-search-title').attr('data-page-template');
6094            if(typeof template !== 'undefined' && template !== null && template === '/apps/shc/templates/clinicaltrials_search'){
6095                    isClinicalTrial = true;
6096                }
6097        }
6098    return isClinicalTrial;
6099};
6100
6101SHC.ui.Search.DirectoryUtil.isDirectoryPage = function() {
6102    return SHC.ui.Search.DirectoryUtil.isDoctorDirectoryPage() || SHC.ui.Search.DirectoryUtil.isClinicDirectoryPage()
6103        || SHC.ui.Search.DirectoryUtil.isConditionDirectoryPage() || SHC.ui.Search.DirectoryUtil.isTrialDirectoryPage()
6104        || SHC.ui.Search.DirectoryUtil.isNewsroomDirectoryPage() || SHC.ui.Search.DirectoryUtil.isNewsroomLandingPage();
6105};
6106
6107SHC.ui.Search.DirectoryUtil.isSearchResultsPage = function() {
6108    return (SHC.ui.Search.DirectoryUtil.isDirectoryPage() || SHC.util.pathContains("search-results.html", window.location.pathname));
6109};
6110
6111SHC.ui.Search.DirectoryUtil.isPrimaryCareToggleActive = function () {
6112    var $primCareFilter = $('.primary-care-filter');
6113    if(SHC.ui.Search.DirectoryUtil.isMicrosite()) {
6114        if($primCareFilter.length) {
6115            return $primCareFilter.hasClass("active");
6116        } else {
6117            return window.location.hash.indexOf("sp_spec_care_phy") < 0;
6118        }
6119    } else {
6120        if($primCareFilter.length) {
6121            return $primCareFilter.hasClass("active");
6122        }
6123        else {
6124            return window.location.hash.indexOf("sp_prim_care_phy") > -1;
6125        }
6126    }
6127};
6128
6129SHC.ui.Search.DirectoryUtil.isSpecialistsToggleActive = function () {
6130    var $specFilter = $(".specialists-filter");
6131    if($specFilter.length) {
6132        return $specFilter.hasClass("active");
6133    }
6134    else {
6135        return window.location.hash.indexOf("sp_prim_care_phy") > -1;
6136    }
6137};
6138
6139SHC.ui.Search.DirectoryUtil.isMicrosite = function() {
6140    return typeof GLOBAL_MICROSITE_SRC !== "undefined" && GLOBAL_MICROSITE_SRC !== "";
6141};
6142
6143SHC.ui.Search.DirectoryUtil.isZipCodeQuery = function(Q) {
6144    return Q.indexOf("sp_q_location") > -1 && Q.indexOf("sp_q_max") > -1 || Q.indexOf("radius") > -1 && Q.indexOf("zip") > -1;
6145};
6146
6147SHC.ui.Search.DirectoryUtil.clearMapCookies = function() {
6148    SHC.util.setCookie("lastMapMarkerIndex", "", 0, "/");
6149    SHC.util.setCookie("lastMapLatitude", "", 0, "/");
6150    SHC.util.setCookie("lastMapLongitude", "", 0, "/");
6151    SHC.util.setCookie("lastMapZoom", "", 0, "/");
6152};
6153
6154SHC.ui.Search.DirectoryUtil.getSelectedView = function() {
6155    $selectedView = $('.grid-list-toggle .active');
6156    if($selectedView.length) {
6157        return $selectedView.attr('class').split('-')[0];
6158    }
6159    else {return false;}
6160};
6161
6162//
6163// Let's centralize Helper functions to avoid
6164// name clashing and duplication of declarations.
6165
6166Handlebars.registerHelper('ifCond', function(v1, v2, options) {
6167    if (String(v1) === String(v2)) {
6168        return options.fn(this);
6169    }
6170    return options.inverse(this);
6171});
6172
6173Handlebars.registerHelper('ifStringsEqualWithEntitiesRemoved', function(v1, v2, options) {
6174    v1 = (v1+"").replace(/&#\d+;/gm, function(s) {
6175        return String.fromCharCode(s.match(/\d+/gm)[0]);
6176    });
6177    v1 = v1.replace(/&amp;/g, '&');
6178    v2 = (v2+"").replace(/&#\d+;/gm, function(s) {
6179        return String.fromCharCode(s.match(/\d+/gm)[0]);
6180    });
6181    v2 = v2.replace(/&amp;/g, '&');
6182    if (v1 === v2) {
6183        return options.fn(this);
6184    }
6185    return options.inverse(this);
6186});
6187
6188Handlebars.registerHelper('isSmallScreen', function(options) {
6189    if(SHC.ui.screenMode === "small") {
6190        return options.fn(this);
6191    }
6192    else {
6193        return options.inverse(this);
6194    }
6195});
6196
6197Handlebars.registerHelper('list', function(items, options) {
6198    var out = "";
6199
6200    for(var i=0, l=items.length; i<l; i++) {
6201        out = out + options.fn(items[i]);
6202        if (i === Math.floor(l/3) || i === (Math.floor(l/3 * 2))) {
6203            out = out + "</ul><ul class=\"col-sm-4\">";
6204        }
6205    }
6206    return out;
6207});
6208
6209Handlebars.registerHelper("foreach",function(arr, options) {
6210    if((options.inverse && !arr) || (options.inverse && !arr.length)) {
6211        return options.inverse(this);
6212    }
6213
6214    return arr.map(function(item,index) {
6215        item.$index = index;
6216        item.$first = index === 0;
6217        item.$last  = index === arr.length-1;
6218        return options.fn(item);
6219    }).join('');
6220});
6221
6222Handlebars.registerHelper("foreachThreeCombined",function(arr1, arr2, arr3, options) {
6223    var practices = arr1.concat(arr2).concat(arr3);
6224
6225    // can't just call sort on practices because it's an array of objects which contain values.
6226    // this just overrides sort for practices to sort alphabetically by the values within the objects.
6227    practices = practices.sort(function(a, b) {
6228        if(a.value < b.value) {
6229            return -1;
6230        }
6231        if(a.value > b.value) {
6232            return 1;
6233        }
6234        return 0;
6235    });
6236
6237    return practices.map(function(item,index) {
6238        item.index = index;
6239        return options.fn(item);
6240    }).join('');
6241});
6242
6243Handlebars.registerHelper("foreachFourCombined",function(arr1, arr2, arr3, arr4, options) {
6244    var practices = arr1.concat(arr2).concat(arr3).concat(arr4);
6245
6246    // can't just call sort on practices because it's an array of objects which contain values.
6247    // this just overrides sort for practices to sort alphabetically by the values within the objects.
6248    practices = practices.sort(function(a, b) {
6249        if(a.value < b.value) {
6250            return -1;
6251        }
6252        if(a.value > b.value) {
6253            return 1;
6254        }
6255        return 0;
6256    });
6257
6258    return practices.map(function(item,index) {
6259        item.index = index;
6260        return options.fn(item);
6261    }).join('');
6262});
6263
6264Handlebars.registerHelper('ifCond', function(v1, v2, options) {
6265    if(v1 === v2) {
6266        return options.fn(this);
6267    }
6268    return options.inverse(this);
6269});
6270
6271Handlebars.registerHelper('ifNotEqual', function(v1, v2, options) {
6272    if(v1 !== v2) {
6273        return options.fn(this);
6274    }
6275    return options.inverse(this);
6276});
6277
6278Handlebars.registerHelper('ifGreaterThan', function(v1, v2, options) {
6279    if(parseInt(v1) > parseInt(v2)) {
6280        return options.fn(this);
6281    }
6282    return options.inverse(this);
6283});
6284
6285Handlebars.registerHelper('ifLessThan', function(v1, v2, options) {
6286    if(parseInt(v1) < parseInt(v2)) {
6287        return options.fn(this);
6288    }
6289    return options.inverse(this);
6290});
6291
6292Handlebars.registerHelper('ifEqual', function(v1, v2, options) {
6293    if(v1 === v2) {
6294        return options.fn(this);
6295    }
6296    return options.inverse(this);
6297});
6298
6299Handlebars.registerHelper('ifEqualsIgnoreCase', function(v1, v2, options) {
6300    if(v1.toLowerCase() === v2.toLowerCase()) {
6301        return options.fn(this);
6302    }
6303    return options.inverse(this);
6304});
6305
6306Handlebars.registerHelper('ifEven', function(v1, options) {
6307    if(v1%2 === 0) {
6308        return options.fn(this);
6309    }
6310    return options.inverse(this);
6311});
6312
6313Handlebars.registerHelper('ifOdd', function(v1, options) {
6314    if(v1%2 === 1) {
6315        return options.fn(this);
6316    }
6317    return options.inverse(this);
6318});
6319
6320Handlebars.registerHelper('ifNotInList', function(v1, list, options) {
6321    var items = [];
6322    items = list.split('|');
6323
6324    if(items.indexOf(v1) === -1) {
6325        return options.fn(this);
6326    }
6327    return options.inverse(this);
6328});
6329
6330
6331//Capability to write nested switch case statements in Handlebars templates
6332Handlebars.__switch_stack__ = [];
6333
6334Handlebars.registerHelper("switch", function (value, options) {
6335    Handlebars.__switch_stack__.push({
6336        switch_match: false,
6337        switch_value: value
6338    });
6339    var html = options.fn(this);
6340    Handlebars.__switch_stack__.pop();
6341    return html;
6342});
6343
6344Handlebars.registerHelper("case", function (value, options) {
6345    var args = Array.from(arguments);
6346    var ops = args.pop();
6347    var caseValues = args;
6348    var stack = Handlebars.__switch_stack__[Handlebars.__switch_stack__.length - 1];
6349
6350    if (stack.switch_match || caseValues.indexOf(stack.switch_value) === -1) {
6351        return '';
6352    } else {
6353        stack.switch_match = true;
6354        return ops.fn(this);
6355    }
6356});
6357
6358Handlebars.registerHelper("default", function (options) {
6359    var stack = Handlebars.__switch_stack__[Handlebars.__switch_stack__.length - 1];
6360    if (!stack.switch_match) {
6361        return options.fn(this);
6362    }
6363});
6364
6365Handlebars.registerHelper('markLetterChange', function(items, options) {
6366    var letter = "";
6367    var out = "";
6368    $(items).each(function(idx, item) {
6369        if (item.hasOwnProperty('alpha') && letter !== item.alpha) {
6370            letter = item.alpha;
6371            out = out + "<li class='section-break'>" + letter.toUpperCase() + "</li>";
6372        }
6373        out = out + options.fn(item);
6374    });
6375    return out;
6376});
6377
6378Handlebars.registerHelper('doBlades', function(items, options) {
6379    var letter = "";
6380    var out = "";
6381    var letterFilter = jQuery(".alphabet").find('.active').attr('data-alpha');
6382    $(items).each(function(idx, item) {
6383        if (item.count !== "" || item.count !== 0) {
6384            var itemAlpha = item.value.substr(0, 1);
6385            if (letter !== itemAlpha) {
6386                if (typeof letterFilter !== 'undefined' && letterFilter !== "" && letterFilter.indexOf(itemAlpha.toLowerCase()) === -1) {
6387                    return out;
6388                }
6389                letter = itemAlpha;
6390                out = out + "<div class='section-break'>" + letter.toUpperCase() + "</div>";
6391            }
6392            var doerIndex = item.link.indexOf("do=");
6393            var link = "?" + item.link.substr(doerIndex);
6394            out += '<div class="blade-box">';
6395            out += '<div class="blade-arrow-wrapper">';
6396            out += '</div>';
6397            out += '<div class="blade-content-wrapper">';
6398            out += "<h2 class=\"condition-blade\" data-target=\"condition-blade" + idx;
6399            out += "\" data-query-string=\"" + link + "\">" + item.value + "<span class=\"blade-arrow\">+</span></h2>";
6400            out += '<div class="trial-list condition-blade' + idx + '-target" style="display:none">';
6401            out += '<div class="spinner"></div>';
6402            out += '</div>';
6403            out += '</div>';
6404            out += '</div>';
6405            out = out + options.fn(item);
6406        }
6407    });
6408    return out;
6409});
6410
6411Handlebars.registerHelper('drLetterSection', function(items, options) {
6412    var letter = "";
6413    var out = "";
6414    for(var i=0, l=items.length; i<l; i++) {
6415        if (letter !== items[i].alpha) {
6416            letter = items[i].alpha;
6417            //out = out + "<div class='section-break'>" + letter.toUpperCase() + "</div>";
6418        }
6419        out = out + options.fn(items[i]);
6420    }
6421    return out;
6422});
6423
6424Handlebars.registerHelper('divideToCeiling', function(v1, v2) {
6425    return Math.ceil(parseInt(v1)/parseInt(v2)).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
6426});
6427
6428Handlebars.registerHelper('formatNumber', function(number) {
6429    return number.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
6430});
6431
6432Handlebars.registerHelper('addThreeNumbers', function(num1, num2, num3) {
6433    return Number(num1) + Number(num2) + Number(num3);
6434});
6435
6436Handlebars.registerHelper('addFourNumbers', function(num1, num2, num3, num4) {
6437    return Number(num1) + Number(num2) + Number(num3) + Number(num4);
6438});
6439
6440Handlebars.registerHelper('ifMoreThanFourPractices', function(num_of_conditions, num_of_medical_tests, num_of_treatments, options) {
6441    if(Number(num_of_conditions) + Number(num_of_medical_tests) + Number(num_of_treatments) > 3) {
6442        return options.fn(this);
6443    }
6444    return options.inverse(this);
6445});
6446Handlebars.registerHelper('ifHasAtLeastOnePractice', function(num_of_conditions, num_of_medical_tests, num_of_treatments, options) {
6447    if(Number(num_of_conditions) + Number(num_of_medical_tests) + Number(num_of_treatments) > 0) {
6448        return options.fn(this);
6449    }
6450    return options.inverse(this);
6451});
6452
6453Handlebars.registerHelper('ifEmpty', function(v1, options) {
6454    if(v1 === null || v1 === "" || v1 === undefined) {
6455        return options.fn(this);
6456    }
6457    return options.inverse(this);
6458});
6459
6460Handlebars.registerHelper('ifNotEmpty', function(v1, options) {
6461    if(v1 !== null && v1 !== "" && v1 !== undefined) {
6462        return options.fn(this);
6463    }
6464    return options.inverse(this);
6465});
6466
6467Handlebars.registerHelper('clearEllipsis', function(context) {
6468    if (context.substr(0,3) === "...") {
6469        return "<p>" + context.substr(3) + "</p>";
6470    } else {
6471        return context;
6472    }
6473});
6474
6475Handlebars.registerHelper('clearEllipsisRemoveHTMLAndTruncate', function(context, truncateLength) {
6476    var regex = /(<([^>]+)>)/ig;
6477    context = context.replace(regex, "");
6478    if (context.substr(0,3) === "...") {
6479        return "<p>" +
6480            jQuery.truncate(context.substr(3), {
6481                length: truncateLength,
6482                words: true,
6483                noBreaks: true })
6484            + "</p>";
6485    } else {
6486        return jQuery.truncate(context, {
6487            length: truncateLength,
6488            words: true,
6489            noBreaks: true });
6490    }
6491});
6492
6493Handlebars.registerHelper('filterAlphaList', function(alpha) {
6494    var out = "<ul class='select-options grid'>";
6495    out += "<li class='all active'' data-alpha=''>View All</li>";
6496    var count = 1;
6497    jQuery(alpha).each(function(idx, obj) {
6498        out += "<li class=\"alphaFilter_" + obj.value;
6499        if (obj.count === "" || obj.count === 0) {
6500            out += " disabled";
6501        }
6502        if (count === 26) {
6503            out += " last";
6504        }
6505        out += "\" data-alpha=\"" + obj.value + "\">" + obj.value + "</li>";
6506        count++;
6507    });
6508    out += "</ul>";
6509    return out;
6510});
6511
6512Handlebars.registerHelper('filterAlphaListSelect', function(alpha) {
6513    var out = "<select class='select-options-mobile grid'>";
6514    out += "<option hidden value=' '></option>";
6515    out += "<option class='all active'' data-alpha=''>View All</option>";
6516    var count = 1;
6517    jQuery(alpha).each(function(idx, obj) {
6518        out += "<option value=\"alphaFilter_" + obj.value + "\"";
6519        if (obj.count === "" || obj.count === 0) {
6520            out += " disabled";
6521        }
6522        out += " data-alpha=\"" + obj.value + "\">" + obj.value + "</option>";
6523        count++;
6524    });
6525    out += "</select>";
6526    return out;
6527});
6528
6529Handlebars.registerHelper('bladesList', function(alpha) {
6530    var out = "";
6531    var count = 1;
6532    jQuery(alpha).each(function(idx, obj) {
6533        out += "<a href=\"#\" class=\"alphaFilter_" + obj.value;
6534        if (obj.count === "" || obj.count === 0) {
6535            out += " disabled";
6536        }
6537        if (count === 26) {
6538            out += " last";
6539        }
6540        out += "\" data-alpha=\"" + obj.value + "\">" + obj.value + "</a>";
6541        count++;
6542    });
6543    return out;
6544});
6545
6546Handlebars.registerHelper('filterAlphaListMobile', function(alpha) {
6547    var out = "";
6548    var ad = " disabled";
6549    var eh = " disabled";
6550    var il = " disabled";
6551    var mp = " disabled";
6552    var qt = " disabled";
6553    var ux = " disabled";
6554    var yz = " disabled";
6555    if (alpha) {
6556        if (alpha[0].count > 0 ||
6557            alpha[1].count > 0 ||
6558            alpha[2].count > 0 ||
6559            alpha[3].count) {
6560            ad = "";
6561        }
6562
6563        if (alpha[4].count ||
6564            alpha[5].count ||
6565            alpha[6].count ||
6566            alpha[7].count) {
6567            eh = "";
6568        }
6569
6570        if (alpha[8].count ||
6571            alpha[9].count ||
6572            alpha[10].count ||
6573            alpha[11].count) {
6574            il = "";
6575        }
6576
6577        if (alpha[12].count ||
6578            alpha[13].count ||
6579            alpha[14].count ||
6580            alpha[15].count) {
6581            mp = "";
6582        }
6583
6584        if (alpha[16].count ||
6585            alpha[17].count ||
6586            alpha[18].count ||
6587            alpha[19].count) {
6588            qt = "";
6589        }
6590
6591        if (alpha[20].count ||
6592            alpha[21].count ||
6593            alpha[22].count ||
6594            alpha[23].count) {
6595            ux = "";
6596        }
6597
6598        if (alpha[24].count ||
6599            alpha[25].count) {
6600            yz = "";
6601        }
6602    }
6603
6604    out += '<a class="all active" data-alpha="">All</a>';
6605    out += '<a class="alphaFilter_abcd' + ad + '" data-alpha="a|b|c|d">A-D</a>';
6606    out += '<a class="alphaFilter_efgh' + eh + '" data-alpha="e|f|g|h">E-H</a>';
6607    out += '<a class="alphaFilter_ijkl' + il + '" data-alpha="i|j|k|l">I-L</a>';
6608    out += '<a class="alphaFilter_mnop' + mp + '" data-alpha="m|n|o|p">M-P</a>';
6609    out += '<a class="alphaFilter_qrst' + qt + '" data-alpha="q|r|s|t">Q-T</a>';
6610    out += '<a class="alphaFilter_uvwx' + ux + '" data-alpha="u|v|w|x">U-X</a>';
6611    out += '<a class="alphaFilter_yz' + yz + ' last" data-alpha="y|z">Y-Z</a>';
6612
6613    return out;
6614});
6615
6616Handlebars.registerHelper('truncate', function(content, truncateLength) {
6617
6618    return jQuery.truncate(content, {
6619        length: truncateLength,
6620        words: true,
6621        noBreaks: true
6622    });
6623
6624});
6625
6626Handlebars.registerHelper('formatStatus', function(status) {
6627    status = status.toLowerCase();
6628    status = status.replace("r", "R");
6629    if(status.indexOf("_") !== -1) {
6630        status = status.replace("n", "N");
6631        status = status.replace("_", " ");
6632    }
6633    return status;
6634});
6635
6636Handlebars.registerHelper('isOdd', function(num) {
6637    return parseInt(num)%2 !== 0;
6638});
6639
6640Handlebars.registerHelper('isEven', function(num) {
6641    return parseInt(num)%2 === 0;
6642});
6643
6644Handlebars.registerHelper('urlDecode', function(url) {
6645    return decodeURIComponent(url).replace(/\+/g, ' ');
6646});
6647
6648Handlebars.registerHelper('encodeString', function(string){
6649    return encodeURIComponent(string);
6650});
6651
6652Handlebars.registerHelper('urlEncode', function(url) {
6653    url = $('<textarea />').html(url).val();
6654    return encodeURIComponent(url);
6655});
6656
6657Handlebars.registerHelper('ifContains', function(v1, v2, options) {
6658    if(v1.indexOf(v2) !== -1) {
6659        return options.fn(this);
6660    }
6661    return options.inverse(this);
6662});
6663
6664Handlebars.registerHelper('ifMatches', function(str, regex, options) {
6665    if(new RegExp(regex).test(str)) {
6666        return options.fn(this);
6667    }
6668    return options.inverse(this);
6669});
6670
6671Handlebars.registerHelper('ifNotContains', function(v1, v2, options) {
6672    if(typeof(v1) === "undefined" || typeof(v2) === "undefined" || v1.indexOf(v2) === -1) {
6673        return options.fn(this);
6674    }
6675    return options.inverse(this);
6676});
6677
6678Handlebars.registerHelper('peerList', function(items, options) {
6679    var out = "";
6680    if (items) {
6681        var l = items.length;
6682        if (l % 3 === 0) {
6683            for (var i = 0; i < l; i++) {
6684                out = out + options.fn(items[i]);
6685                if (i+1 === Math.floor(l / 3) || i+1 === (Math.floor(l / 3 * 2))) {
6686                    out = out + "</ul><ul class=\"col-sm-4\">";
6687                }
6688            }
6689        }
6690        else {
6691            for (var j = 0; j < l; j++) {
6692                out = out + options.fn(items[j]);
6693                if (j === Math.floor(l / 3) || j === (Math.floor(l / 3 * 2))) {
6694                    out = out + "</ul><ul class=\"col-sm-4\">";
6695                }
6696            }
6697        }
6698    }
6699    return out;
6700});
6701
6702Handlebars.registerHelper('peerListTwoColumn', function(items, options) {
6703    var out = "";
6704    if (items) {
6705        var l = items.length;
6706        if (l % 2 === 0) {
6707            for (var i = 0; i < l; i++) {
6708                out = out + options.fn(items[i]);
6709                if (i+1 === Math.floor(l / 2) || i+1 === (Math.floor(l / 2 * 2))) {
6710                    out = out + "</ul><ul class=\"col-sm-6\">";
6711                }
6712            }
6713        }
6714        else {
6715            for (var j = 0; j < l; j++) {
6716                out = out + options.fn(items[j]);
6717                if (j === Math.floor(l / 2) || j === (Math.floor(l / 2 * 2))) {
6718                    out = out + "</ul><ul class=\"col-sm-6\">";
6719                }
6720            }
6721        }
6722    }
6723    return out;
6724});
6725
6726Handlebars.registerHelper('log', function(items) {
6727    console.log("helper logging: ", items);
6728
6729});
6730
6731Handlebars.registerHelper('stripPipeStanford', function(title) {
6732    if (title) {
6733        return title.replace(' | Stanford Health Care', '');
6734    } else {
6735        return title;
6736    }
6737});
6738
6739Handlebars.registerHelper('htmlDecodeThenUrlEncode', function(text) {
6740    text = $('<textarea />').html(text).val();
6741    return encodeURIComponent(text);
6742});
6743
6744Handlebars.registerHelper('htmlEntityDecode', function(text) {
6745    return $('<textarea />').html(text).text();
6746});
6747
6748Handlebars.registerHelper('decodeText', function(Text) {
6749    try {
6750        return decodeURIComponent(escape(Text));
6751    } catch (e) {
6752        return Text;
6753    }
6754});
6755
6756Handlebars.registerHelper('ellipsis', function(text) {
6757    var maxLength = 40;
6758    if (text && maxLength) {
6759        return (text.length > maxLength) ? text.substr(0,maxLength-3) + "..." : text;
6760    }
6761    return "";
6762});
6763
6764Handlebars.registerHelper('trialState', function(key) {
6765    var TRIAL_MAP = {
6766        "RECRUITING": "Recruiting Now",
6767        "NOT_RECRUITING" : "Not Recruiting"
6768    };
6769    if (TRIAL_MAP[key]) {
6770        return TRIAL_MAP[key];
6771    } else {
6772        return "";
6773    }
6774});
6775
6776Handlebars.registerHelper('adjustUrl', function(url){
6777    return SHC.util.adjustUrl(url);
6778});
6779
6780Handlebars.registerHelper('adjustPath', function(url){
6781    return SHC.util.adjustPath(url);
6782});
6783
6784// only adjusts the URL if it does not start with "http" or "https"
6785Handlebars.registerHelper('adjustRelativeLink', function(url){
6786    var regex = /^https?:\/\//i;
6787    if (regex.test(url)) {
6788        return url;
6789    }
6790
6791    return SHC.util.adjustPath(url) + '.html';
6792});
6793
6794Handlebars.registerHelper('homepagePath', function(){
6795    var authorPort = ":4502",
6796        publishPort = ":4503",
6797        homepath = SHC.util.isValleycare() ? "/content/valleycare/en/" : "/content/shc/en/";
6798    if (window.location.toString().indexOf(authorPort) === -1 &&
6799        window.location.toString().indexOf(publishPort) === -1) {
6800        homepath = "/";
6801        if (SHC.util.isValleycare()) {
6802            homepath = "/tri-valley/";
6803        }
6804    }
6805    return homepath;
6806});
6807
6808Handlebars.registerHelper('isFirstButtonRequired', function (block) {
6809    var pages = this.pagination.pages;
6810    for(i = 0; i < pages.length; i++) {
6811        if(i > 1 && pages[i].selected === "true") {
6812            return block.fn(this);
6813        }
6814    }
6815    return block.inverse(this);
6816});
6817
6818Handlebars.registerHelper('isMoreThanOnePage', function (block) {
6819    var pages = this.pagination.pages;
6820    if(pages.length > 1) {
6821        return block.fn(this);
6822    }
6823});
6824
6825Handlebars.registerHelper('getPageNumber', function (val) {
6826    var resultPerPage = 14;
6827    if(SHC.ui.screenMode === 'small'){
6828        resultPerPage = 10;
6829    }
6830    return Math.ceil(parseInt(val)/parseInt(resultPerPage)).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
6831});
6832
6833Handlebars.registerHelper('findAndBold', function (searchTerm, val) {
6834    searchTerm = decodeURIComponent(searchTerm);
6835    var valLowerCase = val.toLowerCase();
6836    var searchTermLowerCase = searchTerm.toLowerCase();
6837    var newVal = "";
6838    var pos = valLowerCase.indexOf(searchTermLowerCase);
6839
6840    if (pos > -1){
6841        newVal += val.substr(0, pos);
6842        newVal += "<strong>" + val.substr(pos, searchTerm.length) + "</strong>";
6843        if(val.substr(0, pos) !== val.substr(pos + searchTerm.length, val.length)){
6844            newVal += val.substr(pos + searchTerm.length, val.length);
6845        }
6846    }
6847    if(pos === -1) {
6848        newVal = val;
6849    }
6850    return newVal;
6851});
6852
6853Handlebars.registerHelper('isTopResult', function (index, lower, options) {
6854    if(index === 0 && Number(lower) === 1) {
6855        return options.fn(this);
6856    }
6857
6858    return options.inverse(this);
6859});
6860
6861
6862Handlebars.registerHelper('isActiveToggle', function (attributeName, isDefault, options) {
6863    var hash = window.location.hash;
6864    var isSHCAFindCarePage = typeof GLOBAL_SEARCH_RESULTS_TEMPLATE !== 'undefined' && GLOBAL_SEARCH_RESULTS_TEMPLATE === '/apps/shca/templates/searchresults'
6865        && SHC.ui.Search.DirectoryUtil.isDoctorDirectoryPage();
6866
6867    if(SHC.util.isIE() && hash === "#"){
6868        hash = "";
6869    }
6870
6871    if(attributeName && hash && hash.indexOf(attributeName) > -1) {
6872        return options.fn(this);
6873    } else if((hash === "" || (SHC.ui.Search.DirectoryUtil.isConditionDirectoryPage()) && hash.indexOf("sp_type")  === -1)) {
6874        // swap the default toggle for the doctor directory page when on SHCA "Find Care" page
6875        if((isSHCAFindCarePage && !isDefault) || (!isSHCAFindCarePage && isDefault)) {
6876            return options.fn(this);
6877        }
6878    }
6879
6880    return options.inverse(this);
6881});
6882
6883Handlebars.registerHelper('parseSpecialty', function (groupsToTitles) {
6884    return SHC.util.setPhysicianShortTitle(groupsToTitles);
6885});
6886
6887Handlebars.registerHelper('isOBGYN', function (groupsToTitles, options) {
6888    var title = SHC.util.setPhysicianShortTitle(groupsToTitles);
6889    if(title === "Obstetrician and Gynecologist (OB-GYN)") {
6890        return options.fn(this);
6891    }
6892    else {
6893        return options.inverse(this);
6894    }
6895});
6896
6897Handlebars.registerHelper('parseSpecialtyFromDoctorsByClinicServlet', function (groupsToTitles) {
6898    var shortTitle = "";
6899    if (groupsToTitles && groupsToTitles.length && groupsToTitles[0]) {
6900        var title = groupsToTitles[0];
6901        shortTitle = SHC.util.splitSelect(title,"_",1);
6902        shortTitle = SHC.util.ellipsis(shortTitle, 50);
6903    }
6904    return shortTitle;
6905});
6906
6907Handlebars.registerHelper('parseSpecialtyFromDoctorsByClinicServlet', function (groupsToTitles) {
6908    var shortTitle = "";
6909    if (groupsToTitles && groupsToTitles.length && groupsToTitles[0]) {
6910        var title = groupsToTitles[0];
6911        shortTitle = SHC.util.splitSelect(title,"_",1);
6912        shortTitle = SHC.util.ellipsis(shortTitle, 50);
6913    }
6914    return shortTitle;
6915});
6916
6917Handlebars.registerHelper('getStarWidth', function (rating) {
6918    var width = "";
6919    if(rating) {
6920        width = ((parseFloat(rating)/5)*100) +'%';
6921    }
6922    return width;
6923});
6924
6925Handlebars.registerHelper('buildDrMakeApptModalLink', function (url) {
6926    var modalLink = '';
6927    //This will add the handler of the microsites if we really need it.
6928    if(typeof GLOBAL_MICROSITE_SRC !== "undefined" && GLOBAL_MICROSITE_SRC !== "" && GLOBAL_MICROSITE_SRC !== "shc") {
6929        //We should be on a microsite, not shc. do
6930        var tempUrl = url.split('healthcare.org')[1];
6931        if(SHC.ui.screenMode === 'small' || SHC.ui.screenMode === 'medium'){
6932            return tempUrl.replace('.html','.appointmentmodal_modbile.html');
6933        }
6934        else {
6935            return tempUrl.replace('.html','.appointmentmodal.html');
6936        }
6937    } else {
6938        if (url && url.indexOf('.html') > -1) {
6939            var path = SHC.util.getPathFromUrl(url);
6940            // ie doesn't always have the forward slash at the beginning so add it if it's not there.
6941            if(path.indexOf('/') !== 0) {
6942                path = '/' + path;
6943            }
6944            if(SHC.ui.screenMode === 'small' || SHC.ui.screenMode === 'medium'){
6945                modalLink = path.substr(0, path.lastIndexOf('.html')) + '.appointmentmodal_mobile.html';
6946            }
6947            else {
6948                modalLink = path.substr(0, path.lastIndexOf('.html')) + '.appointmentmodal.html';
6949            }
6950        }
6951        return SHC.util.adjustPath(modalLink, true);
6952    }
6953});
6954
6955Handlebars.registerHelper('buildMapModalLink', function (url) {
6956    var modalLink = '';
6957    if (url && url.indexOf('.html') > -1) {
6958        var path = SHC.util.getPathFromUrl(url);
6959        // ie doesn't always have the forward slash at the beginning so add it if it's not there.
6960        if(path.indexOf('/') !== 0) {
6961            path = '/' + path;
6962        }
6963        modalLink = path.substr(0, path.lastIndexOf('.html')) + '.mapmodal.html';
6964    }
6965
6966    return SHC.util.adjustPath(modalLink, true);
6967});
6968
6969Handlebars.registerHelper('buildClinicMakeApptModalLink', function (url) {
6970    var path = SHC.util.getPathFromUrl(url);
6971    if (url && url.indexOf('.html') > -1) {
6972        // ie doesn't always have the forward slash at the beginning so add it if it's not there.
6973        if(path.indexOf('/') !== 0) {
6974            path = '/' + path;
6975        }
6976    }
6977
6978    return SHC.util.adjustPath(path, true);
6979});
6980
6981Handlebars.registerHelper('toUpperCase', function (str) {
6982    if(str) {
6983        return str.toUpperCase();
6984    }
6985    return null;
6986});
6987
6988Handlebars.registerHelper('hasClinicPassThroughInfo', function (selectedClinic, options) {
6989    if(selectedClinic && selectedClinic.clinicName && selectedClinic.contactInfo && selectedClinic.contactInfo.address) {
6990        return options.fn(this);
6991    }
6992
6993    return options.inverse(this);
6994});
6995
6996Handlebars.registerHelper('getClinicPassThroughUrl', function(clinicPath, clinicPageTitle) {
6997    clinicPath = clinicPath ? clinicPath.replace('/content/shc/en', '') : '';
6998    var url = SHC.ui.Search.DirectoryUtil.guidedDirectoryURL + "/&sp_clinics%7C" + clinicPath + ".html%5E" + encodeURIComponent($('<textarea />').html(clinicPageTitle).text());
6999    var filters = window.location.hash;
7000
7001    if(filters) {
7002        url += filters;
7003    }
7004    else if(SHC.ui.Search.DirectoryUtil.isPrimaryCareToggleActive()) {
7005        url += "#&x1=sp_prim_care_phy&q1=true";
7006    }
7007    else {
7008        url += "#&x1=sp_spec_care_phy&q1=true";
7009    }
7010
7011    return url;
7012});
7013
7014Handlebars.registerHelper('getL3ClinicPassThroughUrl', function() {
7015    var clinicPath = window.location.pathname.replace('/content/shc/en', '');
7016    var clinicPageTitle = jQuery('.shc-page-title').text().trim();
7017
7018    var filters = window.location.hash;
7019    var url = SHC.ui.Search.DirectoryUtil.guidedDirectoryURL + "/&sp_clinics%7C" + clinicPath + "%5E" + encodeURIComponent(clinicPageTitle);
7020
7021    if(filters) {
7022        url += filters;
7023    }
7024    else if(SHC.ui.Search.DirectoryUtil.isPrimaryCareToggleActive()) {
7025        url += "#&x1=sp_prim_care_phy&q1=true";
7026    }
7027    else {
7028        url += "#&x1=sp_spec_care_phy&q1=true";
7029    }
7030
7031    return url;
7032});
7033
7034Handlebars.registerHelper('getCurrentPagePath', function() {
7035    var url = window.location.pathname;
7036
7037    return url;
7038});
7039
7040Handlebars.registerHelper('getGuidedSearchURL', function() {
7041  var url =  SHC.ui.Search.DirectoryUtil.guidedDirectoryPage;
7042
7043  return url;
7044});
7045
7046Handlebars.registerHelper('getReactGuidedSearchPage', function() {
7047  var url =  SHC.ui.Search.DirectoryUtil.reactGuidedDirectoryPage;
7048
7049  return url;
7050});
7051
7052Handlebars.registerHelper('getLocationPassThroughUrl', function(location, locationAddress) {
7053
7054    var url = SHC.ui.Search.DirectoryUtil.guidedDirectoryURL + "/&sp_clinicLocations%7C" + location + "%5E" + encodeURIComponent(SHC.util.getCompleteAddress(locationAddress));
7055    var filters = window.location.hash;
7056
7057    if(filters) {
7058        url += filters;
7059    }
7060    else if(SHC.ui.Search.DirectoryUtil.isPrimaryCareToggleActive()) {
7061        url += "#&x1=sp_prim_care_phy&q1=true";
7062    }
7063    else {
7064        url += "#&x1=sp_spec_care_phy&q1=true";
7065    }
7066
7067    return url;
7068});
7069
7070Handlebars.registerHelper('getAlphaFilterPrefix', function () {         /* Default select box text must be added to titlesArray in supporting JS file. */
7071    if (SHC.ui.Search.DirectoryUtil.isDoctorDirectoryPage()){
7072        return "All Names ";
7073    }
7074    else if (SHC.ui.Search.DirectoryUtil.isClinicDirectoryPage()) {
7075        return "All Clinics ";
7076    }
7077    else if (SHC.ui.Search.DirectoryUtil.isConditionDirectoryPage()) {
7078        return "All Topics ";
7079    }
7080    else {
7081        return "";
7082    }
7083
7084});
7085
7086Handlebars.registerHelper('getAlphaFilterHeader', function () {                  /* Default select box text must be added to titlesArray in supporting JS file. */
7087    if (SHC.ui.Search.DirectoryUtil.isDoctorDirectoryPage()){
7088        return "DOCTOR'S LAST NAME";
7089    }
7090    else if (SHC.ui.Search.DirectoryUtil.isClinicDirectoryPage()) {
7091        return "CLINIC NAME";
7092    }
7093    else if (SHC.ui.Search.DirectoryUtil.isConditionDirectoryPage()) {
7094        return "TOPIC NAME";
7095    }
7096    else {
7097        return "";
7098    }
7099
7100});
7101
7102Handlebars.registerHelper('isActiveCheckBox', function (facet, cb, options) {
7103    var i;
7104    if (facet){
7105        for (i = 0; i < facet.length; i++) {
7106            if (facet[i]["value"].toLowerCase() === cb.toLowerCase()) {
7107                return options.fn();
7108            }
7109        }
7110    }
7111    return options.inverse();
7112});
7113
7114Handlebars.registerHelper('isActiveSortBy', function (options) {
7115    var hash = window.location.hash;
7116
7117    if(((SHC.ui.Search.DirectoryUtil.isConditionDirectoryPage()) && hash.indexOf("sp_s=title")  >= 0 )) {
7118        return options.fn(this);
7119    }
7120
7121    return options.inverse(this);
7122});
7123
7124Handlebars.registerHelper('formatPhoneNumber', function (phone) {
7125    phone = phone.toString();
7126    if(phone.length < 11) {
7127        return phone.substr(0,3) + '-' + phone.substr(3,3) + '-' + phone.substr(6,4);
7128    }
7129    return phone;
7130});
7131
7132Handlebars.registerHelper('decodeMapThumbnailURL', function (url) {
7133    // if the URL points to google, then we want to replace '&amp;' with '&'
7134    // as S&P encodes the '&' symbol in this URL
7135    if(url && url.indexOf('maps.googleapis.com/maps/api/staticmap') > -1) {
7136        return url.replace(new RegExp('&amp;', 'g'), '&');
7137    }
7138
7139    return url;
7140});
7141
7142Handlebars.registerHelper('isStanfordPhysician', function (result, options) {
7143    var path = SHC.util.getPathFromUrl(result.url);
7144
7145    if((path.indexOf('uha-doctors') === -1 && path.indexOf('pcha-doctors') === -1 ) || (result.participatingOrganizations && result.participatingOrganizations.indexOf('shc') > -1)) {
7146        return options.fn(this);
7147    }
7148    return options.inverse(this);
7149});
7150
7151//The expected format from S&P for the address is {address}|{address2}|{city}|{state}
7152Handlebars.registerHelper('getAddressValue', function (address, index) {
7153    var returnVal = "";
7154    if(address){
7155        var splitVals = address.split("|");
7156        if(splitVals.length > index){
7157            returnVal = splitVals[index];
7158        }
7159    }
7160    return returnVal;
7161});
7162
7163Handlebars.registerHelper('getLocationRelevantAddress', function(contactInfo, selectedLocation, index) {
7164    // first grab the first part of the address from selectedLocation
7165    var addressLine1 = selectedLocation.split(",")[0];
7166    // now let's see which clinic address contains this snippet
7167    for(var i = 0; i < contactInfo.length; i++) {
7168        if(contactInfo[i].address.indexOf(addressLine1) > -1) {
7169            if(index === "OfficeName") {
7170                return $('<textarea />').html(contactInfo[i].OfficeName).text();
7171            }
7172            else if(index === "zip") {
7173                return contactInfo[i].zip;
7174            }
7175            else if(index === "phoneNumbers") {
7176                return contactInfo[i].phoneNumbers;
7177            }
7178            else {
7179                return SHC.util.getAddressValue(contactInfo[i].address, index);
7180            }
7181        }
7182    }
7183});
7184
7185Handlebars.registerHelper('checkLocationRelevantAddress', function(contactInfo, selectedLocation, index, options) {
7186    // first grab the first part of the address from selectedLocation
7187    var addressLine1 = selectedLocation.split(",")[0];
7188    // now let's see which clinic address contains this snippet
7189    for(var i = 0; i < contactInfo.length; i++) {
7190        if(index === "address") {
7191            if (contactInfo[i].address) {
7192                if (contactInfo[i].address.indexOf(addressLine1) > -1) {
7193                    return options.fn(this);
7194                }
7195            }
7196        }
7197        else if(index === "phoneNumbers") {
7198            if(contactInfo[i].phoneNumbers) {
7199                if (contactInfo[i].address.indexOf(addressLine1) > -1) {
7200                    return options.fn(this);
7201                }
7202            }
7203        }
7204    }
7205    return options.inverse(this);
7206});
7207
7208Handlebars.registerHelper('locationRelevantOfficeIsNotLifeConnections', function(contactInfo, selectedLocation, options) {
7209    // first grab the first part of the address from selectedLocation
7210    var addressLine1 = selectedLocation.split(",")[0];
7211    // now let's see which clinic address contains this snippet
7212    for(var i = 0; i < contactInfo.length; i++) {
7213        if (contactInfo[i].address) {
7214            if (contactInfo[i].address.indexOf(addressLine1) > -1) {
7215                if(contactInfo[i].OfficeName.indexOf("LifeConnections") < 0) {
7216                    return options.fn(this);
7217                }
7218            }
7219        }
7220    }
7221    return options.inverse(this);
7222});
7223
7224Handlebars.registerHelper('getCompleteAddress', function(address) {
7225    var returnVal = "";
7226    if(address){
7227        var splitVals = address.split("|");
7228        for(var i = 0; i < splitVals.length; i++) {
7229            if(splitVals[i] !== "") {
7230                returnVal += splitVals[i].trim();
7231                if(i !== splitVals.length - 1) {
7232                    returnVal += ", ";
7233                }
7234            }
7235        }
7236    }
7237    return returnVal;
7238});
7239
7240Handlebars.registerHelper('getMainAddress', function(address) {
7241    var returnVal = "";
7242    if(address){
7243        var splitVals = address.split("|");
7244        for(var i = 0; i < splitVals.length; i++) {
7245            if(splitVals[i] !== "") {
7246                returnVal += splitVals[i].trim();
7247                if(i !== splitVals.length - 1) {
7248                    returnVal += ", ";
7249                }
7250            }
7251        }
7252    }
7253    return SHC.util.getMainAddress(returnVal);
7254});
7255
7256Handlebars.registerHelper('formatDistance', function(distance) {
7257    if (distance === '0.00') {
7258        return 0;
7259    } else if (distance < 10) {
7260        return Math.round(distance * 10)/10;
7261    } else {
7262        return parseInt(distance);
7263    }
7264});
7265
7266Handlebars.registerHelper('formatAcademicTitle', function(primaryAcademicTitle) {
7267    if(primaryAcademicTitle.indexOf("-") > -1){
7268        return primaryAcademicTitle.replace(/-(.*)\w+/g, "");
7269    } else if(primaryAcademicTitle.indexOf("(") > -1) {
7270        return primaryAcademicTitle.replace(/\s\(.*?\)/g, "");
7271    } else if(primaryAcademicTitle === "Dean of the Stanford University School of Medicine") {
7272        return primaryAcademicTitle = "Professor, Dean";
7273    } else if(primaryAcademicTitle === "Former Dean of the Stanford University School of Medicine") {
7274        return primaryAcademicTitle = "Professor, Former Dean";
7275    } else {
7276        return primaryAcademicTitle;
7277    }
7278});
7279
7280Handlebars.registerHelper('ifShowAccepting', function(options) {
7281    if(typeof GLOBAL_MICROSITE_SRC !== "undefined" && GLOBAL_MICROSITE_SRC !== "" && (GLOBAL_MICROSITE_SRC === "cisco" || GLOBAL_MICROSITE_SRC === "intel" )) {
7282        return options.fn(this);
7283    }
7284    return options.inverse(this);
7285});
7286
7287Handlebars.registerHelper('ifSHCA', function(options) {
7288    var isSHCAFindCarePage = GLOBAL_SEARCH_RESULTS_TEMPLATE === '/apps/shca/templates/searchresults';
7289    if (isSHCAFindCarePage) {
7290        return options.fn(this);
7291    } else {
7292        return options.inverse(this);
7293    }
7294});
7295
7296Handlebars.registerHelper('getSRC', function() {
7297    return "?fromMicro=" + GLOBAL_MICROSITE_SRC;
7298});
7299
7300Handlebars.registerHelper('ifUseSrc', function(options) {
7301    if(typeof GLOBAL_MICROSITE_SRC !== "undefined" && GLOBAL_MICROSITE_SRC !== "") {
7302        return options.fn(this);
7303    }
7304    return options.inverse(this);
7305});
7306
7307Handlebars.registerHelper('consoleLog', function(object) {
7308    console.log(object);
7309});
7310
7311Handlebars.registerHelper('womenOnlyAdjust', function(title) {
7312    if (title === 'Women Only') {
7313        return "Women Only (OB/GYN)";
7314    } else {
7315        return title;
7316    }
7317});
7318
7319Handlebars.registerHelper('usedZipCodeFilter', function(options) {
7320    if(SHC.util.getNumericalDistanceVarsFromURL("sp_q_location") !== null) {
7321        return options.fn(this);
7322    }
7323    return options.inverse(this);
7324});
7325
7326//in a condition page clicking on 'find doctors' will send to the directory page, this helper will populate the title
7327//at the top  and the link to go back to the condition page you came from
7328Handlebars.registerHelper('ifCtaPassthrough', function(options){
7329    var url = window.location.href.toLowerCase();
7330    url = url.replace(/\|/g, '%7c'); //firefox fix
7331    var passthroughPortion = url.substring(url.lastIndexOf('%7c') + 3);
7332
7333    if(passthroughPortion.indexOf('#&x') > -1) {
7334        passthroughPortion = passthroughPortion.substring(0, passthroughPortion.indexOf('#&x'));
7335    }
7336
7337    if( url.indexOf('%7c') > -1  &&
7338        url.indexOf('&sp_') > -1 &&
7339        passthroughPortion.indexOf('&') === -1){
7340        return options.fn(this);
7341    }else{
7342        return options.inverse(this);
7343    }
7344});
7345
7346Handlebars.registerHelper('ctaPassthroughName', function(){
7347    var url = window.location.href.toLowerCase();
7348    url = url.replace(/\|/g, '%7c'); //firefox fix
7349    var splitUrl = url.split('%7c');
7350    var conditionName;
7351    if (splitUrl.length >= 3) {
7352        var hashIndex = splitUrl[2].indexOf('#') > -1 ? splitUrl[2].indexOf('#') : splitUrl[2].length;
7353        conditionName = splitUrl[2].substring(0, hashIndex);
7354    }
7355    return decodeURI(conditionName);
7356});
7357
7358Handlebars.registerHelper('ctaPassthroughLink', function(){
7359    var url = window.location.href.toLowerCase();
7360    url = url.replace(/\|/g, '%7c'); //firefox fix
7361    var splitUrl = url.split('%7c');
7362    var linkPath = "";
7363    if (splitUrl.length >= 3) {
7364        linkPath = splitUrl[1];
7365    }
7366    SHC.util.adjustPath(linkPath);
7367    return linkPath;
7368});
7369
7370Handlebars.registerHelper('ifTrialsPassthrough', function(options){
7371    var url = window.location.href.toLowerCase();
7372    var passthroughPortion = "";
7373    if (url.indexOf('%7c') > -1) {
7374        passthroughPortion = url.substring(url.lastIndexOf('%7c') + 3);
7375    } else if (url.indexOf('|') > -1) {
7376        passthroughPortion = url.substring(url.lastIndexOf('|') + 1);
7377    } else {
7378        passthroughPortion = url;
7379    }
7380
7381    if (passthroughPortion.indexOf('#&x') > -1) {
7382        passthroughPortion = passthroughPortion.substring(0, passthroughPortion.indexOf('#&x'));
7383    }
7384    else if (passthroughPortion.indexOf('#x') > -1) {
7385        passthroughPortion = passthroughPortion.substring(0, passthroughPortion.indexOf('#x'));
7386    }
7387
7388    if ((url.indexOf('%7c') > -1 ||
7389        url.indexOf('|') > -1) &&
7390        url.indexOf('&sp_triallocks') > -1 &&
7391        passthroughPortion.indexOf('&q') === -1 &&
7392        passthroughPortion.indexOf('&x') === -1 &&
7393        SHC.clinicalTrialsFilter.paginationClickCounter === 0) {
7394        return options.fn(this);
7395    } else{
7396        return options.inverse(this);
7397    }
7398});
7399
7400Handlebars.registerHelper('trialsPassthroughLink', function(){
7401    var url = window.location.href.toLowerCase();
7402    url = url.replace(/\|/g, '%7c'); //firefox fix
7403    var splitUrl = url.split('%7c');
7404    var linkPath = "";
7405    if (splitUrl.length >= 3) {
7406        linkPath = splitUrl[2];
7407    }
7408    if (linkPath.indexOf("#") > -1) {
7409        linkPath = linkPath.substring(0, linkPath.indexOf("#"));
7410    }
7411    SHC.util.adjustPath(linkPath);
7412    return linkPath;
7413});
7414
7415Handlebars.registerHelper('trialsPassthroughName', function() {
7416
7417    var url = window.location.href.toLowerCase(),
7418        trialName = "",
7419        splitURL = "";
7420    if (url.indexOf('%7c') > -1) {
7421        if (url.indexOf('&recruiting') > -1) {
7422            splitURL = url.split('&recruiting')[0];
7423            if(splitURL.indexOf('%7c') > -1) {
7424                trialName = splitURL.split('%7c')[1];
7425            }
7426            else if(splitURL.indexOf('|') > -1) {
7427                trialName = splitURL.split('|')[1];
7428            }
7429        }
7430        else if (url.indexOf('&not_recruiting') > -1) {
7431            splitURL = url.split('&not_recruiting')[0];
7432            if(splitURL.indexOf('%7c') > -1) {
7433                trialName = splitURL.split('%7c')[1];
7434            }
7435            else if(splitURL.indexOf('|') > -1) {
7436                trialName = splitURL.split('|')[1];
7437            }
7438        }
7439    }
7440    else if (url.indexOf('|') > -1) {
7441        trialName = url.split('|')[1];
7442    }
7443    if (trialName.indexOf("#") > -1) {
7444        trialName = trialName.substring(0, trialName.indexOf("#"));
7445    }
7446    if (trialName.indexOf('&') > -1) {
7447        trialName = trialName.substring(0, trialName.indexOf('&'));
7448    }
7449    trialName = trialName.replace(/%2B/g, '+');
7450    trialName = trialName.replace(/%2b/g, '+');
7451    return decodeURI(trialName);
7452
7453});
7454
7455Handlebars.registerHelper('clinicalTrialsGetIdFromUrl', function(trialUrl){
7456    if(trialUrl && trialUrl.indexOf('NCT') > 0){
7457        var trialId = trialUrl.substring(trialUrl.indexOf('NCT') + 3).split('.html').join('');
7458        return  'TRIAL ID(NCT) ' + trialId;
7459    }
7460    return '';
7461});
7462
7463Handlebars.registerHelper('setItemSeparator', function(currentIndex, totalItems){
7464    if(currentIndex > 0 && totalItems > 1){
7465        return "hr";
7466    }
7467    return "";
7468});
7469
7470//Exact-match visibility helpers
7471Handlebars.registerHelper('setItemSeparatorExactMatch', function(currentIndex){
7472    if(currentIndex > 0 || SHC.clinicalTrialsFilter.paginationClickCounter > 0){
7473        return "hr";
7474    }
7475    return "";
7476});
7477
7478Handlebars.registerHelper('clinicalTrialViewMoreDisplay', function(data){
7479    if((data.total === data.upper)){
7480        return "hidden";
7481    }else{
7482        return "";
7483    }
7484});
7485
7486Handlebars.registerHelper('getPaginationClickCountClass', function(){
7487    if(typeof SHC.clinicalTrialsFilter.paginationClickCounter === 'undefined'){
7488        SHC.clinicalTrialsFilter.paginationClickCounter = 0;
7489    }
7490    return 'pagination_click_' + SHC.clinicalTrialsFilter.paginationClickCounter;
7491});
7492
7493/**
7494 * On pagination clicks, we still need the div for the filter rails to appear, just need to supress all of the filter boxes
7495 */
7496Handlebars.registerHelper('isNotPaginationClick', function(options){
7497    if(SHC.clinicalTrialsFilter.paginationClickCounter && SHC.clinicalTrialsFilter.paginationClickCounter > 0) {
7498        return options.inverse(this);
7499    }else{
7500        return options.fn(this);
7501    }
7502});
7503
7504//Non-Exact match helpers
7505Handlebars.registerHelper('resetTrialConditionCounter', function(){
7506    SHC.trialsConditionData = {};
7507    SHC.trialsConditionData.paginateAt = 20;
7508    SHC.trialsConditionData.totalCount = 0;
7509    SHC.trialsConditionData.alphaIndex = "";
7510    SHC.trialsConditionData.groupTotal = 0;
7511    SHC.trialsConditionData.groupCounter = 0;
7512    SHC.trialsConditionData.groupDisplayed = 0;
7513});
7514
7515Handlebars.registerHelper('insertAlphaHeader', function(condition){
7516    var letter = condition.substring(0,1).toUpperCase();
7517    if(SHC.trialsConditionData.alphaIndex.indexOf(letter) === -1){
7518        SHC.trialsConditionData.alphaIndex += letter;
7519
7520        var notFirst = "";
7521        if(SHC.trialsConditionData.groupCounter > 0){
7522            notFirst = " not-first ";
7523        }
7524
7525        var isHidden = "";
7526        if(SHC.trialsConditionData.groupTotal > 0){
7527            isHidden = " hidden ";
7528        }
7529
7530        var groupNumber = SHC.trialsConditionData.groupTotal; //to avoid showing a single letter with no results underneath
7531        if(SHC.trialsConditionData.groupCounter === SHC.trialsConditionData.paginateAt){
7532            groupNumber = parseInt(SHC.trialsConditionData.groupTotal) + 1;
7533        }
7534        return "<div class='condition-letter-header ct_grp_" + groupNumber + notFirst + isHidden + "'>" + letter + "</div>";
7535    }
7536});
7537
7538Handlebars.registerHelper('trialsConditionVisibility', function(){
7539    if(SHC.trialsConditionData.groupCounter === SHC.trialsConditionData.paginateAt){
7540        SHC.trialsConditionData.groupCounter = 0;
7541        SHC.trialsConditionData.groupTotal += 1;
7542    }
7543
7544    var groupClass = "ct_grp_" + SHC.trialsConditionData.groupTotal;
7545    if(SHC.trialsConditionData.groupTotal > 0){
7546        groupClass += " hidden";
7547    }
7548
7549    SHC.trialsConditionData.totalCount += 1;
7550    SHC.trialsConditionData.groupCounter += 1;
7551
7552    return groupClass;
7553});
7554
7555Handlebars.registerHelper('clinicalTrialConditionViewMoreDisplay', function(){
7556    if(SHC.trialsConditionData.totalCount < SHC.trialsConditionData.paginateAt ){
7557        return 'hidden';
7558    }
7559});
7560
7561Handlebars.registerHelper('getArrValueByValue', function(arr, val, param) {
7562    if (arr) {
7563        var element = $.grep(arr, function(e) {
7564            return e.value === val;
7565        });
7566        var value = 0;
7567        if (element && element[0] && element[0][param]) {
7568            value = element[0][param];
7569        }
7570        return value;
7571    }else if(val === 'RECRUITING' || val === 'NOT_RECRUITING'){
7572        return '0';
7573    }
7574});
7575
7576Handlebars.registerHelper('addArrayElements', function(arr, param) {
7577    var value = 0;
7578    if (arr) {
7579        arr.forEach(function(element) {
7580            if (param) {
7581                value = parseFloat(value) + parseFloat(element[param]);
7582            } else {
7583                value += parseFloat(value) + parseFloat(element);
7584            }
7585        });
7586    }
7587    return value;
7588});
7589
7590Handlebars.registerHelper('pluralize', function(word, count){
7591    if (count === "1" || count === 1){
7592        return word;
7593    }
7594    else{
7595        return word + "s";
7596    }
7597});
7598
7599Handlebars.registerHelper('setPredictiveTerm', function(data){
7600    SHC.DoctorDirPredictivePanelTerm = {};
7601    SHC.DoctorDirPredictivePanelTerm = data.searchTerm;
7602});
7603
7604Handlebars.registerHelper('getDoctorTitle', function(data){
7605    if(typeof data.doctorTitles !== 'undefined' && data.doctorTitles.length > 0 && typeof data.doctorTitles[0].doctorTitle !== 'undefined'){
7606        var finalTitle = data.doctorTitles[0].doctorTitle;
7607        for(var i=0; i < data.doctorTitles.length; i++){
7608            if(data.doctorTitles[i].doctorTitle.toLowerCase().indexOf(SHC.DoctorDirPredictivePanelTerm.toLowerCase().trim()) > -1){
7609                finalTitle = data.doctorTitles[i].doctorTitle;
7610            }
7611        }
7612        return "<br/><span class='pred-doctor-title'>" + finalTitle + "</span>";
7613    }
7614    return "";
7615});
7616
7617Handlebars.registerHelper('showPredictiveSections', function(data, dataType, options){
7618    if(data[dataType] && data[dataType].length > 0){
7619        return options.fn(this);
7620    }
7621    else {
7622        return options.inverse(this);
7623    }
7624});
7625
7626Handlebars.registerHelper('getDoctorPredictiveViewAllLink', function(){
7627    return SHC.ui.Search.DirectoryUtil.guidedDirectoryURL + "/" + encodeURIComponent(SHC.DoctorDirPredictivePanelTerm) + "#x1=sp_spec_care_phy&q1=true&page=1";
7628});
7629
7630Handlebars.registerHelper('getClinicPredictiveViewAllLink', function(){
7631    return SHC.ui.Search.DirectoryUtil.guidedDirectoryURL + "/" + encodeURIComponent(SHC.DoctorDirPredictivePanelTerm) + "#x1=sp_prim_care_clinic&q1=true&page=1";
7632});
7633
7634Handlebars.registerHelper('getNewsroomPredictiveViewAllLink', function(searchTerm, collection){
7635    var q1 = "image";
7636    if (collection === "news-updates") {
7637        q1 = "news-updates";
7638    } else if (collection === "videos") {
7639        q1 = "video";
7640    }
7641    var fullpath = "/content/shc/en/search-results.newsroom.html/" + encodeURIComponent(searchTerm) + "?src=pred_newsroom#x1=sp_tags&q1=" + q1;
7642    return SHC.util.adjustPath(fullpath);
7643});
7644
7645Handlebars.registerHelper('replaceAll', function(string, old, knew) {
7646    if (string) {
7647        return string.replace(new RegExp(old, "g"), knew);
7648    }
7649    return "";
7650});
7651/**
7652 * Validate the list contains at least one element.
7653 */
7654Handlebars.registerHelper('listNotEmpty', function(v1, options) {
7655    if (v1 && v1.length && v1.length > 0) {
7656        return options.fn(this);
7657    }
7658    return options.inverse(this);
7659});
7660
7661Handlebars.registerHelper('listEmpty', function(v1, options) {
7662    if (!v1) {
7663        return options.fn(this);
7664    }
7665    return options.inverse(this);
7666});
7667
7668Handlebars.registerHelper('arrayLength', function(arr) {
7669    return arr.length;
7670});
7671
7672Handlebars.registerHelper('ifArrayIsEmpty', function(arr, options){
7673    if( (arr && arr.length === 0) || (typeof arr === 'undefined')) {
7674        return options.fn(this);
7675    } else {
7676        return options.inverse(this);
7677    }
7678});
7679
7680Handlebars.registerHelper('newsroomCategoryNameFix', function(categoryName, tagMap) {
7681    if (tagMap) {
7682        if (categoryName) {
7683            var categoryNameFormatted = categoryName.toLowerCase();
7684            if (tagMap[categoryNameFormatted]) {
7685                return tagMap[categoryNameFormatted];
7686            }
7687        }
7688    }
7689
7690    var words = categoryName.split('_');
7691    categoryName = "";
7692    words.forEach(function(element){
7693        categoryName += element.charAt(0).toUpperCase() + element.slice(1) + " ";
7694    });
7695    return categoryName.trim();
7696});
7697
7698/***
7699 * Truncates a text string to a number of characters and adds ellipsis, for "dont truncate" pass in the number 0
7700 * Specify different character lengths to truncate at for desktop, tablet and mobile
7701 */
7702Handlebars.registerHelper('textEllipsis', function(text, desktopTruncation, tabletTruncation, mobileTruncation){
7703    if(SHC.ui.screenMode === 'large' && desktopTruncation !== 0){
7704        return SHC.util.ellipsis(text, desktopTruncation);
7705
7706    }else if(SHC.ui.screenMode === 'medium' && tabletTruncation !== 0){
7707        return SHC.util.ellipsis(text, tabletTruncation );
7708
7709    }else if(SHC.ui.screenMode === 'small' && mobileTruncation !== 0){
7710        return SHC.util.ellipsis(text, mobileTruncation);
7711    }
7712    return text;
7713});
7714
7715/**
7716 * takes a date in the format mm.dd.yy and turns it into: month day, year
7717 * 01.01.17 to January 1. 2017
7718 */
7719Handlebars.registerHelper('longDateFormatter', function(date){
7720    var ls = 'en-us';
7721    //regex format: Mon, 05 Dec 2016 17:00:00 GMT
7722    var dateRegEx = new RegExp('[A-Za-z]{3},[ ][0-9]*[ ][A-Za-z]{3}[ ][0-9]{4}[ ][0-9]*[:][0-9]*[:][0-9]*[ ](GMT)');
7723
7724    if(dateRegEx.test(date)){
7725        var dateObj = new Date(date);
7726        var month = dateObj.toLocaleDateString(ls ,{month: 'long'});
7727        var day   = dateObj.toLocaleDateString(ls ,{day: 'numeric'});
7728        var year  = dateObj.toLocaleDateString(ls ,{year: 'numeric'});
7729
7730        return month + ' ' + day + ', ' + year;
7731    }else {
7732        var dateArr =  date.split('.');
7733        var months = ["January","February","March","April","May","June","July","August","September","October","November","December"];
7734
7735        return months[dateArr[0] - 1] + ' ' + dateArr[1] + ', ' + 20 + dateArr[2];
7736    }
7737});
7738
7739/**
7740 * format the correct link to display an image, use when S&P returns image links form multiple locations
7741 */
7742Handlebars.registerHelper('imageLinkProcessor', function(link){
7743    if(link.indexOf('jcr:content/') > 0){
7744        return link + '.img.png';
7745    }else{
7746        return link;
7747    }
7748});
7749
7750Handlebars.registerHelper('toLowerCase', function(str) {
7751  if (typeof str === "string") {
7752    return str.toLowerCase();
7753  }
7754});
7755
7756Handlebars.registerHelper('notLocation', function(templatePath){
7757    var isLocationTemplate = "/apps/shc/templates/location" === templatePath;
7758    if(isLocationTemplate) {
7759        return 'modalcontainer';
7760    } else {
7761        return 'mapcontainer';
7762    }
7763});
7764
7765Handlebars.registerHelper('isLargeViewport', function () {
7766    if(SHC.ui.screenMode === 'large') {
7767        return true;
7768    } else if(SHC.ui.screenMode === 'medium') {
7769        return false;
7770    } else if(SHC.ui.screenMode === 'small') {
7771        return false;
7772    }
7773    return true;
7774});
7775
7776Handlebars.registerHelper('isNotLargeViewport', function () {
7777    if(SHC.ui.screenMode === 'large') {
7778        return false;
7779    } else if(SHC.ui.screenMode === 'medium') {
7780        return true;
7781    } else if(SHC.ui.screenMode === 'small') {
7782        return true;
7783    }
7784    return false;
7785});
7786
7787Handlebars.registerHelper('isValleycare', function () {
7788    return SHC.util.isValleycare();
7789});
7790
7791Handlebars.registerHelper('isStanfordlab', function () {
7792    return SHC.util.isStanfordlab();
7793});
7794
7795//
7796//  Handlebars partial file for parsing and displaying no-results options.
7797//
7798var topStr = '<h2>Sorry, we couldn\'t find what you\'re looking for based on your search criteria</h2>' +
7799             '<h3>Here are a few suggestions to improve your search.</h3>';
7800
7801var midStr = '<ul class=\'suggestions\'>' +
7802                 '<li>Check your spelling</li>' +
7803                 '<li>Try more general words or try a different search term</li>';
7804
7805var endStr = '<h4>If you refined your results, try removing one of your selections.</h4>';
7806
7807//Doctors page Specialist toggle
7808Handlebars.registerPartial('noResultsDoctorSpecialty',
7809    topStr +
7810    '<h4>If you searched by name or specialty:</h4>' +
7811    midStr +
7812    '<li>Try changing the doctor type to Primary Care</li>' +
7813    '</ul>' +
7814    endStr
7815);
7816
7817//Doctors Page Primary Care toggle
7818Handlebars.registerPartial('noResultsDoctorPrimary',
7819    topStr +
7820    '<h4>If you searched by name or specialty:</h4>' +
7821    midStr +
7822    '<li>Try changing the doctor type to Specialist</li>' +
7823    '</ul>' +
7824    endStr
7825);
7826
7827//Clinics & Locations Page Specialty Care toggle
7828Handlebars.registerPartial('noResultsClinicsSpecialty',
7829    topStr +
7830    '<h4>If you searched by name or specialty:</h4>' +
7831    midStr +
7832    '<li>Try changing the clinic type to Primary Care or Other Services</li>' +
7833    '</ul>' +
7834    endStr
7835);
7836
7837//Clinics & Locations Page Primary Care toggle
7838Handlebars.registerPartial('noResultsClinicsPrimary',
7839    topStr +
7840    '<h4>If you searched by name or specialty:</h4>' +
7841    midStr +
7842    '<li>Try changing the clinic type to Specialty Care or Other Services</li>' +
7843    '</ul>' +
7844    endStr
7845);
7846
7847//Clinics & Locations Page Other Services Toggle
7848Handlebars.registerPartial('noResultsClinicsOther',
7849    topStr +
7850    '<h4>If you searched by name or specialty:</h4>' +
7851    midStr +
7852    '<li>Try changing the clinic type to Specialty Care or Primary Care</li>' +
7853    '</ul>' +
7854    endStr
7855);
7856
7857//Conditions & Treatments all pages.
7858Handlebars.registerPartial('noResultsConditionsAndTreatment',
7859    topStr +
7860    '<h4>If you typed something into the search bar:</h4>' +
7861    midStr +
7862    '<li>Try changing the setting “Show me results for” to All</li>' +
7863    '</ul>' +
7864    endStr
7865);
7866
7867//Doctors page Specialist toggle
7868Handlebars.registerPartial('noResultsDoctorSpecialtyMap',
7869    topStr +
7870    '<h4>If you searched by name or specialty:</h4>' +
7871    midStr +
7872    '<li>Try changing the doctor type to Primary Care</li>' +
7873    '</ul>'
7874);
7875
7876//Doctors Page Primary Care toggle
7877Handlebars.registerPartial('noResultsDoctorPrimaryMap',
7878    topStr +
7879    '<h4>If you searched by name or specialty:</h4>' +
7880    midStr +
7881    '<li>Try changing the doctor type to Specialist</li>' +
7882    '</ul>'
7883);
7884
7885//Clinics & Locations Page Specialty Care toggle
7886Handlebars.registerPartial('noResultsClinicsSpecialtyMap',
7887    topStr +
7888    '<h4>If you searched by name or specialty:</h4>' +
7889    midStr +
7890    '<li>Try changing the clinic type to Primary Care or Other Services</li>' +
7891    '</ul>'
7892);
7893
7894//Clinics & Locations Page Primary Care toggle
7895Handlebars.registerPartial('noResultsClinicsPrimaryMap',
7896    topStr +
7897    '<h4>If you searched by name or specialty:</h4>' +
7898    midStr +
7899    '<li>Try changing the clinic type to Specialty Care or Other Services</li>' +
7900    '</ul>'
7901);
7902
7903//Clinics & Locations Page Other Services Toggle
7904Handlebars.registerPartial('noResultsClinicsOtherMap',
7905    topStr +
7906    '<h4>If you searched by name or specialty:</h4>' +
7907    midStr +
7908    '<li>Try changing the clinic type to Specialty Care or Primary Care</li>' +
7909    '</ul>'
7910);
7911this["JST"] = this["JST"] || {};
7912
7913Handlebars.registerPartial("checkboxItem", Handlebars.template({"compiler":[7,">= 4.0.0"],"main":function(container,depth0,helpers,partials,data) {
7914    var stack1, helper, alias1=depth0 != null ? depth0 : (container.nullContext || {}), alias2=helpers.helperMissing, alias3="function", alias4=container.escapeExpression;
7915
7916  return "<div class=\"checkbox\">
vendor: 6,289 bytes, lines 7916-7974
7916\n<input type=\"checkbox\" id=\""
7917    + alias4(((helper = (helper = helpers.id || (depth0 != null ? depth0.id : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"id","hash":{},"data":data}) : helper)))
7918    + "\">\n<label class=\"checkbox-text\" for=\""
7919    + alias4(((helper = (helper = helpers.id || (depth0 != null ? depth0.id : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"id","hash":{},"data":data}) : helper)))
7920    + "\"><span></span>"
7921    + ((stack1 = ((helper = (helper = helpers.text || (depth0 != null ? depth0.text : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"text","hash":{},"data":data}) : helper))) != null ? stack1 : "")
7922    + "</label>\n</div>\n";
7923},"useData":true}));
7924
7925Handlebars.registerPartial("clinicLocations", Handlebars.template({"1":function(container,depth0,helpers,partials,data) {
7926    var stack1;
7927
7928  return ((stack1 = helpers["if"].call(depth0 != null ? depth0 : (container.nullContext || {}),((stack1 = (depth0 != null ? depth0.specialInterests : depth0)) != null ? stack1.length : stack1),{"name":"if","hash":{},"fn":container.program(2, data, 0),"inverse":container.program(5, data, 0),"data":data})) != null ? stack1 : "");
7929},"2":function(container,depth0,helpers,partials,data) {
7930    var stack1;
7931
7932  return ((stack1 = helpers["if"].call(depth0 != null ? depth0 : (container.nullContext || {}),((stack1 = (depth0 != null ? depth0.clinicLocations : depth0)) != null ? stack1.length : stack1),{"name":"if","hash":{},"fn":container.program(3, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "");
7933},"3":function(container,depth0,helpers,partials,data) {
7934    return "<div class='col-xl-6 col-lg-6 col-md-6 col-sm-6 col-xs-6 clinic-locations right-column border_container'>\n";
7935},"5":function(container,depth0,helpers,partials,data) {
7936    return "<div class='col-xl-6 col-lg-6 col-md-6 col-sm-6 col-xs-6 clinic-locations right-column'>\n";
7937},"7":function(container,depth0,helpers,partials,data) {
7938    var stack1;
7939
7940  return ((stack1 = helpers["if"].call(depth0 != null ? depth0 : (container.nullContext || {}),((stack1 = (depth0 != null ? depth0.conditionsTreated : depth0)) != null ? stack1.length : stack1),{"name":"if","hash":{},"fn":container.program(2, data, 0),"inverse":container.program(5, data, 0),"data":data})) != null ? stack1 : "");
7941},"9":function(container,depth0,helpers,partials,data) {
7942    var stack1, alias1=depth0 != null ? depth0 : (container.nullContext || {});
7943
7944  return "<h4>Clinic Locations</h4>\n"
7945    + ((stack1 = helpers.each.call(alias1,(depth0 != null ? depth0.clinicLocations : depth0),{"name":"each","hash":{},"fn":container.program(10, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
7946    + ((stack1 = (helpers.ifGreaterThan || (depth0 && depth0.ifGreaterThan) || helpers.helperMissing).call(alias1,((stack1 = (depth0 != null ? depth0.clinicLocations : depth0)) != null ? stack1.length : stack1),1,{"name":"ifGreaterThan","hash":{},"fn":container.program(22, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "");
7947},"10":function(container,depth0,helpers,partials,data) {
7948    var stack1;
7949
7950  return ((stack1 = helpers["if"].call(depth0 != null ? depth0 : (container.nullContext || {}),(data && data.first),{"name":"if","hash":{},"fn":container.program(11, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "");
7951},"11":function(container,depth0,helpers,partials,data) {
7952    var stack1, helper, alias1=depth0 != null ? depth0 : (container.nullContext || {}), alias2=helpers.helperMissing, alias3="function", alias4=container.escapeExpression;
7953
7954  return "<div class='location'>\n"
7955    + ((stack1 = helpers["if"].call(alias1,((stack1 = (depth0 != null ? depth0.officeName : depth0)) != null ? stack1.length : stack1),{"name":"if","hash":{},"fn":container.program(12, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
7956    + ((stack1 = helpers["if"].call(alias1,((stack1 = (depth0 != null ? depth0.OfficeName : depth0)) != null ? stack1.length : stack1),{"name":"if","hash":{},"fn":container.program(14, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
7957    + "<p>"
7958    + alias4(((helper = (helper = helpers.address || (depth0 != null ? depth0.address : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"address","hash":{},"data":data}) : helper)))
7959    + "<br>\n"
7960    + ((stack1 = helpers["if"].call(alias1,((stack1 = (depth0 != null ? depth0.address2 : depth0)) != null ? stack1.length : stack1),{"name":"if","hash":{},"fn":container.program(16, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
7961    + alias4(((helper = (helper = helpers.city || (depth0 != null ? depth0.city : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"city","hash":{},"data":data}) : helper)))
7962    + ", "
7963    + alias4(((helper = (helper = helpers.state || (depth0 != null ? depth0.state : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"state","hash":{},"data":data}) : helper)))
7964    + " "
7965    + alias4(((helper = (helper = helpers.zip || (depth0 != null ? depth0.zip : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"zip","hash":{},"data":data}) : helper)))
7966    + "<br>\n<span class=\"phoneNumber\">\nTel: "
7967    + ((stack1 = helpers.each.call(alias1,(depth0 != null ? depth0.phoneNumbers : depth0),{"name":"each","hash":{},"fn":container.program(18, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
7968    + ((stack1 = helpers["if"].call(alias1,(depth0 != null ? depth0.fax : depth0),{"name":"if","hash":{},"fn":container.program(20, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
7969    + "\n</span>\n</p>\n</div>\n";
7970},"12":function(container,depth0,helpers,partials,data) {
7971    var stack1, helper;
7972
7973  return "<p><b>"
7974    + ((stack1 = ((helper = (helper = helpers.officeName || (depth0 != null ? depth0.officeName : depth0)) != null ? helper : helpers.helperMissing),(typeof helper === "function" ? helper.call(depth0 != null ? depth0 : (container.nullContext || {}
vendor: 5,356 bytes, lines 7974-8041
7974),{"name":"officeName","hash":{},"data":data}) : helper))) != null ? stack1 : "")
7975    + "</b></p>\n";
7976},"14":function(container,depth0,helpers,partials,data) {
7977    var stack1, helper;
7978
7979  return "<p><b>"
7980    + ((stack1 = ((helper = (helper = helpers.OfficeName || (depth0 != null ? depth0.OfficeName : depth0)) != null ? helper : helpers.helperMissing),(typeof helper === "function" ? helper.call(depth0 != null ? depth0 : (container.nullContext || {}),{"name":"OfficeName","hash":{},"data":data}) : helper))) != null ? stack1 : "")
7981    + "</b></p>\n";
7982},"16":function(container,depth0,helpers,partials,data) {
7983    var stack1, helper;
7984
7985  return ((stack1 = ((helper = (helper = helpers.address2 || (depth0 != null ? depth0.address2 : depth0)) != null ? helper : helpers.helperMissing),(typeof helper === "function" ? helper.call(depth0 != null ? depth0 : (container.nullContext || {}),{"name":"address2","hash":{},"data":data}) : helper))) != null ? stack1 : "")
7986    + "<br>\n";
7987},"18":function(container,depth0,helpers,partials,data) {
7988    return "\n"
7989    + container.escapeExpression(container.lambda(depth0, depth0))
7990    + "\n";
7991},"20":function(container,depth0,helpers,partials,data) {
7992    var helper;
7993
7994  return "<br> Fax: "
7995    + container.escapeExpression(((helper = (helper = helpers.fax || (depth0 != null ? depth0.fax : depth0)) != null ? helper : helpers.helperMissing),(typeof helper === "function" ? helper.call(depth0 != null ? depth0 : (container.nullContext || {}),{"name":"fax","hash":{},"data":data}) : helper)));
7996},"22":function(container,depth0,helpers,partials,data) {
7997    var helper, alias1=depth0 != null ? depth0 : (container.nullContext || {}), alias2=helpers.helperMissing, alias3="function", alias4=container.escapeExpression;
7998
7999  return "<a href='"
8000    + alias4(((helper = (helper = helpers.path || (depth0 != null ? depth0.path : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"path","hash":{},"data":data}) : helper)))
8001    + ".html#summary-content'>See All "
8002    + alias4(((helper = (helper = helpers.clinicCounts || (depth0 != null ? depth0.clinicCounts : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"clinicCounts","hash":{},"data":data}) : helper)))
8003    + " Clinics</a>\n";
8004},"compiler":[7,">= 4.0.0"],"main":function(container,depth0,helpers,partials,data) {
8005    var stack1, alias1=depth0 != null ? depth0 : (container.nullContext || {});
8006
8007  return ((stack1 = helpers["if"].call(alias1,(depth0 != null ? depth0.isPrimaryCareDeck : depth0),{"name":"if","hash":{},"fn":container.program(1, data, 0),"inverse":container.program(7, data, 0),"data":data})) != null ? stack1 : "")
8008    + "\n"
8009    + ((stack1 = helpers["if"].call(alias1,((stack1 = (depth0 != null ? depth0.clinicLocations : depth0)) != null ? stack1.length : stack1),{"name":"if","hash":{},"fn":container.program(9, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
8010    + "\n</div>\n";
8011},"useData":true}));
8012
8013Handlebars.registerPartial("columns", Handlebars.template({"1":function(container,depth0,helpers,partials,data) {
8014    var stack1;
8015
8016  return ((stack1 = container.invokePartial(partials.checkboxItem,depth0,{"name":"checkboxItem","data":data,"helpers":helpers,"partials":partials,"decorators":container.decorators})) != null ? stack1 : "");
8017},"compiler":[7,">= 4.0.0"],"main":function(container,depth0,helpers,partials,data) {
8018    var stack1, alias1=depth0 != null ? depth0 : (container.nullContext || {});
8019
8020  return "<div class=\"row\">\n<div class=\"col-sm-4\">\n"
8021    + ((stack1 = helpers.each.call(alias1,(depth0 != null ? depth0.col1 : depth0),{"name":"each","hash":{},"fn":container.program(1, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
8022    + "</div>\n<div class=\"col-sm-4\">\n"
8023    + ((stack1 = helpers.each.call(alias1,(depth0 != null ? depth0.col2 : depth0),{"name":"each","hash":{},"fn":container.program(1, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
8024    + "</div>\n<div class=\"col-sm-4\">\n"
8025    + ((stack1 = helpers.each.call(alias1,(depth0 != null ? depth0.col3 : depth0),{"name":"each","hash":{},"fn":container.program(1, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
8026    + "</div>\n</div>\n";
8027},"usePartial":true,"useData":true}));
8028
8029Handlebars.registerPartial("conditionResult", Handlebars.template({"compiler":[7,">= 4.0.0"],"main":function(container,depth0,helpers,partials,data) {
8030    var stack1, helper, alias1=depth0 != null ? depth0 : (container.nullContext || {}), alias2=helpers.helperMissing, alias3="function";
8031
8032  return "<li class=\"cond-result\">\n<a href=\""
8033    + container.escapeExpression(((helper = (helper = helpers.url || (depth0 != null ? depth0.url : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"url","hash":{},"data":data}) : helper)))
8034    + "\">"
8035    + ((stack1 = ((helper = (helper = helpers.title || (depth0 != null ? depth0.title : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"title","hash":{},"data":data}) : helper))) != null ? stack1 : "")
8036    + "</a>\n</li>\n";
8037},"useData":true}));
8038
8039Handlebars.registerPartial("conditionsTreated", Handlebars.template({"1":function(container,depth0,helpers,partials,data) {
8040    var stack1;
8041
vendor: 9,410 bytes, lines 8042-8138
8042  return ((stack1 = helpers["if"].call(depth0 != null ? depth0 : (container.nullContext || {}),((stack1 = (depth0 != null ? depth0.specialInterests : depth0)) != null ? stack1.length : stack1),{"name":"if","hash":{},"fn":container.program(2, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "");
8043},"2":function(container,depth0,helpers,partials,data) {
8044    var stack1, alias1=depth0 != null ? depth0 : (container.nullContext || {});
8045
8046  return "<div class='col-xl-6 col-lg-6 col-md-6 col-sm-6 col-xs-6 conditions-treated '>\n<h4>Areas of Interest</h4>\n"
8047    + ((stack1 = helpers.each.call(alias1,(depth0 != null ? depth0.specialInterests : depth0),{"name":"each","hash":{},"fn":container.program(3, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
8048    + ((stack1 = (helpers.ifGreaterThan || (depth0 && depth0.ifGreaterThan) || helpers.helperMissing).call(alias1,((stack1 = (depth0 != null ? depth0.specialInterests : depth0)) != null ? stack1.length : stack1),4,{"name":"ifGreaterThan","hash":{},"fn":container.program(9, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
8049    + "</div>\n";
8050},"3":function(container,depth0,helpers,partials,data) {
8051    var stack1;
8052
8053  return ((stack1 = (helpers.ifLessThan || (depth0 && depth0.ifLessThan) || helpers.helperMissing).call(depth0 != null ? depth0 : (container.nullContext || {}),(data && data.index),4,{"name":"ifLessThan","hash":{},"fn":container.program(4, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "");
8054},"4":function(container,depth0,helpers,partials,data) {
8055    var stack1, alias1=depth0 != null ? depth0 : (container.nullContext || {});
8056
8057  return ((stack1 = helpers["if"].call(alias1,((stack1 = (depth0 != null ? depth0.value : depth0)) != null ? stack1.length : stack1),{"name":"if","hash":{},"fn":container.program(5, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
8058    + ((stack1 = (helpers.ifNotEmpty || (depth0 && depth0.ifNotEmpty) || helpers.helperMissing).call(alias1,(depth0 != null ? depth0.path : depth0),{"name":"ifNotEmpty","hash":{},"fn":container.program(7, data, 0),"inverse":container.program(7, data, 0),"data":data})) != null ? stack1 : "");
8059},"5":function(container,depth0,helpers,partials,data) {
8060    return "<a class=\"profile-deck-condition no-links\">"
8061    + container.escapeExpression(container.lambda((depth0 != null ? depth0.value : depth0), depth0))
8062    + "</a>\n";
8063},"7":function(container,depth0,helpers,partials,data) {
8064    return "<a class=\"profile-deck-condition no-links\">"
8065    + container.escapeExpression(container.lambda((depth0 != null ? depth0.title : depth0), depth0))
8066    + "</a>\n";
8067},"9":function(container,depth0,helpers,partials,data) {
8068    var stack1, helper, alias1=container.escapeExpression;
8069
8070  return "<a class='viewAll' href='"
8071    + alias1(((helper = (helper = helpers.path || (depth0 != null ? depth0.path : depth0)) != null ? helper : helpers.helperMissing),(typeof helper === "function" ? helper.call(depth0 != null ? depth0 : (container.nullContext || {}),{"name":"path","hash":{},"data":data}) : helper)))
8072    + ".html#summary-practices'>View All "
8073    + alias1(container.lambda(((stack1 = (depth0 != null ? depth0.specialInterests : depth0)) != null ? stack1.length : stack1), depth0))
8074    + " Practice Areas</a>\n";
8075},"11":function(container,depth0,helpers,partials,data) {
8076    var stack1;
8077
8078  return ((stack1 = helpers["if"].call(depth0 != null ? depth0 : (container.nullContext || {}),((stack1 = (depth0 != null ? depth0.conditionsTreated : depth0)) != null ? stack1.length : stack1),{"name":"if","hash":{},"fn":container.program(12, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "");
8079},"12":function(container,depth0,helpers,partials,data) {
8080    var stack1, alias1=depth0 != null ? depth0 : (container.nullContext || {});
8081
8082  return "<div class='col-xl-6 col-lg-6 col-md-6 col-sm-6 col-xs-6 conditions-treated '>\n<h4>Practice Areas</h4>\n"
8083    + ((stack1 = helpers.each.call(alias1,(depth0 != null ? depth0.conditionsTreated : depth0),{"name":"each","hash":{},"fn":container.program(13, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
8084    + ((stack1 = (helpers.ifGreaterThan || (depth0 && depth0.ifGreaterThan) || helpers.helperMissing).call(alias1,((stack1 = (depth0 != null ? depth0.conditionsTreated : depth0)) != null ? stack1.length : stack1),4,{"name":"ifGreaterThan","hash":{},"fn":container.program(19, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
8085    + "</div>\n";
8086},"13":function(container,depth0,helpers,partials,data) {
8087    var stack1;
8088
8089  return ((stack1 = (helpers.ifLessThan || (depth0 && depth0.ifLessThan) || helpers.helperMissing).call(depth0 != null ? depth0 : (container.nullContext || {}),(data && data.index),4,{"name":"ifLessThan","hash":{},"fn":container.program(14, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "");
8090},"14":function(container,depth0,helpers,partials,data) {
8091    var stack1, alias1=depth0 != null ? depth0 : (container.nullContext || {});
8092
8093  return ((stack1 = helpers["if"].call(alias1,((stack1 = (depth0 != null ? depth0.value : depth0)) != null ? stack1.length : stack1),{"name":"if","hash":{},"fn":container.program(15, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
8094    + ((stack1 = (helpers.ifNotEmpty || (depth0 && depth0.ifNotEmpty) || helpers.helperMissing).call(alias1,(depth0 != null ? depth0.path : depth0),{"name":"ifNotEmpty","hash":{},"fn":container.program(17, data, 0),"inverse":container.program(7, data, 0),"data":data})) != null ? stack1 : "");
8095},"15":function(container,depth0,helpers,partials,data) {
8096    var alias1=container.lambda, alias2=container.escapeExpression;
8097
8098  return "<a href='"
8099    + alias2(alias1((depth0 != null ? depth0.path : depth0), depth0))
8100    + "'>"
8101    + alias2(alias1((depth0 != null ? depth0.value : depth0), depth0))
8102    + "</a>\n";
8103},"17":function(container,depth0,helpers,partials,data) {
8104    var helper, alias1=container.escapeExpression;
8105
8106  return "<a href='"
8107    + alias1(((helper = (helper = helpers.path || (depth0 != null ? depth0.path : depth0)) != null ? helper : helpers.helperMissing),(typeof helper === "function" ? helper.call(depth0 != null ? depth0 : (container.nullContext || {}),{"name":"path","hash":{},"data":data}) : helper)))
8108    + ".html'>"
8109    + alias1(container.lambda((depth0 != null ? depth0.title : depth0), depth0))
8110    + "</a>\n";
8111},"19":function(container,depth0,helpers,partials,data) {
8112    var helper, alias1=depth0 != null ? depth0 : (container.nullContext || {}), alias2=helpers.helperMissing, alias3="function", alias4=container.escapeExpression;
8113
8114  return "<a class='viewAll' href='"
8115    + alias4(((helper = (helper = helpers.path || (depth0 != null ? depth0.path : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"path","hash":{},"data":data}) : helper)))
8116    + ".html#summary-practices'>View All "
8117    + alias4(((helper = (helper = helpers.conditions_count || (depth0 != null ? depth0.conditions_count : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"conditions_count","hash":{},"data":data}) : helper)))
8118    + " Practice Areas</a>\n";
8119},"compiler":[7,">= 4.0.0"],"main":function(container,depth0,helpers,partials,data) {
8120    var stack1;
8121
8122  return ((stack1 = helpers["if"].call(depth0 != null ? depth0 : (container.nullContext || {}),(depth0 != null ? depth0.isPrimaryCareDeck : depth0),{"name":"if","hash":{},"fn":container.program(1, data, 0),"inverse":container.program(11, data, 0),"data":data})) != null ? stack1 : "");
8123},"useData":true}));
8124
8125Handlebars.registerPartial("edTimeAdult", Handlebars.template({"1":function(container,depth0,helpers,partials,data) {
8126    return "<div class=\"ed-time\">\n<div class=\"ed-time-title\">Current Adult ED Wait Time</div>\n<div class=\"ed-time-timer adult\"></div>\n<div class=\"ed-time-sub-text\">Estimated wait times are approximate and subject to change.</div>\n<a href=\"https://stanfordhealthcare.org/medical-clinics/emergency-department-1199-welch.html\" class=\"ed-time-cta\">Learn More</a>\n</div>\n";
8127},"compiler":[7,">= 4.0.0"],"main":function(container,depth0,helpers,partials,data) {
8128    var stack1;
8129
8130  return ((stack1 = (helpers.ifMatches || (depth0 && depth0.ifMatches) || helpers.helperMissing).call(depth0 != null ? depth0 : (container.nullContext || {}),(depth0 != null ? depth0.title : depth0),"Adult Emergency Department",{"name":"ifMatches","hash":{},"fn":container.program(1, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "");
8131},"useData":true}));
8132
8133Handlebars.registerPartial("edTimePedia", Handlebars.template({"1":function(container,depth0,helpers,partials,data) {
8134    return "<div class=\"ed-time\">\n<div class=\"ed-time-title\">Current Pediatric ED Wait Time</div>\n<div class=\"ed-time-timer pedia\"></div>\n<div class=\"ed-time-sub-text\">Estimated wait times are approximate and subject to change.</div>\n<a href=\"https://stanfordhealthcare.org/medical-clinics/emergency-department-900-quarry.html\" class=\"ed-time-cta\">Learn More</a>\n</div>\n";
8135},"compiler":[7,">= 4.0.0"],"main":function(container,depth0,helpers,partials,data) {
8136    var stack1;
8137
8138  return ((stack1 = (helpers.ifMatches || (depth0 && depth0.ifMatches) || helpers.helperMissing).call(
8138depth0 != null ? depth0 : (container.nullContext || {}),(depth0 != null ? depth0.title : depth0),"Pediatric Emergency Department",{"name":"ifMatches","hash":{},"fn":container.program(1, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "");
8139},"useData":true}));
8140
8141Handlebars.registerPartial("focusBox", Handlebars.template({"1":function(container,depth0,helpers,partials,data) {
8142    var stack1;
8143
8144  return ((stack1 = (helpers.ifEqual || (depth0 && depth0.ifEqual) || helpers.helperMissing).call(depth0 != null ? depth0 : (container.nullContext || {}),((stack1 = ((stack1 = ((stack1 = (depth0 != null ? depth0.results : depth0)) != null ? stack1.data : stack1)) != null ? stack1["0"] : stack1)) != null ? stack1.sp_isPatientEd : stack1),"true",{"name":"ifEqual","hash":{},"fn":container.program(2, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "");
8145},"2":function(container,depth0,helpers,partials,data) {
8146    var stack1;
8147
8148  return ((stack1 = (helpers.ifEqualsIgnoreCase || (depth0 && depth0.ifEqualsIgnoreCase) || helpers.helperMissing).call(depth0 != null ? depth0 : (container.nullContext || {}),((stack1 = (depth0 != null ? depth0.general : depth0)) != null ? stack1.query : stack1),((stack1 = ((stack1 = ((stack1 = (depth0 != null ? depth0.results : depth0)) != null ? stack1.data : stack1)) != null ? stack1["0"] : stack1)) != null ? stack1.title : stack1),{"name":"ifEqualsIgnoreCase","hash":{},"fn":container.program(3, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "");
8149},"3":function(container,depth0,helpers,partials,data) {
8150    var stack1, alias1=container.lambda, alias2=container.escapeExpression, alias3=depth0 != null ? depth0 : (container.nullContext || {}), alias4=helpers.helperMissing;
8151
8152  return "<div class=\"focus-box\">\n<div class=\"focus-box-inner\">\n<div class=\"focus-box-title\"><a href=\""
8153    + alias2(alias1(((stack1 = ((stack1 = ((stack1 = (depth0 != null ? depth0.results : depth0)) != null ? stack1.data : stack1)) != null ? stack1["0"] : stack1)) != null ? stack1.url : stack1), depth0))
8154    + "\">"
8155    + ((stack1 = alias1(((stack1 = ((stack1 = ((stack1 = (depth0 != null ? depth0.results : depth0)) != null ? stack1.data : stack1)) != null ? stack1["0"] : stack1)) != null ? stack1.title : stack1), depth0)) != null ? stack1 : "")
8156    + "</a></div>\n<div class=\"focus-box-text\">SEE ALSO</div>\n<div class=\"focus-box-links-container\">\n<div><a href=\""
8157    + alias2((helpers.adjustRelativeLink || (depth0 && depth0.adjustRelativeLink) || alias4).call(alias3,((stack1 = ((stack1 = ((stack1 = ((stack1 = ((stack1 = (depth0 != null ? depth0.results : depth0)) != null ? stack1.data : stack1)) != null ? stack1["0"] : stack1)) != null ? stack1.sp_el_links : stack1)) != null ? stack1["1"] : stack1)) != null ? stack1.value : stack1),{"name":"adjustRelativeLink","hash":{},"data":data}))
8158    + "\">"
8159    + ((stack1 = alias1(((stack1 = ((stack1 = ((stack1 = ((stack1 = ((stack1 = (depth0 != null ? depth0.results : depth0)) != null ? stack1.data : stack1)) != null ? stack1["0"] : stack1)) != null ? stack1.sp_el_links : stack1)) != null ? stack1["0"] : stack1)) != null ? stack1.value : stack1), depth0)) != null ? stack1 : "")
8160    + "</a></div>\n<div><a href=\""
8161    + alias2((helpers.adjustRelativeLink || (depth0 && depth0.adjustRelativeLink) || alias4).call(alias3,((stack1 = ((stack1 = ((stack1 = ((stack1 = ((stack1 = (depth0 != null ? depth0.results : depth0)) != null ? stack1.data : stack1)) != null ? stack1["0"] : stack1)) != null ? stack1.sp_el_links : stack1)) != null ? stack1["4"] : stack1)) != null ? stack1.value : stack1),{"name":"adjustRelativeLink","hash":{},"data":data}))
8162    + "\">"
8163    + ((stack1 = alias1(((stack1 = ((stack1 = ((stack1 = ((stack1 = ((stack1 = (depth0 != null ? depth0.results : depth0)) != null ? stack1.data : stack1)) != null ? stack1["0"] : stack1)) != null ? stack1.sp_el_links : stack1)) != null ? stack1["3"] : stack1)) != null ? stack1.value : stack1), depth0)) != null ? stack1 : "")
8164    + "</a></div>\n</div>\n</div>\n</div>\n";
8165},"compiler":[7,">= 4.0.0"],"main":function(container,depth0,helpers,partials,data) {
8166    var stack1;
8167
8168  return ((stack1 = (helpers.listNotEmpty || (depth0 && depth0.listNotEmpty) || helpers.helperMissing).call(
vendor: 5,117 bytes, lines 8168-8220
8168depth0 != null ? depth0 : (container.nullContext || {}),((stack1 = ((stack1 = ((stack1 = (depth0 != null ? depth0.results : depth0)) != null ? stack1.data : stack1)) != null ? stack1["0"] : stack1)) != null ? stack1.sp_el_links : stack1),{"name":"listNotEmpty","hash":{},"fn":container.program(1, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "");
8169},"useData":true}));
8170
8171Handlebars.registerPartial("mediaCarousel", Handlebars.template({"1":function(container,depth0,helpers,partials,data) {
8172    return "no-articles";
8173},"3":function(container,depth0,helpers,partials,data) {
8174    var stack1, helper, alias1=depth0 != null ? depth0 : (container.nullContext || {}), alias2=helpers.helperMissing;
8175
8176  return "<div class=\"slide\">\n<a href=\""
8177    + ((stack1 = ((helper = (helper = helpers.url || (depth0 != null ? depth0.url : depth0)) != null ? helper : alias2),(typeof helper === "function" ? helper.call(alias1,{"name":"url","hash":{},"data":data}) : helper))) != null ? stack1 : "")
8178    + "\">\n<div class='image-article' style=\"background-image:url('"
8179    + ((stack1 = (helpers.imageLinkProcessor || (depth0 && depth0.imageLinkProcessor) || alias2).call(alias1,(depth0 != null ? depth0.imageUrl : depth0),{"name":"imageLinkProcessor","hash":{},"data":data})) != null ? stack1 : "")
8180    + "')\"></div>\n"
8181    + ((stack1 = (helpers.ifEqual || (depth0 && depth0.ifEqual) || alias2).call(alias1,(depth0 != null ? depth0.mediaType : depth0),"video",{"name":"ifEqual","hash":{},"fn":container.program(4, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
8182    + "</a>\n</div>\n";
8183},"4":function(container,depth0,helpers,partials,data) {
8184    return "<div class=\"video-icon\"/>\n";
8185},"6":function(container,depth0,helpers,partials,data,blockParams,depths) {
8186    var stack1;
8187
8188  return ((stack1 = helpers.each.call(depth0 != null ? depth0 : (container.nullContext || {}),(depth0 != null ? depth0.articles : depth0),{"name":"each","hash":{},"fn":container.program(7, data, 0, blockParams, depths),"inverse":container.noop,"data":data})) != null ? stack1 : "");
8189},"7":function(container,depth0,helpers,partials,data,blockParams,depths) {
8190    var stack1, alias1=depth0 != null ? depth0 : (container.nullContext || {}), alias2=helpers.helperMissing;
8191
8192  return "<a href=\""
8193    + ((stack1 = container.lambda((depths[1] != null ? depths[1].url : depths[1]), depth0)) != null ? stack1 : "")
8194    + "\">\n<div class=\"slide"
8195    + ((stack1 = (helpers.ifNotEqual || (depth0 && depth0.ifNotEqual) || alias2).call(alias1,(data && data.index),0,{"name":"ifNotEqual","hash":{},"fn":container.program(8, data, 0, blockParams, depths),"inverse":container.noop,"data":data})) != null ? stack1 : "")
8196    + "\">\n<div class='image-article' style=\"background-image:url('"
8197    + ((stack1 = (helpers.imageLinkProcessor || (depth0 && depth0.imageLinkProcessor) || alias2).call(alias1,(depth0 != null ? depth0.imageUrl : depth0),{"name":"imageLinkProcessor","hash":{},"data":data})) != null ? stack1 : "")
8198    + "')\"></div>\n"
8199    + ((stack1 = (helpers.ifEqual || (depth0 && depth0.ifEqual) || alias2).call(alias1,(depth0 != null ? depth0.mediaType : depth0),"video",{"name":"ifEqual","hash":{},"fn":container.program(4, data, 0, blockParams, depths),"inverse":container.noop,"data":data})) != null ? stack1 : "")
8200    + "</div>\n</a>\n";
8201},"8":function(container,depth0,helpers,partials,data) {
8202    return " right";
8203},"10":function(container,depth0,helpers,partials,data) {
8204    return "<div class=\"left paddle disabled\"/>\n<div class=\"right paddle\"/>\n";
8205},"compiler":[7,">= 4.0.0"],"main":function(container,depth0,helpers,partials,data,blockParams,depths) {
8206    var stack1, alias1=depth0 != null ? depth0 : (container.nullContext || {}), alias2=helpers.helperMissing;
8207
8208  return "<div class=\"media-carousel "
8209    + ((stack1 = (helpers.ifArrayIsEmpty || (depth0 && depth0.ifArrayIsEmpty) || alias2).call(alias1,(depth0 != null ? depth0.articles : depth0),{"name":"ifArrayIsEmpty","hash":{},"fn":container.program(1, data, 0, blockParams, depths),"inverse":container.noop,"data":data})) != null ? stack1 : "")
8210    + "\">\n<div class=\"slides\" data-active-slide=\"0\">\n"
8211    + ((stack1 = (helpers.ifArrayIsEmpty || (depth0 && depth0.ifArrayIsEmpty) || alias2).call(alias1,(depth0 != null ? depth0.articles : depth0),{"name":"ifArrayIsEmpty","hash":{},"fn":container.program(3, data, 0, blockParams, depths),"inverse":container.program(6, data, 0, blockParams, depths),"data":data})) != null ? stack1 : "")
8212    + "</div>\n"
8213    + ((stack1 = (helpers.listNotEmpty || (depth0 && depth0.listNotEmpty) || alias2).call(alias1,(depth0 != null ? depth0.articles : depth0),{"name":"listNotEmpty","hash":{},"fn":container.program(10, data, 0, blockParams, depths),"inverse":container.noop,"data":data})) != null ? stack1 : "")
8214    + "</div>\n";
8215},"useData":true,"useDepths":true}));
8216
8217Handlebars.registerPartial("nonED", Handlebars.template({"1":function(container,depth0,helpers,partials,data) {
8218    var stack1;
8219
8220  return ((stack1 = (helpers.ifEqual || (depth0 && depth0.ifEqual) || helpers.helperMissing).call(
8220depth0 != null ? depth0 : (container.nullContext || {}),(depth0 != null ? depth0.hasMakeAnAppointment : depth0),"true",{"name":"ifEqual","hash":{},"fn":container.program(2, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "");
8221},"2":function(container,depth0,helpers,partials,data) {
8222    return "<div class=\"make-appointment-btn-wrapper\">\n<a href=\""
8223    + container.escapeExpression((helpers.buildClinicMakeApptModalLink || (depth0 && depth0.buildClinicMakeApptModalLink) || helpers.helperMissing).call(depth0 != null ? depth0 : (container.nullContext || {}),(depth0 != null ? depth0.url : depth0),{"name":"buildClinicMakeApptModalLink","hash":{},"data":data}))
8224    + "\" class=\"make-appointment-btn open-modal\" data-modalcontainer=\".make-an-appt\">MAKE AN APPOINTMENT</a>\n</div>\n";
8225},"compiler":[7,">= 4.0.0"],"main":function(container,depth0,helpers,partials,data) {
8226    var stack1;
8227
8228  return ((stack1 = (helpers.ifNotContains || (depth0 && depth0.ifNotContains) || helpers.helperMissing).call(depth0 != null ? depth0 : (container.nullContext || {}),(depth0 != null ? depth0.title : depth0),"Emergency Department",{"name":"ifNotContains","hash":{},"fn":container.program(1, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "");
8229},"useData":true}));
8230
8231Handlebars.registerPartial("subsection", Handlebars.template({"compiler":[7,">= 4.0.0"],"main":function(container,depth0,helpers,partials,data) {
8232    var stack1;
8233
8234  return "<div class=\"sub-section\">\n"
8235    + ((stack1 = container.invokePartial(partials.subsectionHeader,depth0,{"name":"subsectionHeader","data":data,"helpers":helpers,"partials":partials,"decorators":container.decorators})) != null ? stack1 : "")
8236    + "<div class=\"sub-section-content\">\n"
8237    + ((stack1 = container.invokePartial(partials.columns,depth0,{"name":"columns","data":data,"helpers":helpers,"partials":partials,"decorators":container.decorators})) != null ? stack1 : "")
8238    + ((stack1 = container.invokePartial(partials.updateResults,depth0,{"name":"updateResults","data":data,"helpers":helpers,"partials":partials,"decorators":container.decorators})) != null ? stack1 : "")
8239    + "</div>\n</div>\n";
8240},"usePartial":true,"useData":true}));
8241
8242Handlebars.registerPartial("subsectionHeader", Handlebars.template({"compiler":[7,">= 4.0.0"],"main":function(container,depth0,helpers,partials,data) {
8243    var helper, alias1=depth0 != null ? depth0 : (container.nullContext || {}), alias2=helpers.helperMissing, alias3="function", alias4=container.escapeExpression;
8244
8245  return "<a href=\"#\" class=\"sub-section-header\">\n"
8246    + alias4(((helper = (helper = helpers.subsectionHeader || (depth0 != null ? depth0.subsectionHeader : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"subsectionHeader","hash":{},"data":data}) : helper)))
8247    + "\n<span class=\"toggle\">"
8248    + alias4(((helper = (helper = helpers.plusMinus || (depth0 != null ? depth0.plusMinus : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"plusMinus","hash":{},"data":data}) : helper)))
8249    + "</span>\n<span class=\"count\"></span>\n</a>\n";
8250},"useData":true}));
8251
8252Handlebars.registerPartial("trials-filter-rail-template", Handlebars.template({"1":function(container,depth0,helpers,partials,data) {
8253    var stack1;
8254
8255  return "<div class=\"search-results-filters trials-filter-rail\">\n<div class=\"refine-results filter-title refine-title\">REFINE BY</div>\n<a href=\"/content/shc/en-tools/directory-filters/directory-info/clinical-trials.html\" class='info-icon desktop-icon open-modal' data-modalcontainer=\".info-section-template\" data=\"\"></a>\n<div class=\"refine-box\">\n<div class=\"refine-title refine-title-large\">REFINE BY</div>\n<div class=\"refine-title refine-title-mobile\">REFINE BY ("
8256    + container.escapeExpression((helpers.formatNumber || (depth0 && depth0.formatNumber) || helpers.helperMissing).call(depth0 != null ? depth0 : (container.nullContext || {}),((stack1 = (depth0 != null ? depth0.general : depth0)) != null ? stack1.total : stack1),{"name":"formatNumber","hash":{},"data":data}))
8257    + ")</div>\n<div class=\"refine-arrow\">\n<span>&nbsp;</span>\n</div>\n</div>\n<div class=\"reset-filter desktop\"><a>Reset Filters</a></div>\n<div class=\"mobile-filter-section-border\">\n<div class=\"mobile-info-container\">\n<a href=\"/content/shc/en-tools/directory-filters/directory-info/clinical-trials.html\" class='open-modal' data-modalcontainer=\".info-section-template\" data=\"\">\n<div class=\"info-icon mobile-icon\">More about these options</div>\n</a>\n</div>\n<div class=\"reset-filter mobile\"><a>Reset Filters</a></div>\n<div id=\"trials-condition-filter-target\"></div>\n<div id=\"trials-id-filter-target\"></div>\n<div id=\"trials-recruiting-filter-target\"></div>\n<div class=\"apply-filter\">APPLY FILTERS</div>\n</div>\n</div>\n";
8258},"3":function(container,depth0,helpers,partials,data) {
8259    return "<div class=\"filter-rails-spacer\">\n&nbsp;\n</div>\n";
8260},"compiler":[7,">= 4.0.0"],"main":function(container,depth0,helpers,partials,data) {
8261    var stack1, helper, options, buffer = "";
8262
8263  stack1 = ((helper = (helper = helpers.isNotPaginationClick || (depth0 != null ? depth0.isNotPaginationClick : depth0)) != null ? helper : helpers.helperMissing),(options={"name":"isNotPaginationClick","hash":{},"fn":container.program(1, data, 0),"inverse":container.program(3, data, 0),"data":data}),(typeof helper === "function" ? helper.call(depth0 != null ? depth0 : (container.nullContext || {}),options) : helper));
8264  if (!helpers.isNotPaginationClick) { stack1 = helpers.blockHelperMissing.call(depth0,stack1,options)}
8265  if (stack1 != null) { buffer += stack1; }
8266  return buffer;
8267},"useData":true}));
8268
8269Handlebars.registerPartial("updateResults", Handlebars.template({"compiler":[7,">= 4.0.0"],"main":function(container,depth0,helpers,partials,data) {
8270    return "<div class=\"update\">\n<button href=\"#\" class=\"update-btn\">Update Results</button>\n</div>\n";
8271},"useData":true}));
8272
8273this["JST"]["handlebars/article-handlebars.hbs"] = Handlebars.template({"1":function(container,depth0,helpers,partials,data) {
8274    return "Story";
8275},"3":function(container,depth0,helpers,partials,data) {
8276    return "Stories";
8277},"5":function(container,depth0,helpers,partials,data) {
8278    var stack1, alias1=depth0 != null ? depth0 : (container.nullContext || {}), alias2=helpers.helperMissing;
8279
8280  return ((stack1 = (helpers.ifLessThan || (depth0 && depth0.ifLessThan) || alias2).call(alias1,(data && data.index),"4",{"name":"ifLessThan","hash":{},"fn":container.program(6, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
8281    + ((stack1 = (helpers.ifGreaterThan || (depth0 && depth0.ifGreaterThan) || alias2).call(alias1,(data && data.index),"3",{"name":"ifGreaterThan","hash":{},"fn":container.program(11, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "");
8282},"6":function(container,depth0,helpers,partials,data) {
8283    var stack1, helper, alias1=depth0 != null ? depth0 : (container.nullContext || {}), alias2=helpers.helperMissing, alias3="function", alias4=container.escapeExpression;
8284
8285  return "<article class=\"col-sm-3\">\n<div class=\"row featured-stories\">\n<div class=\"image-wrapper col-xs-4 col-sm-12 rectangleThumbnail\">\n<span><img src=\""
8286    + alias4(((helper = (helper = helpers.rectangleThumbnail || (depth0 != null ? depth0.rectangleThumbnail : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"rectangleThumbnail","hash":{},"data":data}) : helper)))
8287    + ((stack1 = (helpers.ifNotContains || (depth0 && depth0.ifNotContains) || alias2).call(alias1,(depth0 != null ? depth0.rectangleThumbnail : depth0),"http",{"name":"ifNotContains","hash":{},"fn":container.program(7, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
8288    + "\" alt=\""
8289    + alias4(((helper = (helper = helpers.altText || (depth0 != null ? depth0.altText : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"altText","hash":{},"data":data}) : helper)))
8290    + "\" class=\""
8291    + alias4(((helper = (helper = helpers.hasVideo || (depth0 != null ? depth0.hasVideo : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"hasVideo","hash":{},"data":data}) : helper)))
8292    + "\"></span>\n<a href=\""
8293    + alias4(((helper = (helper = helpers.path || (depth0 != null ? depth0.path : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"path","hash":{},"data":data}) : helper)))
8294    + ".html\" class=\"presentation\" data-presentation-container=\".article-presentation\">\n"
8295    + ((stack1 = (helpers.ifEqual || (depth0 && depth0.ifEqual) || alias2).call(alias1,(depth0 != null ? depth0.hasVideo : depth0),"video",{"name":"ifEqual","hash":{},"fn":container.program(9, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
8296    + "\n</a>\n</div>\n<div class=\"stanford-now-articles-content col-xs-8 col-sm-12\">\n<a href=\""
8297    + alias4(((helper = (helper = helpers.path || (depth0 != null ? depth0.path : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"path","hash":{},"data":data}) : helper)))
8298    + ".html\" class=\"presentation\" data-presentation-container=\".article-presentation\">"
8299    + ((stack1 = ((helper = (helper = helpers.title || (depth0 != null ? depth0.title : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"title","hash":{},"data":data}) : helper))) != null ? stack1 : "")
8300    + "</a>\n</div>\n</div>\n</article>\n";
8301},"7":function(container,depth0,helpers,partials,data) {
8302    return ".transform/221x221/q82/image.png";
8303},"9":function(container,depth0,helpers,partials,data) {
8304    return "<span class=\"play-btn\"></span>";
8305},"11":function(container,depth0,helpers,partials,data) {
8306    var stack1, helper, alias1=depth0 != null ? depth0 : (container.nullContext || {}), alias2=helpers.helperMissing, alias3="function", alias4=container.escapeExpression;
8307
8308  return ((stack1 = (helpers.ifEqual || (depth0 && depth0.ifEqual) || alias2).call(alias1,(data && data.index),"4",{"name":"ifEqual","hash":{},"fn":container.program(12, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
8309    + ((stack1 = (helpers.ifEven || (depth0 && depth0.ifEven) || alias2).call(alias1,(data && data.index),{"n
vendor: 11,733 bytes, lines 8309-8418
8309ame":"ifEven","hash":{},"fn":container.program(14, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
8310    + "<div class=\"col-md-6\">\n<article class=\"stanford-now-tabs-detail-container\">\n<div class=\"image-wrapper "
8311    + alias4(((helper = (helper = helpers.shape || (depth0 != null ? depth0.shape : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"shape","hash":{},"data":data}) : helper)))
8312    + " "
8313    + alias4(((helper = (helper = helpers.crop || (depth0 != null ? depth0.crop : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"crop","hash":{},"data":data}) : helper)))
8314    + "\">\n<span>\n<img src=\""
8315    + alias4(((helper = (helper = helpers.squareThumbnail || (depth0 != null ? depth0.squareThumbnail : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"squareThumbnail","hash":{},"data":data}) : helper)))
8316    + ((stack1 = (helpers.ifNotContains || (depth0 && depth0.ifNotContains) || alias2).call(alias1,(depth0 != null ? depth0.squareThumbnail : depth0),"http",{"name":"ifNotContains","hash":{},"fn":container.program(7, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
8317    + "\" alt=\""
8318    + alias4(((helper = (helper = helpers.altText || (depth0 != null ? depth0.altText : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"altText","hash":{},"data":data}) : helper)))
8319    + "\" class=\"hidden-xs "
8320    + alias4(((helper = (helper = helpers.hasVideo || (depth0 != null ? depth0.hasVideo : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"hasVideo","hash":{},"data":data}) : helper)))
8321    + "\">\n</span>\n<a href=\""
8322    + alias4(((helper = (helper = helpers.path || (depth0 != null ? depth0.path : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"path","hash":{},"data":data}) : helper)))
8323    + ".html\" class=\"presentation\" data-presentation-container=\".article-presentation\">\n"
8324    + ((stack1 = (helpers.ifEqual || (depth0 && depth0.ifEqual) || alias2).call(alias1,(depth0 != null ? depth0.hasVideo : depth0),"video",{"name":"ifEqual","hash":{},"fn":container.program(9, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
8325    + "\n</a>\n</div>\n<div class=\"stanford-now-tabs-detail\">\n<a href=\""
8326    + alias4(((helper = (helper = helpers.path || (depth0 != null ? depth0.path : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"path","hash":{},"data":data}) : helper)))
8327    + ".html\" class=\"presentation\" data-presentation-container=\".article-presentation\">"
8328    + ((stack1 = ((helper = (helper = helpers.title || (depth0 != null ? depth0.title : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"title","hash":{},"data":data}) : helper))) != null ? stack1 : "")
8329    + "</a>\n</div>\n</article>\n</div>\n";
8330},"12":function(container,depth0,helpers,partials,data) {
8331    return "</div>\n<div class=\"row\">\n";
8332},"14":function(container,depth0,helpers,partials,data) {
8333    var stack1;
8334
8335  return ((stack1 = (helpers.ifGreaterThan || (depth0 && depth0.ifGreaterThan) || helpers.helperMissing).call(depth0 != null ? depth0 : (container.nullContext || {}),(data && data.index),"3",{"name":"ifGreaterThan","hash":{},"fn":container.program(12, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "");
8336},"16":function(container,depth0,helpers,partials,data) {
8337    var stack1;
8338
8339  return ((stack1 = (helpers.ifEven || (depth0 && depth0.ifEven) || helpers.helperMissing).call(depth0 != null ? depth0 : (container.nullContext || {}),(depth0 != null ? depth0.results : depth0),{"name":"ifEven","hash":{},"fn":container.program(17, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "");
8340},"17":function(container,depth0,helpers,partials,data) {
8341    return "</div>\n";
8342},"compiler":[7,">= 4.0.0"],"main":function(container,depth0,helpers,partials,data) {
8343    var stack1, alias1=depth0 != null ? depth0 : (container.nullContext || {}), alias2=helpers.helperMissing;
8344
8345  return "<div class=\"row stanford-now-articles\">\n<div class=\"col-md-12\">\n<div class=\"row stories-found\">\n<h2>"
8346    + container.escapeExpression(container.lambda((depth0 != null ? depth0.results : depth0), depth0))
8347    + " "
8348    + ((stack1 = (helpers.ifEqual || (depth0 && depth0.ifEqual) || alias2).call(alias1,(depth0 != null ? depth0.results : depth0),"1",{"name":"ifEqual","hash":{},"fn":container.program(1, data, 0),"inverse":container.program(3, data, 0),"data":data})) != null ? stack1 : "")
8349    + " Found</h2>\n</div>\n</div>\n"
8350    + ((stack1 = helpers.each.call(alias1,(depth0 != null ? depth0.articles : depth0),{"name":"each","hash":{},"fn":container.program(5, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
8351    + ((stack1 = (helpers.ifGreaterThan || (depth0 && depth0.ifGreaterThan) || alias2).call(alias1,((stack1 = (depth0 != null ? depth0.articles : depth0)) != null ? stack1.length : stack1),"4",{"name":"ifGreaterThan","hash":{},"fn":container.program(16, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
8352    + "</div>\n";
8353},"useData":true});
8354
8355this["JST"]["handlebars/caremap.hbs"] = Handlebars.template({"compiler":[7,">= 4.0.0"],"main":function(container,depth0,helpers,partials,data) {
8356    var helper, alias1=depth0 != null ? depth0 : (container.nullContext || {}), alias2=helpers.helperMissing, alias3="function", alias4=container.escapeExpression;
8357
8358  return "<h2>"
8359    + alias4(((helper = (helper = helpers.heading || (depth0 != null ? depth0.heading : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"heading","hash":{},"data":data}) : helper)))
8360    + "</h2>\n<p class=\"all-caps\">"
8361    + alias4(((helper = (helper = helpers.caption || (depth0 != null ? depth0.caption : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"caption","hash":{},"data":data}) : helper)))
8362    + "</p>\n<div id=\"shca-map\">\n</div>\n";
8363},"useData":true});
8364
8365this["JST"]["handlebars/dropdownPredictiveClinicTemplate.hbs"] = Handlebars.template({"1":function(container,depth0,helpers,partials,data) {
8366    var stack1, alias1=depth0 != null ? depth0 : (container.nullContext || {});
8367
8368  return container.escapeExpression((helpers.setPredictiveTerm || (depth0 && depth0.setPredictiveTerm) || helpers.helperMissing).call(alias1,depth0,{"name":"setPredictiveTerm","hash":{},"data":data}))
8369    + "\n<div id=\"search-results\">\n"
8370    + ((stack1 = helpers.each.call(alias1,(depth0 != null ? depth0.categories : depth0),{"name":"each","hash":{},"fn":container.program(2, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
8371    + "</div>\n";
8372},"2":function(container,depth0,helpers,partials,data) {
8373    var stack1;
8374
8375  return ((stack1 = (helpers.ifNotEmpty || (depth0 && depth0.ifNotEmpty) || helpers.helperMissing).call(depth0 != null ? depth0 : (container.nullContext || {}),(depth0 != null ? depth0.data : depth0),{"name":"ifNotEmpty","hash":{},"fn":container.program(3, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "");
8376},"3":function(container,depth0,helpers,partials,data) {
8377    var stack1, alias1=depth0 != null ? depth0 : (container.nullContext || {}), alias2=helpers.helperMissing;
8378
8379  return ((stack1 = (helpers.showPredictiveSections || (depth0 && depth0.showPredictiveSections) || alias2).call(alias1,depth0,"specialty",{"name":"showPredictiveSections","hash":{},"fn":container.program(4, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
8380    + "<div class = \"search-results-section\">\n<h2 class=\"search-result-heading\">Stanford Clinics</h2>\n"
8381    + ((stack1 = helpers.each.call(alias1,(depth0 != null ? depth0.data : depth0),{"name":"each","hash":{},"fn":container.program(8, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
8382    + ((stack1 = (helpers.ifGreaterThan || (depth0 && depth0.ifGreaterThan) || alias2).call(alias1,(depth0 != null ? depth0.count : depth0),((stack1 = (depth0 != null ? depth0.data : depth0)) != null ? stack1.length : stack1),{"name":"ifGreaterThan","hash":{},"fn":container.program(12, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
8383    + "</div>\n</div>\n";
8384},"4":function(container,depth0,helpers,partials,data) {
8385    var stack1;
8386
8387  return "<div class = \"search-results-section predictive-clinic-result\">\n<h2 class=\"search-result-heading\">Specialty</h2>\n"
8388    + ((stack1 = helpers.each.call(depth0 != null ? depth0 : (container.nullContext || {}),(depth0 != null ? depth0.specialty : depth0),{"name":"each","hash":{},"fn":container.program(5, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
8389    + "\n</div>\n";
8390},"5":function(container,depth0,helpers,partials,data) {
8391    var stack1;
8392
8393  return ((stack1 = (helpers.ifLessThan || (depth0 && depth0.ifLessThan) || helpers.helperMissing).call(depth0 != null ? depth0 : (container.nullContext || {}),(data && data.index),3,{"name":"ifLessThan","hash":{},"fn":container.program(6, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "");
8394},"6":function(container,depth0,helpers,partials,data) {
8395    var alias1=container.escapeExpression;
8396
8397  return "<div class=\"link-item predictive-clinic-clinic\">\n<a href=\"/content/shc/en/search-results.clinics.html/"
8398    + alias1((helpers.encodeString || (depth0 && depth0.encodeString) || helpers.helperMissing).call(depth0 != null ? depth0 : (container.nullContext || {}),(depth0 != null ? depth0.value : depth0),{"name":"encodeString","hash":{},"data":data}))
8399    + "?src=pred\" class=\"predictive-clinic-result\">\n"
8400    + alias1(container.lambda((depth0 != null ? depth0.value : depth0), depth0))
8401    + "\n</a>\n</div>\n";
8402},"8":function(container,depth0,helpers,partials,data) {
8403    var stack1;
8404
8405  return ((stack1 = (helpers.ifLessThan || (depth0 && depth0.ifLessThan) || helpers.helperMissing).call(depth0 != null ? depth0 : (container.nullContext || {}),(data && data.index),3,{"name":"ifLessThan","hash":{},"fn":container.program(9, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "");
8406},"9":function(container,depth0,helpers,partials,data) {
8407    var stack1, helper, alias1=depth0 != null ? depth0 : (container.nullContext || {}), alias2=helpers.helperMissing, alias3="function";
8408
8409  return "<div class=\"link-item predictive-clinic-result\">\n<a href=\""
8410    + ((stack1 = ((helper = (helper = helpers.url || (depth0 != null ? depth0.url : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"url","hash":{},"data":data}) : helper))) != null ? stack1 : "")
8411    + "\" class=\"predictive-clinic-result\">\n"
8412    + ((stack1 = ((helper = (helper = helpers.title || (depth0 != null ? depth0.title : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"title","hash":{},"data":data}) : helper))) != null ? stack1 : "")
8413    + ((stack1 = helpers.unless.call(alias1,(depth0 != null ? depth0.title : depth0),{"name":"unless","hash":{},"fn":container.program(10, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
8414    + "\n</a>\n</div>\n";
8415},"10":function(container,depth0,helpers,partials,data) {
8416    var stack1, helper;
8417
8418  return ((stack1 = ((helper = (helper = helpers.displayName || (depth0 != null ? depth0.displayName : depth0)) != null ? helper : helpers.helperMissing),(typeof helper === "function" ? helper.call(depth0 != null ? depth0 : (container.nullContext || {}
8418),{"name":"displayName","hash":{},"data":data}) : helper))) != null ? stack1 : "");
8419},"12":function(container,depth0,helpers,partials,data) {
8420    return "<div class=\"view-more predictive-clinic-result\">\n<a href=\""
8421    + container.escapeExpression((helpers.getClinicPredictiveViewAllLink || (depth0 && depth0.getClinicPredictiveViewAllLink) || helpers.helperMissing).call(depth0 != null ? depth0 : (container.nullContext || {}),depth0,{"name":"getClinicPredictiveViewAllLink","hash":{},"data":data}))
8422    + "\" class=\"view-link predictive-clinic-result\">View All Stanford Clinics</a>\n</div>\n";
8423},"compiler":[7,">= 4.0.0"],"main":function(container,depth0,helpers,partials,data) {
8424    var stack1;
8425
8426  return ((stack1 = (helpers.ifNotEmpty || (depth0 && depth0.ifNotEmpty) || helpers.helperMissing).call(depth0 != null ? depth0 : (container.nullContext || {}),(depth0 != null ? depth0.categories : depth0),{"name":"ifNotEmpty","hash":{},"fn":container.program(1, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "");
8427},"useData":true});
8428
8429this["JST"]["handlebars/dropdownPredictiveDoctorTemplate.hbs"] = Handlebars.template({"1":function(container,depth0,helpers,partials,data) {
8430    var stack1, alias1=depth0 != null ? depth0 : (container.nullContext || {});
8431
8432  return container.escapeExpression((helpers.setPredictiveTerm || (depth0 && depth0.setPredictiveTerm) || helpers.helperMissing).call(alias1,depth0,{"name":"setPredictiveTerm","hash":{},"data":data}))
8433    + "\n<div id=\"search-results\">\n"
8434    + ((stack1 = helpers.each.call(alias1,(depth0 != null ? depth0.categories : depth0),{"name":"each","hash":{},"fn":container.program(2, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
8435    + "</div>\n";
8436},"2":function(container,depth0,helpers,partials,data) {
8437    var stack1;
8438
8439  return ((stack1 = (helpers.ifNotEmpty || (depth0 && depth0.ifNotEmpty) || helpers.helperMissing).call(depth0 != null ? depth0 : (container.nullContext || {}),(depth0 != null ? depth0.data : depth0),{"name":"ifNotEmpty","hash":{},"fn":container.program(3, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "");
8440},"3":function(container,depth0,helpers,partials,data) {
8441    var stack1, alias1=depth0 != null ? depth0 : (container.nullContext || {}), alias2=helpers.helperMissing;
8442
8443  return "<div class = \"search-results-section\">\n<h2 class=\"search-result-heading\">Specialists</h2>\n"
8444    + ((stack1 = helpers.each.call(alias1,(depth0 != null ? depth0.data : depth0),{"name":"each","hash":{},"fn":container.program(4, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
8445    + ((stack1 = (helpers.ifGreaterThan || (depth0 && depth0.ifGreaterThan) || alias2).call(alias1,(depth0 != null ? depth0.count : depth0),((stack1 = (depth0 != null ? depth0.data : depth0)) != null ? stack1.length : stack1),{"name":"ifGreaterThan","hash":{},"fn":container.program(8, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
8446    + "</div>\n"
8447    + ((stack1 = (helpers.showPredictiveSections || (depth0 && depth0.showPredictiveSections) || alias2).call(alias1,depth0,"doctorTitles",{"name":"showPredictiveSections","hash":{},"fn":container.program(10, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
8448    + ((stack1 = (helpers.showPredictiveSections || (depth0 && depth0.showPredictiveSections) || alias2).call(alias1,depth0,"doctorMedicalCategories",{"name":"showPredictiveSections","hash":{},"fn":container.program(14, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
8449    + "</div>\n";
8450},"4":function(container,depth0,helpers,partials,data) {
8451    var stack1;
8452
8453  return ((stack1 = (helpers.ifLessThan || (depth0 && depth0.ifLessThan) || helpers.helperMissing).call(depth0 != null ? depth0 : (container.nullContext || {}),(data && data.index),3,{"name":"ifLessThan","hash":{},"fn":container.program(5, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "");
8454},"5":function(container,depth0,helpers,partials,data) {
8455    var stack1, helper, alias1=depth0 != null ? depth0 : (container.nullContext || {}), alias2=helpers.helperMissing, alias3="function";
8456
8457  return "<div class=\"link-item predictive-doctor-result\">\n<a href=\""
8458    + ((stack1 = ((helper = (helper = helpers.url || (depth0 != null ? depth0.url : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"url","hash":{},"data":data}) : helper))) != null ? stack1 : "")
8459    + "\" class=\"predictive-doctor-result\">\n"
8460    + ((stack1 = ((helper = (helper = helpers.title || (depth0 != null ? depth0.title : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"title","hash":{},"data":data}) : helper))) != null ? stack1 : "")
8461    + ((stack1 = helpers.unless.call(alias1,(depth0 != null ? depth0.title : depth0),{"name":"unless","hash":{},"fn":container.program(6, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
8462    + "\n"
8463    + ((stack1 = (helpers.getDoctorTitle || (depth0 && depth0.getDoctorTitle) || alias2).call(alias1,depth0,{"name":"getDoctorTitle","hash":{},"data":data})) != null ? stack1 : "")
8464    + "\n</a>\n</div>\n";
8465},"6":function(container,depth0,helpers,partials,data) {
8466    var stack1, helper;
8467
8468  return ((stack1 = ((helper = (helper = helpers.displayName || (depth0 != null ? depth0.displayName : depth0)) != null ? helper : helpers.helperMissing),(typeof helper === "function" ? helper.call(depth0 != null ? depth0 : (container.nullContext || {}
8468),{"name":"displayName","hash":{},"data":data}) : helper))) != null ? stack1 : "");
8469},"8":function(container,depth0,helpers,partials,data) {
8470    return "<div class=\"view-more predictive-doctor-result\">\n<a href=\""
8471    + container.escapeExpression((helpers.getDoctorPredictiveViewAllLink || (depth0 && depth0.getDoctorPredictiveViewAllLink) || helpers.helperMissing).call(depth0 != null ? depth0 : (container.nullContext || {}),depth0,{"name":"getDoctorPredictiveViewAllLink","hash":{},"data":data}))
8472    + "\" class=\"view-link predictive-doctor-result\">View All Specialists</a>\n</div>\n";
8473},"10":function(container,depth0,helpers,partials,data) {
8474    var stack1;
8475
8476  return "<div class = \"search-results-section predictive-doctor-result\">\n<h2 class=\"search-result-heading\">Provider Type</h2>\n"
8477    + ((stack1 = helpers.each.call(depth0 != null ? depth0 : (container.nullContext || {}),(depth0 != null ? depth0.doctorTitles : depth0),{"name":"each","hash":{},"fn":container.program(11, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
8478    + "\n</div>\n";
8479},"11":function(container,depth0,helpers,partials,data) {
8480    var stack1;
8481
8482  return ((stack1 = (helpers.ifLessThan || (depth0 && depth0.ifLessThan) || helpers.helperMissing).call(depth0 != null ? depth0 : (container.nullContext || {}),(data && data.index),3,{"name":"ifLessThan","hash":{},"fn":container.program(12, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "");
8483},"12":function(container,depth0,helpers,partials,data) {
8484    var alias1=container.escapeExpression;
8485
8486  return "<div class=\"link-item predictive-doctor-result-category\">\n<a href=\"/content/shc/en/search-results.doctors.html/"
8487    + alias1((helpers.encodeString || (depth0 && depth0.encodeString) || helpers.helperMissing).call(depth0 != null ? depth0 : (container.nullContext || {}),(depth0 != null ? depth0.value : depth0),{"name":"encodeString","hash":{},"data":data}))
8488    + "?src=pred\" class=\"predictive-doctor-result\">\n"
8489    + alias1(container.lambda((depth0 != null ? depth0.value : depth0), depth0))
8490    + "\n</a>\n</div>\n";
8491},"14":function(container,depth0,helpers,partials,data) {
8492    var stack1;
8493
8494  return "<div class = \"search-results-section predictive-doctor-result\">\n<h2 class=\"search-result-heading\">Categories and Specialties</h2>\n"
8495    + ((stack1 = helpers.each.call(depth0 != null ? depth0 : (container.nullContext || {}),(depth0 != null ? depth0.doctorMedicalCategories : depth0),{"name":"each","hash":{},"fn":container.program(11, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
8496    + "</div>\n";
8497},"compiler":[7,">= 4.0.0"],"main":function(container,depth0,helpers,partials,data) {
8498    var stack1;
8499
8500  return ((stack1 = (helpers.ifNotEmpty || (depth0 && depth0.ifNotEmpty) || helpers.helperMissing).call(depth0 != null ? depth0 : (container.nullContext || {}),(depth0 != null ? depth0.categories : depth0),{"name":"ifNotEmpty","hash":{},"fn":container.program(1, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "");
8501},"useData":true});
8502
8503this["JST"]["handlebars/dropdownPredictiveNewsroomTemplate.hbs"] = Handlebars.template({"1":function(container,depth0,helpers,partials,data,blockParams,depths) {
8504    var stack1;
8505
8506  return "<div id=\"search-results\">\n"
8507    + ((stack1 = helpers.each.call(depth0 != null ? depth0 : (container.nullContext || {}),depth0,{"name":"each","hash":{},"fn":container.program(2, data, 0, blockParams, depths),"inverse":container.noop,"data":data})) != null ? stack1 : "")
8508    + "</div>\n";
8509},"2":function(container,depth0,helpers,partials,data,blockParams,depths) {
8510    var stack1;
8511
8512  return ((stack1 = (helpers.ifLessThan || (depth0 && depth0.ifLessThan) || helpers.helperMissing).call(depth0 != null ? depth0 : (container.nullContext || {}),(data && data.index),"3",{"name":"ifLessThan","hash":{},"fn":container.program(3, data, 0, blockParams, depths),"inverse":container.noop,"data":data})) != null ? stack1 : "");
8513},"3":function(container,depth0,helpers,partials,data,blockParams,depths) {
8514    var stack1;
8515
8516  return ((stack1 = (helpers.showPredictiveSections || (depth0 && depth0.showPredictiveSections) || helpers.helperMissing).call(
8516depth0 != null ? depth0 : (container.nullContext || {}),depth0,"data",{"name":"showPredictiveSections","hash":{},"fn":container.program(4, data, 0, blockParams, depths),"inverse":container.noop,"data":data})) != null ? stack1 : "");
8517},"4":function(container,depth0,helpers,partials,data,blockParams,depths) {
8518    var stack1, alias1=depth0 != null ? depth0 : (container.nullContext || {});
8519
8520  return "<div class = \"search-results-section\">\n<h2 class=\"search-result-heading\">"
8521    + container.escapeExpression(container.lambda((depth0 != null ? depth0.heading : depth0), depth0))
8522    + "</h2>\n"
8523    + ((stack1 = helpers.each.call(alias1,(depth0 != null ? depth0.data : depth0),{"name":"each","hash":{},"fn":container.program(5, data, 0, blockParams, depths),"inverse":container.noop,"data":data})) != null ? stack1 : "")
8524    + ((stack1 = (helpers.ifGreaterThan || (depth0 && depth0.ifGreaterThan) || helpers.helperMissing).call(alias1,((stack1 = ((stack1 = (depth0 != null ? depth0.query : depth0)) != null ? stack1["0"] : stack1)) != null ? stack1.total : stack1),3,{"name":"ifGreaterThan","hash":{},"fn":container.program(8, data, 0, blockParams, depths),"inverse":container.noop,"data":data})) != null ? stack1 : "")
8525    + "</div>\n";
8526},"5":function(container,depth0,helpers,partials,data) {
8527    var stack1;
8528
8529  return ((stack1 = (helpers.ifLessThan || (depth0 && depth0.ifLessThan) || helpers.helperMissing).call(depth0 != null ? depth0 : (container.nullContext || {}),(data && data.index),3,{"name":"ifLessThan","hash":{},"fn":container.program(6, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "");
8530},"6":function(container,depth0,helpers,partials,data) {
8531    var stack1, helper, alias1=depth0 != null ? depth0 : (container.nullContext || {}), alias2=helpers.helperMissing;
8532
8533  return "<div class=\"link-item predictive-newsroom-result\">\n<a href=\""
8534    + ((stack1 = ((helper = (helper = helpers.url || (depth0 != null ? depth0.url : depth0)) != null ? helper : alias2),(typeof helper === "function" ? helper.call(alias1,{"name":"url","hash":{},"data":data}) : helper))) != null ? stack1 : "")
8535    + "\" class=\"predictive-newsroom-result\">\n"
8536    + ((stack1 = (helpers.textEllipsis || (depth0 && depth0.textEllipsis) || alias2).call(alias1,(depth0 != null ? depth0.title : depth0),80,50,0,{"name":"textEllipsis","hash":{},"data":data})) != null ? stack1 : "")
8537    + "\n</a>\n</div>\n";
8538},"8":function(container,depth0,helpers,partials,data,blockParams,depths) {
8539    var alias1=container.escapeExpression;
8540
8541  return "<div class=\"view-more predictive-newsroom-result\">\n<a href=\""
8542    + alias1((helpers.getNewsroomPredictiveViewAllLink || (depth0 && depth0.getNewsroomPredictiveViewAllLink) || helpers.helperMissing).call(depth0 != null ? depth0 : (container.nullContext || {}),(depths[1] != null ? depths[1].searchTerm : depths[1]),(depth0 != null ? depth0.collection : depth0),{"name":"getNewsroomPredictiveViewAllLink","hash":{},"data":data}))
8543    + "\" class=\"view-link predictive-newsroom-result\">View All "
8544    + alias1(container.lambda((depth0 != null ? depth0.heading : depth0), depth0))
8545    + "</a>\n</div>\n";
8546},"compiler":[7,">= 4.0.0"],"main":function(container,depth0,helpers,partials,data,blockParams,depths) {
8547    var stack1;
8548
8549  return ((stack1 = (helpers.ifNotEmpty || (depth0 && depth0.ifNotEmpty) || helpers.helperMissing).call(depth0 != null ? depth0 : (container.nullContext || {}),depth0,{"name":"ifNotEmpty","hash":{},"fn":container.program(1, data, 0, blockParams, depths),"inverse":container.noop,"data":data})) != null ? stack1 : "");
8550},"useData":true,"useDepths":true});
8551
8552this["JST"]["handlebars/dropdownPredictiveStanfordlab.hbs"] = Handlebars.template({"1":function(container,depth0,helpers,partials,data) {
8553    var stack1;
8554
8555  return "<div id=\"search-results\">\n"
8556    + ((stack1 = helpers.each.call(depth0 != null ? depth0 : (container.nullContext || {}),(depth0 != null ? depth0.categories : depth0),{"name":"each","hash":{},"fn":container.program(2, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
8557    + "</div>\n<a class='view-all' href='/content/stanfordlab/en/search-results.html/"
8558    + container.escapeExpression(container.lambda((depth0 != null ? depth0.searchTerm : depth0), depth0))
8559    + "?src=pred'>See All Results</a>\n";
8560},"2":function(container,depth0,helpers,partials,data) {
8561    var stack1;
8562
8563  return ((stack1 = (helpers.ifNotEmpty || (depth0 && depth0.ifNotEmpty) || helpers.helperMissing).call(
vendor: 5,397 bytes, lines 8563-8613
8563depth0 != null ? depth0 : (container.nullContext || {}),(depth0 != null ? depth0.data : depth0),{"name":"ifNotEmpty","hash":{},"fn":container.program(3, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "");
8564},"3":function(container,depth0,helpers,partials,data) {
8565    var stack1;
8566
8567  return ((stack1 = (helpers.ifGreaterThan || (depth0 && depth0.ifGreaterThan) || helpers.helperMissing).call(depth0 != null ? depth0 : (container.nullContext || {}),((stack1 = (depth0 != null ? depth0.data : depth0)) != null ? stack1.length : stack1),0,{"name":"ifGreaterThan","hash":{},"fn":container.program(4, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
8568    + "</div>\n";
8569},"4":function(container,depth0,helpers,partials,data) {
8570    var stack1;
8571
8572  return ((stack1 = (helpers.ifNotEqual || (depth0 && depth0.ifNotEqual) || helpers.helperMissing).call(depth0 != null ? depth0 : (container.nullContext || {}),(depth0 != null ? depth0.heading : depth0),"Suggested Searches",{"name":"ifNotEqual","hash":{},"fn":container.program(5, data, 0),"inverse":container.program(16, data, 0),"data":data})) != null ? stack1 : "");
8573},"5":function(container,depth0,helpers,partials,data) {
8574    var stack1, alias1=depth0 != null ? depth0 : (container.nullContext || {});
8575
8576  return "<div class = \"search-results-section"
8577    + ((stack1 = helpers["if"].call(alias1,((stack1 = (data && data.root)) && stack1.onlyCollection),{"name":"if","hash":{},"fn":container.program(6, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
8578    + "\">\n<h2 class=\"search-result-heading\">"
8579    + ((stack1 = container.lambda((depth0 != null ? depth0.heading : depth0), depth0)) != null ? stack1 : "")
8580    + "</h2>\n"
8581    + ((stack1 = helpers.each.call(alias1,(depth0 != null ? depth0.data : depth0),{"name":"each","hash":{},"fn":container.program(8, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
8582    + ((stack1 = (helpers.ifGreaterThan || (depth0 && depth0.ifGreaterThan) || helpers.helperMissing).call(alias1,(depth0 != null ? depth0.count : depth0),((stack1 = (depth0 != null ? depth0.data : depth0)) != null ? stack1.length : stack1),{"name":"ifGreaterThan","hash":{},"fn":container.program(11, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "");
8583},"6":function(container,depth0,helpers,partials,data) {
8584    return "-only";
8585},"8":function(container,depth0,helpers,partials,data) {
8586    var stack1, helper, alias1=depth0 != null ? depth0 : (container.nullContext || {}), alias2=helpers.helperMissing, alias3="function";
8587
8588  return "<div class=\"link-item\">\n<a href=\""
8589    + ((stack1 = ((helper = (helper = helpers.url || (depth0 != null ? depth0.url : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"url","hash":{},"data":data}) : helper))) != null ? stack1 : "")
8590    + "\" class=\""
8591    + ((stack1 = ((helper = (helper = helpers.exactMatch || (depth0 != null ? depth0.exactMatch : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"exactMatch","hash":{},"data":data}) : helper))) != null ? stack1 : "")
8592    + "\">"
8593    + ((stack1 = ((helper = (helper = helpers.title || (depth0 != null ? depth0.title : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"title","hash":{},"data":data}) : helper))) != null ? stack1 : "")
8594    + ((stack1 = helpers.unless.call(alias1,(depth0 != null ? depth0.title : depth0),{"name":"unless","hash":{},"fn":container.program(9, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
8595    + "</a>\n</div>\n";
8596},"9":function(container,depth0,helpers,partials,data) {
8597    var stack1, helper;
8598
8599  return ((stack1 = ((helper = (helper = helpers.displayName || (depth0 != null ? depth0.displayName : depth0)) != null ? helper : helpers.helperMissing),(typeof helper === "function" ? helper.call(depth0 != null ? depth0 : (container.nullContext || {}),{"name":"displayName","hash":{},"data":data}) : helper))) != null ? stack1 : "");
8600},"11":function(container,depth0,helpers,partials,data) {
8601    var stack1, alias1=depth0 != null ? depth0 : (container.nullContext || {}), alias2=helpers.helperMissing;
8602
8603  return "<div class=\"view-more\">\n"
8604    + ((stack1 = (helpers.ifEqual || (depth0 && depth0.ifEqual) || alias2).call(alias1,(depth0 != null ? depth0.type : depth0),"slab_test_details",{"name":"ifEqual","hash":{},"fn":container.program(12, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
8605    + ((stack1 = (helpers.ifNotEqual || (depth0 && depth0.ifNotEqual) || alias2).call(alias1,(depth0 != null ? depth0.type : depth0),"slab_test_details",{"name":"ifNotEqual","hash":{},"fn":container.program(14, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
8606    + "</div>\n";
8607},"12":function(container,depth0,helpers,partials,data) {
8608    var stack1, helper;
8609
8610  return "<a href=\"/content/stanfordlab/en/test-directory/search-results.html/"
8611    + ((stack1 = container.lambda(((stack1 = (data && data.root)) && stack1.searchTerm), depth0)) != null ? stack1 : "")
8612    + "\">\nView All "
8613    + ((stack1 = ((helper = (helper = helpers.heading || (depth0 != null ? depth0.heading : depth0)) != null ? helper : helpers.helperMissing),(typeof helper === "function" ? helper.call(depth0 != null ? depth0 : (container.nullContext || {}
8613),{"name":"heading","hash":{},"data":data}) : helper))) != null ? stack1 : "")
8614    + "</a>\n";
8615},"14":function(container,depth0,helpers,partials,data) {
8616    var stack1, helper;
8617
8618  return "<a href=\"/content/stanfordlab/en/search-results.html/"
8619    + ((stack1 = container.lambda(((stack1 = (data && data.root)) && stack1.searchTerm), depth0)) != null ? stack1 : "")
8620    + "\">\nView All "
8621    + ((stack1 = ((helper = (helper = helpers.heading || (depth0 != null ? depth0.heading : depth0)) != null ? helper : helpers.helperMissing),(typeof helper === "function" ? helper.call(depth0 != null ? depth0 : (container.nullContext || {}),{"name":"heading","hash":{},"data":data}) : helper))) != null ? stack1 : "")
8622    + "</a>\n";
8623},"16":function(container,depth0,helpers,partials,data) {
8624    var stack1;
8625
8626  return "<div id = \"search-suggestions\">\n<h2 class=\"search-result-heading suggested-searches-heading\">"
8627    + ((stack1 = container.lambda((depth0 != null ? depth0.heading : depth0), depth0)) != null ? stack1 : "")
8628    + "</h2>\n"
8629    + ((stack1 = helpers.each.call(depth0 != null ? depth0 : (container.nullContext || {}),(depth0 != null ? depth0.data : depth0),{"name":"each","hash":{},"fn":container.program(17, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "");
8630},"17":function(container,depth0,helpers,partials,data) {
8631    var alias1=container.escapeExpression;
8632
8633  return "<div class=\"suggestion link-item suggested-searches-item\">\n<a href=\"/content/stanfordlab/en/search-results.html/"
8634    + alias1((helpers.urlEncode || (depth0 && depth0.urlEncode) || helpers.helperMissing).call(depth0 != null ? depth0 : (container.nullContext || {}),depth0,{"name":"urlEncode","hash":{},"data":data}))
8635    + "\">\n<span class=\"icon\"></span>\n"
8636    + alias1(container.lambda(depth0, depth0))
8637    + "\n</a>\n</div>\n";
8638},"compiler":[7,">= 4.0.0"],"main":function(container,depth0,helpers,partials,data) {
8639    var stack1;
8640
8641  return ((stack1 = (helpers.ifNotEmpty || (depth0 && depth0.ifNotEmpty) || helpers.helperMissing).call(depth0 != null ? depth0 : (container.nullContext || {}),(depth0 != null ? depth0.categories : depth0),{"name":"ifNotEmpty","hash":{},"fn":container.program(1, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "");
8642},"useData":true});
8643
8644this["JST"]["handlebars/dropdownPredictiveTemplate.hbs"] = Handlebars.template({"1":function(container,depth0,helpers,partials,data,blockParams,depths) {
8645    var stack1;
8646
8647  return "<div id=\"search-results\">\n"
8648    + ((stack1 = helpers.each.call(depth0 != null ? depth0 : (container.nullContext || {}),(depth0 != null ? depth0.categories : depth0),{"name":"each","hash":{},"fn":container.program(2, data, 0, blockParams, depths),"inverse":container.noop,"data":data})) != null ? stack1 : "")
8649    + "</div>\n";
8650},"2":function(container,depth0,helpers,partials,data,blockParams,depths) {
8651    var stack1;
8652
8653  return ((stack1 = (helpers.ifNotEmpty || (depth0 && depth0.ifNotEmpty) || helpers.helperMissing).call(depth0 != null ? depth0 : (container.nullContext || {}),(depth0 != null ? depth0.data : depth0),{"name":"ifNotEmpty","hash":{},"fn":container.program(3, data, 0, blockParams, depths),"inverse":container.noop,"data":data})) != null ? stack1 : "");
8654},"3":function(container,depth0,helpers,partials,data,blockParams,depths) {
8655    var stack1;
8656
8657  return ((stack1 = (helpers.ifGreaterThan || (depth0 && depth0.ifGreaterThan) || helpers.helperMissing).call(depth0 != null ? depth0 : (container.nullContext || {}),((stack1 = (depth0 != null ? depth0.data : depth0)) != null ? stack1.length : stack1),0,{"name":"ifGreaterThan","hash":{},"fn":container.program(4, data, 0, blockParams, depths),"inverse":container.noop,"data":data})) != null ? stack1 : "")
8658    + "</div>\n";
8659},"4":function(container,depth0,helpers,partials,data,blockParams,depths) {
8660    var stack1;
8661
8662  return ((stack1 = (helpers.ifNotEqual || (depth0 && depth0.ifNotEqual) || helpers.helperMissing).call(depth0 != null ? depth0 : (container.nullContext || {}),(depth0 != null ? depth0.heading : depth0),"Suggested Searches",{"name":"ifNotEqual","hash":{},"fn":container.program(5, data, 0, blockParams, depths),"inverse":container.program(49, data, 0, blockParams, depths),"data":data})) != null ? stack1 : "");
8663},"5":function(container,depth0,helpers,partials,data,blockParams,depths) {
8664    var stack1, alias1=depth0 != null ? depth0 : (container.nullContext || {});
8665
8666  return "<div class = \"search-results-section"
8667    + ((stack1 = helpers["if"].call(alias1,((stack1 = (data && data.root)) && stack1.onlyCollection),{"name":"if","hash":{},"fn":container.program(6, data, 0, blockParams, depths),"inverse":container.noop,"data":data})) != null ? stack1 : "")
8668    + "\">\n<h2 class=\"search-result-heading\">"
8669    + ((stack1 = container.lambda((depth0 != null ? depth0.heading : depth0), depth0)) != null ? stack1 : "")
8670    + "</h2>\n"
8671    + ((stack1 = helpers.each.call(alias1,(depth0 != null ? depth0.data : depth0),{"name":"each","hash":{},"fn":container.program(8, data, 0, blockParams, depths),"inverse":container.noop,"data":data})) != null ? stack1 : "")
8672    + ((stack1 = (helpers.ifGreaterThan || (depth0 && depth0.ifGreaterThan) || helpers.helperMissing).call(alias1,(depth0 != null ? depth0.count : depth0),((stack1 = (depth0 != null ? depth0.data : depth0)) != null ? stack1.length : stack1),{"name":"ifGreaterThan","hash":{},"fn":container.program(18, data, 0, blockParams, depths),"inverse":container.noop,"data":data})) != null ? stack1 : "");
8673},"6":function(container,depth0,helpers,partials,data) {
8674    return "-only";
8675},"8":function(container,depth0,helpers,partials,data,blockParams,depths) {
8676    var stack1;
8677
8678  return ((stack1 = (helpers.ifEqual || (depth0 && depth0.ifEqual) || helpers.helperMissing).call(
vendor: 5,513 bytes, lines 8678-8729
8678depth0 != null ? depth0 : (container.nullContext || {}),(depths[1] != null ? depths[1].heading : depths[1]),"Newsroom",{"name":"ifEqual","hash":{},"fn":container.program(9, data, 0, blockParams, depths),"inverse":container.program(13, data, 0, blockParams, depths),"data":data})) != null ? stack1 : "");
8679},"9":function(container,depth0,helpers,partials,data) {
8680    var stack1;
8681
8682  return ((stack1 = (helpers.ifLessThan || (depth0 && depth0.ifLessThan) || helpers.helperMissing).call(depth0 != null ? depth0 : (container.nullContext || {}),(data && data.index),"3",{"name":"ifLessThan","hash":{},"fn":container.program(10, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "");
8683},"10":function(container,depth0,helpers,partials,data) {
8684    var stack1, helper, alias1=depth0 != null ? depth0 : (container.nullContext || {}), alias2=helpers.helperMissing, alias3="function";
8685
8686  return "<div class=\"link-item\">\n<a href=\""
8687    + ((stack1 = ((helper = (helper = helpers.url || (depth0 != null ? depth0.url : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"url","hash":{},"data":data}) : helper))) != null ? stack1 : "")
8688    + "\" class=\""
8689    + ((stack1 = ((helper = (helper = helpers.exactMatch || (depth0 != null ? depth0.exactMatch : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"exactMatch","hash":{},"data":data}) : helper))) != null ? stack1 : "")
8690    + " newsroom-pred-result\">"
8691    + ((stack1 = (helpers.textEllipsis || (depth0 && depth0.textEllipsis) || alias2).call(alias1,(depth0 != null ? depth0.title : depth0),80,50,0,{"name":"textEllipsis","hash":{},"data":data})) != null ? stack1 : "")
8692    + ((stack1 = helpers.unless.call(alias1,(depth0 != null ? depth0.title : depth0),{"name":"unless","hash":{},"fn":container.program(11, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
8693    + "</a>\n</div>\n";
8694},"11":function(container,depth0,helpers,partials,data) {
8695    var stack1, helper;
8696
8697  return ((stack1 = ((helper = (helper = helpers.displayName || (depth0 != null ? depth0.displayName : depth0)) != null ? helper : helpers.helperMissing),(typeof helper === "function" ? helper.call(depth0 != null ? depth0 : (container.nullContext || {}),{"name":"displayName","hash":{},"data":data}) : helper))) != null ? stack1 : "");
8698},"13":function(container,depth0,helpers,partials,data) {
8699    var stack1, alias1=depth0 != null ? depth0 : (container.nullContext || {});
8700
8701  return "<div class=\"link-item\">\n"
8702    + ((stack1 = helpers["if"].call(alias1,(helpers.isValleycare || (depth0 && depth0.isValleycare) || helpers.helperMissing).call(alias1,{"name":"isValleycare","hash":{},"data":data}),{"name":"if","hash":{},"fn":container.program(14, data, 0),"inverse":container.program(16, data, 0),"data":data})) != null ? stack1 : "")
8703    + "</div>\n";
8704},"14":function(container,depth0,helpers,partials,data) {
8705    var stack1, helper, alias1=depth0 != null ? depth0 : (container.nullContext || {}), alias2=helpers.helperMissing, alias3="function";
8706
8707  return "<a href=\""
8708    + ((stack1 = ((helper = (helper = helpers.vc_url || (depth0 != null ? depth0.vc_url : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"vc_url","hash":{},"data":data}) : helper))) != null ? stack1 : "")
8709    + "\" class=\""
8710    + ((stack1 = ((helper = (helper = helpers.exactMatch || (depth0 != null ? depth0.exactMatch : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"exactMatch","hash":{},"data":data}) : helper))) != null ? stack1 : "")
8711    + "\">"
8712    + ((stack1 = ((helper = (helper = helpers.title || (depth0 != null ? depth0.title : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"title","hash":{},"data":data}) : helper))) != null ? stack1 : "")
8713    + ((stack1 = helpers.unless.call(alias1,(depth0 != null ? depth0.title : depth0),{"name":"unless","hash":{},"fn":container.program(11, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
8714    + "</a>\n";
8715},"16":function(container,depth0,helpers,partials,data) {
8716    var stack1, helper, alias1=depth0 != null ? depth0 : (container.nullContext || {}), alias2=helpers.helperMissing, alias3="function";
8717
8718  return "<a href=\""
8719    + ((stack1 = ((helper = (helper = helpers.url || (depth0 != null ? depth0.url : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"url","hash":{},"data":data}) : helper))) != null ? stack1 : "")
8720    + "\" class=\""
8721    + ((stack1 = ((helper = (helper = helpers.exactMatch || (depth0 != null ? depth0.exactMatch : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"exactMatch","hash":{},"data":data}) : helper))) != null ? stack1 : "")
8722    + "\">"
8723    + ((stack1 = ((helper = (helper = helpers.title || (depth0 != null ? depth0.title : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"title","hash":{},"data":data}) : helper))) != null ? stack1 : "")
8724    + ((stack1 = helpers.unless.call(alias1,(depth0 != null ? depth0.title : depth0),{"name":"unless","hash":{},"fn":container.program(11, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
8725    + "</a>\n";
8726},"18":function(container,depth0,helpers,partials,data) {
8727    var stack1;
8728
8729  return ((stack1 = (helpers.ifEqual || (depth0 && depth0.ifEqual) || helpers.helperMissing).call(
8729depth0 != null ? depth0 : (container.nullContext || {}),((stack1 = (data && data.root)) && stack1.hasSelector),true,{"name":"ifEqual","hash":{},"fn":container.program(19, data, 0),"inverse":container.program(34, data, 0),"data":data})) != null ? stack1 : "");
8730},"19":function(container,depth0,helpers,partials,data) {
8731    var stack1;
8732
8733  return ((stack1 = (helpers.ifEqual || (depth0 && depth0.ifEqual) || helpers.helperMissing).call(depth0 != null ? depth0 : (container.nullContext || {}),((stack1 = (data && data.root)) && stack1.selectorName),"conditions",{"name":"ifEqual","hash":{},"fn":container.program(20, data, 0),"inverse":container.program(28, data, 0),"data":data})) != null ? stack1 : "");
8734},"20":function(container,depth0,helpers,partials,data) {
8735    var stack1;
8736
8737  return "<div class=\"view-more\">\n"
8738    + ((stack1 = (helpers["switch"] || (depth0 && depth0["switch"]) || helpers.helperMissing).call(depth0 != null ? depth0 : (container.nullContext || {}),(depth0 != null ? depth0.type : depth0),{"name":"switch","hash":{},"fn":container.program(21, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
8739    + "</div>\n";
8740},"21":function(container,depth0,helpers,partials,data) {
8741    var stack1, helper, options, alias1=depth0 != null ? depth0 : (container.nullContext || {}), alias2=helpers.helperMissing, buffer = 
8742  ((stack1 = (helpers["case"] || (depth0 && depth0["case"]) || alias2).call(alias1,"conditions",{"name":"case","hash":{},"fn":container.program(22, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
8743    + ((stack1 = (helpers["case"] || (depth0 && depth0["case"]) || alias2).call(alias1,"treatments",{"name":"case","hash":{},"fn":container.program(24, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
8744    + ((stack1 = (helpers["case"] || (depth0 && depth0["case"]) || alias2).call(alias1,"tests",{"name":"case","hash":{},"fn":container.program(26, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "");
8745  stack1 = ((helper = (helper = helpers["default"] || (depth0 != null ? depth0["default"] : depth0)) != null ? helper : alias2),(options={"name":"default","hash":{},"fn":container.program(26, data, 0),"inverse":container.noop,"data":data}),(typeof helper === "function" ? helper.call(alias1,options) : helper));
8746  if (!helpers["default"]) { stack1 = helpers.blockHelperMissing.call(depth0,stack1,options)}
8747  if (stack1 != null) { buffer += stack1; }
8748  return buffer;
8749},"22":function(container,depth0,helpers,partials,data) {
8750    var stack1, helper, alias1=depth0 != null ? depth0 : (container.nullContext || {}), alias2=helpers.helperMissing, alias3="function", alias4=container.escapeExpression;
8751
8752  return "<a href=\""
8753    + alias4(((helper = (helper = helpers.homepagePath || (depth0 != null ? depth0.homepagePath : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"homepagePath","hash":{},"data":data}) : helper)))
8754    + alias4(((helper = (helper = helpers.getGuidedSearchURL || (depth0 != null ? depth0.getGuidedSearchURL : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"getGuidedSearchURL","hash":{},"data":data}) : helper)))
8755    + "/"
8756    + ((stack1 = container.lambda(((stack1 = (data && data.root)) && stack1.searchTerm), depth0)) != null ? stack1 : "")
8757    + "#x1=sp_type&q1=condition&page=1\">\nView All "
8758    + ((stack1 = ((helper = (helper = helpers.heading || (depth0 != null ? depth0.heading : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"heading","hash":{},"data":data}) : helper))) != null ? stack1 : "")
8759    + "\n</a>\n";
8760},"24":function(container,depth0,helpers,partials,data) {
8761    var stack1, helper, alias1=depth0 != null ? depth0 : (container.nullContext || {}), alias2=helpers.helperMissing, alias3="function", alias4=container.escapeExpression;
8762
8763  return "<a href=\""
8764    + alias4(((helper = (helper = helpers.homepagePath || (depth0 != null ? depth0.homepagePath : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"homepagePath","hash":{},"data":data}) : helper)))
8765    + alias4(((helper = (helper = helpers.getGuidedSearchURL || (depth0 != null ? depth0.getGuidedSearchURL : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"getGuidedSearchURL","hash":{},"data":data}) : helper)))
8766    + "/"
8767    + ((stack1 = container.lambda(((stack1 = (data && data.root)) && stack1.searchTerm), depth0)) != null ? stack1 : "")
8768    + "#x1=sp_type&q1=treatment&page=1\">\nView All "
8769    + ((stack1 = ((helper = (helper = helpers.heading || (depth0 != null ? depth0.heading : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"heading","hash":{},"data":data}) : helper))) != null ? stack1 : "")
8770    + "\n</a>\n";
8771},"26":function(container,depth0,helpers,partials,data) {
8772    var stack1, helper, alias1=depth0 != null ? depth0 : (container.nullContext || {}), alias2=helpers.helperMissing, alias3="function", alias4=container.escapeExpression;
8773
8774  return "<a href=\""
8775    + alias4(((helper = (helper = helpers.homepagePath || (depth0 != null ? depth0.homepagePath : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"homepagePath","hash":{},"data":data}) : helper)))
8776    + alias4(((helper = (helper = helpers.getGuidedSearchURL || (depth0 != null ? depth0.getGuidedSearchURL : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"getGuidedSearchURL","hash":{},"data":data}) : helper)))
8777    + "/"
8778    + ((stack1 = container.lambda(((stack1 = (data && data.root)) && stack1.searchTerm), depth0)) != null ? stack1 : "")
8779    + "#x1=sp_type&q1=%20&page=1\">\nView All "
8780    + ((stack1 = ((helper = (helper = helpers.heading || (depth0 != null ? depth0.heading : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"heading","hash":{},"data":data}) : helper))) != null ? stack1 : "")
8781    + "</a>\n";
8782},"28":function(container,depth0,helpers,partials,data) {
8783    var stack1;
8784
8785  return "</div>\n"
8786    + ((stack1 = (helpers["switch"] || (depth0 && depth0["switch"]) || helpers.helperMissing).call(
8786depth0 != null ? depth0 : (container.nullContext || {}),(depth0 != null ? depth0.type : depth0),{"name":"switch","hash":{},"fn":container.program(29, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "");
8787},"29":function(container,depth0,helpers,partials,data) {
8788    var stack1, helper, options, alias1=depth0 != null ? depth0 : (container.nullContext || {}), alias2=helpers.helperMissing, buffer = 
8789  ((stack1 = (helpers["case"] || (depth0 && depth0["case"]) || alias2).call(alias1,"trials",{"name":"case","hash":{},"fn":container.program(30, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "");
8790  stack1 = ((helper = (helper = helpers["default"] || (depth0 != null ? depth0["default"] : depth0)) != null ? helper : alias2),(options={"name":"default","hash":{},"fn":container.program(32, data, 0),"inverse":container.noop,"data":data}),(typeof helper === "function" ? helper.call(alias1,options) : helper));
8791  if (!helpers["default"]) { stack1 = helpers.blockHelperMissing.call(depth0,stack1,options)}
8792  if (stack1 != null) { buffer += stack1; }
8793  return buffer;
8794},"30":function(container,depth0,helpers,partials,data) {
8795    var stack1, helper, alias1=depth0 != null ? depth0 : (container.nullContext || {}), alias2=helpers.helperMissing, alias3="function";
8796
8797  return "<a class='view-all'\nhref=\""
8798    + container.escapeExpression(((helper = (helper = helpers.homepagePath || (depth0 != null ? depth0.homepagePath : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"homepagePath","hash":{},"data":data}) : helper)))
8799    + "application/ct.html/"
8800    + ((stack1 = container.lambda(((stack1 = (data && data.root)) && stack1.searchTerm), depth0)) != null ? stack1 : "")
8801    + "?src=pred\">\nView All "
8802    + ((stack1 = ((helper = (helper = helpers.heading || (depth0 != null ? depth0.heading : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"heading","hash":{},"data":data}) : helper))) != null ? stack1 : "")
8803    + "\n</a>\n";
8804},"32":function(container,depth0,helpers,partials,data) {
8805    var stack1, helper, alias1=depth0 != null ? depth0 : (container.nullContext || {}), alias2=helpers.helperMissing, alias3="function";
8806
8807  return "<a class='view-all'\nhref=\""
8808    + container.escapeExpression(((helper = (helper = helpers.homepagePath || (depth0 != null ? depth0.homepagePath : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"homepagePath","hash":{},"data":data}) : helper)))
8809    + "search-results."
8810    + ((stack1 = ((helper = (helper = helpers.type || (depth0 != null ? depth0.type : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"type","hash":{},"data":data}) : helper))) != null ? stack1 : "")
8811    + ".html/"
8812    + ((stack1 = container.lambda(((stack1 = (data && data.root)) && stack1.searchTerm), depth0)) != null ? stack1 : "")
8813    + "?src=pred\">\nView All "
8814    + ((stack1 = ((helper = (helper = helpers.heading || (depth0 != null ? depth0.heading : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"heading","hash":{},"data":data}) : helper))) != null ? stack1 : "")
8815    + "\n</a>\n";
8816},"34":function(container,depth0,helpers,partials,data) {
8817    var stack1;
8818
8819  return "<div class=\"view-more\">\n"
8820    + ((stack1 = (helpers["switch"] || (depth0 && depth0["switch"]) || helpers.helperMissing).call(depth0 != null ? depth0 : (container.nullContext || {}),(depth0 != null ? depth0.type : depth0),{"name":"switch","hash":{},"fn":container.program(35, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
8821    + "</div>\n";
8822},"35":function(container,depth0,helpers,partials,data) {
8823    var stack1, helper, options, alias1=depth0 != null ? depth0 : (container.nullContext || {}), alias2=helpers.helperMissing, buffer = 
8824  ((stack1 = (helpers["case"] || (depth0 && depth0["case"]) || alias2).call(alias1,"conditions",{"name":"case","hash":{},"fn":container.program(22, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
8825    + ((stack1 = (helpers["case"] || (depth0 && depth0["case"]) || alias2).call(alias1,"treatments",{"name":"case","hash":{},"fn":container.program(24, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
8826    + ((stack1 = (helpers["case"] || (depth0 && depth0["case"]) || alias2).call(alias1,"tests",{"name":"case","hash":{},"fn":container.program(26, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
8827    + ((stack1 = (helpers["case"] || (depth0 && depth0["case"]) || alias2).call(alias1,"newsroom",{"name":"case","hash":{},"fn":container.program(36, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
8828    + ((stack1 = (helpers["case"] || (depth0 && depth0["case"]) || alias2).call(alias1,"doctors",{"name":"case","hash":{},"fn":container.program(38, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
8829    + ((stack1 = (helpers["case"] || (depth0 && depth0["case"]) || alias2).call(alias1,"clinics",{"name":"case","hash":{},"fn":container.program(40, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
8830    + ((stack1 = (helpers["case"] || (depth0 && depth0["case"]) || alias2).call(alias1,"trials",{"name":"case","hash":{},"fn":container.program(42, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "");
8831  stack1 = ((helper = (helper = helpers["default"] || (depth0 != null ? depth0["default"] : depth0)) != null ? helper : alias2),(options={"name":"default","hash":{},"fn":container.program(44, data, 0),"inverse":container.noop,"data":data}),(typeof helper === "function" ? helper.call(alias1,options) : helper));
8832  if (!helpers["default"]) { stack1 = helpers.blockHelperMissing.call(depth0,stack1,options)}
8833  if (stack1 != null) { buffer += stack1; }
8834  return buffer;
8835},"36":function(container,depth0,helpers,partials,data) {
8836    var stack1, helper, alias1=depth0 != null ? depth0 : (container.nullContext || {}), alias2=helpers.helperMissing, alias3="function";
8837
8838  return "<a href=\""
8839    + container.escapeExpression(((helper = (helper = helpers.homepagePath || (depth0 != null ? depth0.homepagePath : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"homepagePath","hash":{},"data":data}) : helper)))
8840    + "search-results.newsroom.html/"
8841    + ((stack1 = container.lambda(((stack1 = (data && data.root)) && stack1.searchTerm), depth0)) != null ? stack1 : "")
8842    + "?src=pred_newsroom\">\nView All "
8843    + ((stack1 = ((helper = (helper = helpers.heading || (depth0 != null ? depth0.heading : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"heading","hash":{},"data":data}) : helper))) != null ? stack1 : "")
8844    + " Results</a>\n";
8845},"38":function(container,depth0,helpers,partials,data) {
8846    var stack1, helper, alias1=depth0 != null ? depth0 : (container.nullContext || {}), alias2=helpers.helperMissing, alias3="function", alias4=container.escapeExpression;
8847
8848  return "<a href=\""
8849    + alias4(((helper = (helper = helpers.homepagePath || (depth0 != null ? depth0.homepagePath : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"homepagePath","hash":{},"data":data}) : helper)))
8850    + alias4(((helper = (helper = helpers.getGuidedSearchURL || (depth0 != null ? depth0.getGuidedSearchURL : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"getGuidedSearchURL","hash":{},"data":data}) : helper)))
8851    + "/"
8852    + ((stack1 = container.lambda(((stack1 = (data && data.root)) && stack1.searchTerm), depth0)) != null ? stack1 : "")
8853    + "#x1=sp_spec_care_phy&q1=true&page=1\">\nView All "
8854    + ((stack1 = ((helper = (helper = helpers.heading || (depth0 != null ? depth0.heading : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"heading","hash":{},"data":data}) : helper))) != null ? stack1 : "")
8855    + " Results</a>\n";
8856},"40":function(container,depth0,helpers,partials,data) {
8857    var stack1, helper, alias1=depth0 != null ? depth0 : (container.nullContext || {}), alias2=helpers.helperMissing, alias3="function", alias4=container.escapeExpression;
8858
8859  return "<a href=\""
8860    + alias4(((helper = (helper = helpers.homepagePath || (depth0 != null ? depth0.homepagePath : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"homepagePath","hash":{},"data":data}) : helper)))
8861    + alias4(((helper = (helper = helpers.getGuidedSearchURL || (depth0 != null ? depth0.getGuidedSearchURL : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"getGuidedSearchURL","hash":{},"data":data}) : helper)))
8862    + "/"
8863    + ((stack1 = container.lambda(((stack1 = (data && data.root)) && stack1.searchTerm), depth0)) != null ? stack1 : "")
8864    + "#x1=sp_prim_care_clinic&q1=true&page=1\">\nView All "
8865    + ((stack1 = ((helper = (helper = helpers.heading || (depth0 != null ? depth0.heading : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"heading","hash":{},"data":data}) : helper))) != null ? stack1 : "")
8866    + " Results</a>\n";
8867},"42":function(container,depth0,helpers,partials,data) {
8868    var stack1, helper, alias1=depth0 != null ? depth0 : (container.nullContext || {}), alias2=helpers.helperMissing, alias3="function";
8869
8870  return "<a href=\""
8871    + container.escapeExpression(((helper = (helper = helpers.homepagePath || (depth0 != null ? depth0.homepagePath : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"homepagePath","hash":{},"data":data}) : helper)))
8872    + "application/ct.html/"
8873    + ((stack1 = container.lambda(((stack1 = (data && data.root)) && stack1.searchTerm), depth0)) != null ? stack1 : "")
8874    + "?src=pred\">\nView All "
8875    + ((stack1 = ((helper = (helper = helpers.heading || (depth0 != null ? depth0.heading : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"heading","hash":{},"data":data}) : helper))) != null ? stack1 : "")
8876    + "</a>\n";
8877},"44":function(container,depth0,helpers,partials,data) {
8878    var stack1, alias1=depth0 != null ? depth0 : (container.nullContext || {});
8879
8880  return ((stack1 = helpers["if"].call(alias1,(helpers.isValleycare || (depth0 && depth0.isValleycare) || helpers.helperMissing).call(alias1,{"name":"isValleycare","hash":{},"data":data}),{"name":"if","hash":{},"fn":container.program(45, data, 0),"inverse":container.program(47, data, 0),"data":data})) != null ? stack1 : "");
8881},"45":function(container,depth0,helpers,partials,data) {
8882    var stack1, helper, alias1=depth0 != null ? depth0 : (container.nullContext || {}), alias2=helpers.helperMissing, alias3="function";
8883
8884  return "<a href=\""
8885    + container.escapeExpression(((helper = (helper = helpers.homepagePath || (depth0 != null ? depth0.homepagePath : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"homepagePath","hash":{},"data":data}) : helper)))
8886    + "directory/directory.html/"
8887    + ((stack1 = container.lambda(((stack1 = (data && data.root)) && stack1.searchTerm), depth0)) != null ? stack1 : "")
8888    + "#x1=sp_spec_care_phy&q1=true&page=1\">\nView All "
8889    + ((stack1 = ((helper = (helper = helpers.heading || (depth0 != null ? depth0.heading : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"heading","hash":{},"data":data}) : helper))) != null ? stack1 : "")
8890    + "</a>\n";
8891},"47":function(container,depth0,helpers,partials,data) {
8892    var stack1, helper, alias1=depth0 != null ? depth0 : (container.nullContext || {}), alias2=helpers.helperMissing, alias3="function";
8893
8894  return "<a href=\""
8895    + container.escapeExpression(((helper = (helper = helpers.homepagePath || (depth0 != null ? depth0.homepagePath : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"homepagePath","hash":{},"data":data}) : helper)))
8896    + "search-results."
8897    + ((stack1 = ((helper = (helper = helpers.type || (depth0 != null ? depth0.type : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"type","hash":{},"data":data}) : helper))) != null ? stack1 : "")
8898    + ".html/"
8899    + ((stack1 = container.lambda(((stack1 = (data && data.root)) && stack1.searchTerm), depth0)) != null ? stack1 : "")
8900    + "?src=pred\">\nView All "
8901    + ((stack1 = ((helper = (helper = helpers.heading || (depth0 != null ? depth0.heading : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"heading","hash":{},"data":data}) : helper))) != null ? stack1 : "")
8902    + "</a>\n";
8903},"49":function(container,depth0,helpers,partials,data) {
8904    var stack1;
8905
8906  return "<div id = \"search-suggestions\">\n<h2 class=\"search-result-heading suggested-searches-heading\">"
8907    + ((stack1 = container.lambda((depth0 != null ? depth0.heading : depth0), depth0)) != null ? stack1 : "")
8908    + "</h2>\n"
8909    + ((stack1 = helpers.each.call(depth0 != null ? depth0 : (container.nullContext || {}),(depth0 != null ? depth0.data : depth0),{"name":"each","hash":{},"fn":container.program(50, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "");
8910},"50":function(container,depth0,helpers,partials,data) {
8911    var helper, alias1=depth0 != null ? depth0 : (container.nullContext || {}), alias2=helpers.helperMissing, alias3=container.escapeExpression;
8912
8913  return "<div class=\"suggestion link-item suggested-searches-item\">\n<a href=\""
8914    + alias3(((helper = (helper = helpers.homepagePath || (depth0 != null ? depth0.homepagePath : depth0)) != null ? helper : alias2),(typeof helper === "function" ? helper.call(alias1,{"name":"homepagePath","hash":{},"data":data}) : helper)))
8915    + "search-results.html/"
8916    + alias3((helpers.urlEncode || (depth0 && depth0.urlEncode) || alias2).call(alias1,depth0,{"name":"urlEncode","hash":{},"data":data}))
8917    + "\">\n<span class=\"icon\"></span>\n"
8918    + alias3(container.lambda(depth0, depth0))
8919    + "\n</a>\n</div>\n";
8920},"52":function(container,depth0,helpers,partials,data) {
8921    var helper, alias1=container.escapeExpression;
8922
8923  return "<a class='view-all' href='"
8924    + alias1(((helper = (helper = helpers.homepagePath || (depth0 != null ? depth0.homepagePath : depth0)) != null ? helper : helpers.helperMissing),(typeof helper === "function" ? helper.call(depth0 != null ? depth0 : (container.nullContext || {}
vendor: 45,165 bytes, lines 8924-9332
8924),{"name":"homepagePath","hash":{},"data":data}) : helper)))
8925    + "search-results.html/"
8926    + alias1(container.lambda((depth0 != null ? depth0.searchTerm : depth0), depth0))
8927    + "?src=pred'>See All Results</a>\n";
8928},"compiler":[7,">= 4.0.0"],"main":function(container,depth0,helpers,partials,data,blockParams,depths) {
8929    var stack1, alias1=depth0 != null ? depth0 : (container.nullContext || {}), alias2=helpers.helperMissing;
8930
8931  return ((stack1 = (helpers.ifNotEmpty || (depth0 && depth0.ifNotEmpty) || alias2).call(alias1,(depth0 != null ? depth0.categories : depth0),{"name":"ifNotEmpty","hash":{},"fn":container.program(1, data, 0, blockParams, depths),"inverse":container.noop,"data":data})) != null ? stack1 : "")
8932    + ((stack1 = (helpers.ifEqual || (depth0 && depth0.ifEqual) || alias2).call(alias1,(depth0 != null ? depth0.hasSelector : depth0),false,{"name":"ifEqual","hash":{},"fn":container.program(52, data, 0, blockParams, depths),"inverse":container.noop,"data":data})) != null ? stack1 : "");
8933},"useData":true,"useDepths":true});
8934
8935this["JST"]["handlebars/info-window-clinic-header.hbs"] = Handlebars.template({"1":function(container,depth0,helpers,partials,data) {
8936    var helper, alias1=depth0 != null ? depth0 : (container.nullContext || {}), alias2=helpers.helperMissing, alias3="function", alias4=container.escapeExpression;
8937
8938  return "<p class=\"info-window-header-address line-one\">\n"
8939    + alias4(((helper = (helper = helpers.address || (depth0 != null ? depth0.address : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"address","hash":{},"data":data}) : helper)))
8940    + ",\n</p>\n<p class=\"info-window-header-address line-two\">\n"
8941    + alias4(((helper = (helper = helpers.city || (depth0 != null ? depth0.city : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"city","hash":{},"data":data}) : helper)))
8942    + ", "
8943    + alias4(((helper = (helper = helpers.state || (depth0 != null ? depth0.state : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"state","hash":{},"data":data}) : helper)))
8944    + "\n</p>\n<span class=\"hidden multi-clinic-address clinic-title-tracking\">"
8945    + alias4(((helper = (helper = helpers.address || (depth0 != null ? depth0.address : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"address","hash":{},"data":data}) : helper)))
8946    + ", "
8947    + alias4(((helper = (helper = helpers.city || (depth0 != null ? depth0.city : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"city","hash":{},"data":data}) : helper)))
8948    + ", "
8949    + alias4(((helper = (helper = helpers.state || (depth0 != null ? depth0.state : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"state","hash":{},"data":data}) : helper)))
8950    + "</span>\n";
8951},"compiler":[7,">= 4.0.0"],"main":function(container,depth0,helpers,partials,data) {
8952    var stack1, helper, alias1=depth0 != null ? depth0 : (container.nullContext || {}), alias2=helpers.helperMissing;
8953
8954  return "<div class=\"info-window-header-container clinics\">\n"
8955    + ((stack1 = (helpers.ifNotEmpty || (depth0 && depth0.ifNotEmpty) || alias2).call(alias1,(depth0 != null ? depth0.address : depth0),{"name":"ifNotEmpty","hash":{},"fn":container.program(1, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
8956    + "<p class=\"info-window-header\"><span class=\"num-clinics\">"
8957    + container.escapeExpression(((helper = (helper = helpers.numClinics || (depth0 != null ? depth0.numClinics : depth0)) != null ? helper : alias2),(typeof helper === "function" ? helper.call(alias1,{"name":"numClinics","hash":{},"data":data}) : helper)))
8958    + " clinics</span> at this location:</p>\n</div>\n";
8959},"useData":true});
8960
8961this["JST"]["handlebars/info-window-clinic-template.hbs"] = Handlebars.template({"1":function(container,depth0,helpers,partials,data) {
8962    var helper;
8963
8964  return "<p>"
8965    + container.escapeExpression(((helper = (helper = helpers.address || (depth0 != null ? depth0.address : depth0)) != null ? helper : helpers.helperMissing),(typeof helper === "function" ? helper.call(depth0 != null ? depth0 : (container.nullContext || {}),{"name":"address","hash":{},"data":data}) : helper)))
8966    + ",<p>\n";
8967},"3":function(container,depth0,helpers,partials,data) {
8968    var helper;
8969
8970  return "<p>"
8971    + container.escapeExpression(((helper = (helper = helpers.address2 || (depth0 != null ? depth0.address2 : depth0)) != null ? helper : helpers.helperMissing),(typeof helper === "function" ? helper.call(depth0 != null ? depth0 : (container.nullContext || {}),{"name":"address2","hash":{},"data":data}) : helper)))
8972    + "</p>\n";
8973},"5":function(container,depth0,helpers,partials,data) {
8974    var helper, alias1=depth0 != null ? depth0 : (container.nullContext || {}), alias2=helpers.helperMissing, alias3="function", alias4=container.escapeExpression;
8975
8976  return "<p>"
8977    + alias4(((helper = (helper = helpers.city || (depth0 != null ? depth0.city : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"city","hash":{},"data":data}) : helper)))
8978    + ", "
8979    + alias4(((helper = (helper = helpers.state || (depth0 != null ? depth0.state : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"state","hash":{},"data":data}) : helper)))
8980    + " "
8981    + alias4(((helper = (helper = helpers.zipcode || (depth0 != null ? depth0.zipcode : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"zipcode","hash":{},"data":data}) : helper)))
8982    + "</p>\n";
8983},"7":function(container,depth0,helpers,partials,data) {
8984    var helper, alias1=depth0 != null ? depth0 : (container.nullContext || {}), alias2=helpers.helperMissing, alias3=container.escapeExpression;
8985
8986  return "<a href=\""
8987    + alias3(((helper = (helper = helpers.locationDetails || (depth0 != null ? depth0.locationDetails : depth0)) != null ? helper : alias2),(typeof helper === "function" ? helper.call(alias1,{"name":"locationDetails","hash":{},"data":data}) : helper)))
8988    + "\" data-"
8989    + alias3((helpers.notLocation || (depth0 && depth0.notLocation) || alias2).call(alias1,(depth0 != null ? depth0.templatePath : depth0),{"name":"notLocation","hash":{},"data":data}))
8990    + "=\"#main-container\" class=\"info-window-modal info-window-location\">Getting&nbsp;Here&nbsp;</a>\n";
8991},"9":function(container,depth0,helpers,partials,data) {
8992    var helper;
8993
8994  return "<a href=\""
8995    + container.escapeExpression(((helper = (helper = helpers.locationDetails || (depth0 != null ? depth0.locationDetails : depth0)) != null ? helper : helpers.helperMissing),(typeof helper === "function" ? helper.call(depth0 != null ? depth0 : (container.nullContext || {}),{"name":"locationDetails","hash":{},"data":data}) : helper)))
8996    + "\" class=\"info-window-modal info-window-location\">Getting&nbsp;Here&nbsp;</a>\n";
8997},"compiler":[7,">= 4.0.0"],"main":function(container,depth0,helpers,partials,data) {
8998    var stack1, helper, options, alias1=depth0 != null ? depth0 : (container.nullContext || {}), alias2=helpers.helperMissing, alias3="function", buffer = 
8999  "<div class=\"info-window single-clinic clearfix\">\n<div class=\"info-window-details\">\n<a href=\""
9000    + container.escapeExpression(((helper = (helper = helpers.pagePath || (depth0 != null ? depth0.pagePath : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"pagePath","hash":{},"data":data}) : helper)))
9001    + "\" class=\"info-window-name clinic-title-tracking\">"
9002    + ((stack1 = (helpers.htmlEntityDecode || (depth0 && depth0.htmlEntityDecode) || alias2).call(alias1,(depth0 != null ? depth0.title : depth0),{"name":"htmlEntityDecode","hash":{},"data":data})) != null ? stack1 : "")
9003    + "</a>\n"
9004    + ((stack1 = (helpers.ifNotEmpty || (depth0 && depth0.ifNotEmpty) || alias2).call(alias1,(depth0 != null ? depth0.address : depth0),{"name":"ifNotEmpty","hash":{},"fn":container.program(1, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
9005    + ((stack1 = (helpers.ifNotEmpty || (depth0 && depth0.ifNotEmpty) || alias2).call(alias1,(depth0 != null ? depth0.address2 : depth0),{"name":"ifNotEmpty","hash":{},"fn":container.program(3, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
9006    + ((stack1 = (helpers.ifNotEmpty || (depth0 && depth0.ifNotEmpty) || alias2).call(alias1,(depth0 != null ? depth0.city : depth0),{"name":"ifNotEmpty","hash":{},"fn":container.program(5, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
9007    + ((stack1 = helpers["if"].call(alias1,(depth0 != null ? depth0.isClinic : depth0),{"name":"if","hash":{},"fn":container.program(7, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "");
9008  stack1 = ((helper = (helper = helpers.empty || (depth0 != null ? depth0.empty : depth0)) != null ? helper : alias2),(options={"name":"empty","hash":{},"fn":container.program(9, data, 0),"inverse":container.noop,"data":data}),(typeof helper === alias3 ? helper.call(alias1,options) : helper));
9009  if (!helpers.empty) { stack1 = helpers.blockHelperMissing.call(depth0,stack1,options)}
9010  if (stack1 != null) { buffer += stack1; }
9011  return buffer + "</div>\n</div>\n";
9012},"useData":true});
9013
9014this["JST"]["handlebars/info-window-clinics-template.hbs"] = Handlebars.template({"compiler":[7,">= 4.0.0"],"main":function(container,depth0,helpers,partials,data) {
9015    var stack1, helper, alias1=depth0 != null ? depth0 : (container.nullContext || {}), alias2=helpers.helperMissing, alias3="function", alias4=container.escapeExpression;
9016
9017  return "<div class=\"info-window clinics clearfix\">\n<div class=\"info-window-details\">\n<a href=\""
9018    + alias4(((helper = (helper = helpers.pagePath || (depth0 != null ? depth0.pagePath : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"pagePath","hash":{},"data":data}) : helper)))
9019    + "\" class=\"info-window-name\">"
9020    + ((stack1 = (helpers.htmlEntityDecode || (depth0 && depth0.htmlEntityDecode) || alias2).call(alias1,(depth0 != null ? depth0.title : depth0),{"name":"htmlEntityDecode","hash":{},"data":data})) != null ? stack1 : "")
9021    + "</a>\n<a href=\""
9022    + alias4(((helper = (helper = helpers.locationDetails || (depth0 != null ? depth0.locationDetails : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"locationDetails","hash":{},"data":data}) : helper)))
9023    + "\" class=\"info-window-modal info-window-location\">Getting&nbsp;Here&nbsp;</a>\n</div>\n</div>\n";
9024},"useData":true});
9025
9026this["JST"]["handlebars/info-window-template.hbs"] = Handlebars.template({"1":function(container,depth0,helpers,partials,data) {
9027    return " has-image";
9028},"3":function(container,depth0,helpers,partials,data) {
9029    var stack1, helper, alias1=depth0 != null ? depth0 : (container.nullContext || {}), alias2=helpers.helperMissing, alias3="function", alias4=container.escapeExpression;
9030
9031  return "<div class=\"image-container\">\n<img src=\""
9032    + alias4(((helper = (helper = helpers.image || (depth0 != null ? depth0.image : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"image","hash":{},"data":data}) : helper)))
9033    + ((stack1 = (helpers.ifNotContains || (depth0 && depth0.ifNotContains) || alias2).call(alias1,(depth0 != null ? depth0.image : depth0),"http",{"name":"ifNotContains","hash":{},"fn":container.program(4, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
9034    + "\" alt=\""
9035    + alias4(((helper = (helper = helpers.imageAltText || (depth0 != null ? depth0.imageAltText : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"imageAltText","hash":{},"data":data}) : helper)))
9036    + "\" class=\"info-window-image\"/>\n</div>\n";
9037},"4":function(container,depth0,helpers,partials,data) {
9038    return ".transform/221x221/q82/image.png";
9039},"6":function(container,depth0,helpers,partials,data) {
9040    var helper;
9041
9042  return container.escapeExpression(((helper = (helper = helpers.address2 || (depth0 != null ? depth0.address2 : depth0)) != null ? helper : helpers.helperMissing),(typeof helper === "function" ? helper.call(depth0 != null ? depth0 : (container.nullContext || {}),{"name":"address2","hash":{},"data":data}) : helper)))
9043    + "<br>\n";
9044},"compiler":[7,">= 4.0.0"],"main":function(container,depth0,helpers,partials,data) {
9045    var stack1, helper, alias1=depth0 != null ? depth0 : (container.nullContext || {}), alias2=helpers.helperMissing, alias3="function", alias4=container.escapeExpression;
9046
9047  return "<div class=\"info-window clearfix"
9048    + ((stack1 = (helpers.ifNotEmpty || (depth0 && depth0.ifNotEmpty) || alias2).call(alias1,(depth0 != null ? depth0.image : depth0),{"name":"ifNotEmpty","hash":{},"fn":container.program(1, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
9049    + "\">\n"
9050    + ((stack1 = (helpers.ifNotEmpty || (depth0 && depth0.ifNotEmpty) || alias2).call(alias1,(depth0 != null ? depth0.image : depth0),{"name":"ifNotEmpty","hash":{},"fn":container.program(3, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
9051    + "<div class=\"info-window-details"
9052    + ((stack1 = (helpers.ifNotEmpty || (depth0 && depth0.ifNotEmpty) || alias2).call(alias1,(depth0 != null ? depth0.image : depth0),{"name":"ifNotEmpty","hash":{},"fn":container.program(1, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
9053    + "\">\n<a href=\""
9054    + alias4(((helper = (helper = helpers.pagePath || (depth0 != null ? depth0.pagePath : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"pagePath","hash":{},"data":data}) : helper)))
9055    + "\" class=\"info-window-title\">"
9056    + alias4(((helper = (helper = helpers.title || (depth0 != null ? depth0.title : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"title","hash":{},"data":data}) : helper)))
9057    + "</a>\n<span class=\"info-window-address\">\n"
9058    + alias4(((helper = (helper = helpers.address || (depth0 != null ? depth0.address : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"address","hash":{},"data":data}) : helper)))
9059    + "<br>\n"
9060    + ((stack1 = (helpers.ifNotEmpty || (depth0 && depth0.ifNotEmpty) || alias2).call(alias1,(depth0 != null ? depth0.address2 : depth0),{"name":"ifNotEmpty","hash":{},"fn":container.program(6, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
9061    + "</span>\n<div class=\"address-line-2\">\n<span class=\"info-window-city\">"
9062    + alias4(((helper = (helper = helpers.city || (depth0 != null ? depth0.city : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"city","hash":{},"data":data}) : helper)))
9063    + ",</span>\n<span class=\"info-window-state\">"
9064    + alias4(((helper = (helper = helpers.state || (depth0 != null ? depth0.state : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"state","hash":{},"data":data}) : helper)))
9065    + "</span>\n<span class=\"info-window-zipcode\">"
9066    + alias4(((helper = (helper = helpers.zipcode || (depth0 != null ? depth0.zipcode : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"zipcode","hash":{},"data":data}) : helper)))
9067    + "</span>\n</div>\n<a href=\""
9068    + alias4(((helper = (helper = helpers.locationDetails || (depth0 != null ? depth0.locationDetails : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"locationDetails","hash":{},"data":data}) : helper)))
9069    + "\" class=\"info-window-modal info-window-location\">Getting&nbsp;Here&nbsp;</a>\n</div>\n</div>\n";
9070},"useData":true});
9071
9072this["JST"]["handlebars/infobubble.hbs"] = Handlebars.template({"compiler":[7,">= 4.0.0"],"main":function(container,depth0,helpers,partials,data) {
9073    var helper, alias1=depth0 != null ? depth0 : (container.nullContext || {}), alias2=helpers.helperMissing, alias3="function", alias4=container.escapeExpression;
9074
9075  return "<div id=\"content\">\n<strong class=\"firstHeading\">"
9076    + alias4(((helper = (helper = helpers.name || (depth0 != null ? depth0.name : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"name","hash":{},"data":data}) : helper)))
9077    + "</strong>\n<p>\n"
9078    + alias4(((helper = (helper = helpers.address || (depth0 != null ? depth0.address : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"address","hash":{},"data":data}) : helper)))
9079    + ",<br/>\n"
9080    + alias4(((helper = (helper = helpers.city || (depth0 != null ? depth0.city : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"city","hash":{},"data":data}) : helper)))
9081    + ", "
9082    + alias4(((helper = (helper = helpers.state || (depth0 != null ? depth0.state : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"state","hash":{},"data":data}) : helper)))
9083    + " "
9084    + alias4(((helper = (helper = helpers.zipcode || (depth0 != null ? depth0.zipcode : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"zipcode","hash":{},"data":data}) : helper)))
9085    + "<br/>\nPhone: "
9086    + alias4(((helper = (helper = helpers.phone || (depth0 != null ? depth0.phone : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"phone","hash":{},"data":data}) : helper)))
9087    + "\n</p>\n<p><a href=\""
9088    + alias4(((helper = (helper = helpers.url || (depth0 != null ? depth0.url : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"url","hash":{},"data":data}) : helper)))
9089    + "\" target=\"_blank\">Get Directions</a></p>\n</div>\n";
9090},"useData":true});
9091
9092this["JST"]["handlebars/job-enabled.hbs"] = Handlebars.template({"1":function(container,depth0,helpers,partials,data) {
9093    var helper;
9094
9095  return "<a href=\""
9096    + container.escapeExpression(((helper = (helper = helpers.reportURL || (depth0 != null ? depth0.reportURL : depth0)) != null ? helper : helpers.helperMissing),(typeof helper === "function" ? helper.call(depth0 != null ? depth0 : (container.nullContext || {}),{"name":"reportURL","hash":{},"data":data}) : helper)))
9097    + "\" target=\"_blank\">file</a>";
9098},"compiler":[7,">= 4.0.0"],"main":function(container,depth0,helpers,partials,data) {
9099    var stack1, helper, alias1=depth0 != null ? depth0 : (container.nullContext || {}), alias2=helpers.helperMissing, alias3="function", alias4=container.escapeExpression;
9100
9101  return "<tr>\n<td>"
9102    + alias4(((helper = (helper = helpers.name || (depth0 != null ? depth0.name : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"name","hash":{},"data":data}) : helper)))
9103    + "</td>\n<td>"
9104    + alias4(((helper = (helper = helpers.status || (depth0 != null ? depth0.status : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"status","hash":{},"data":data}) : helper)))
9105    + "</td>\n<td>"
9106    + alias4(((helper = (helper = helpers.ts || (depth0 != null ? depth0.ts : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"ts","hash":{},"data":data}) : helper)))
9107    + "</td>\n<td><a class=\"execute "
9108    + alias4(((helper = (helper = helpers.status || (depth0 != null ? depth0.status : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"status","hash":{},"data":data}) : helper)))
9109    + "\" data-name=\""
9110    + alias4(((helper = (helper = helpers.name || (depth0 != null ? depth0.name : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"name","hash":{},"data":data}) : helper)))
9111    + "\" title=\"Generate Report\">trigger</a></td>\n<td>"
9112    + ((stack1 = helpers["if"].call(alias1,(depth0 != null ? depth0.reportURL : depth0),{"name":"if","hash":{},"fn":container.program(1, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
9113    + "</td>\n</tr>\n";
9114},"useData":true});
9115
9116this["JST"]["handlebars/job-running.hbs"] = Handlebars.template({"compiler":[7,">= 4.0.0"],"main":function(container,depth0,helpers,partials,data) {
9117    var helper, alias1=depth0 != null ? depth0 : (container.nullContext || {}), alias2=helpers.helperMissing, alias3="function", alias4=container.escapeExpression;
9118
9119  return "<tr>\n<td>"
9120    + alias4(((helper = (helper = helpers.name || (depth0 != null ? depth0.name : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"name","hash":{},"data":data}) : helper)))
9121    + "</td>\n<td>"
9122    + alias4(((helper = (helper = helpers.status || (depth0 != null ? depth0.status : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"status","hash":{},"data":data}) : helper)))
9123    + " ...</td>\n<td>"
9124    + alias4(((helper = (helper = helpers.ts || (depth0 != null ? depth0.ts : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"ts","hash":{},"data":data}) : helper)))
9125    + "</td>\n<td><div class=\"running\">running ...</div></td>\n<td></td>\n</tr>\n";
9126},"useData":true});
9127
9128this["JST"]["handlebars/l3-doctor-profile-template.hbs"] = Handlebars.template({"1":function(container,depth0,helpers,partials,data) {
9129    var stack1;
9130
9131  return ((stack1 = (helpers.ifLessThan || (depth0 && depth0.ifLessThan) || helpers.helperMissing).call(depth0 != null ? depth0 : (container.nullContext || {}),(depth0 != null ? depth0.$index : depth0),8,{"name":"ifLessThan","hash":{},"fn":container.program(2, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "");
9132},"2":function(container,depth0,helpers,partials,data) {
9133    var stack1, helper, alias1=depth0 != null ? depth0 : (container.nullContext || {}), alias2=helpers.helperMissing, alias3=container.escapeExpression;
9134
9135  return "<div class=\"row\">\n<div class=\"l3-doctor-profile-wrapper col-xs-12\">\n\n<!--Physician Header-->\n<div class=\"doctor-profile-heading clearfix\">\n<div class=\"profile-head-wrapper\">\n<div class=\"doctor-hr hidden-xs\"></div>\n<a href=\""
9136    + alias3(((helper = (helper = helpers.url || (depth0 != null ? depth0.url : depth0)) != null ? helper : alias2),(typeof helper === "function" ? helper.call(alias1,{"name":"url","hash":{},"data":data}) : helper)))
9137    + "\" class=\"doctor-name\">"
9138    + ((stack1 = (helpers.decodeText || (depth0 && depth0.decodeText) || alias2).call(alias1,(depth0 != null ? depth0.displayName : depth0),{"name":"decodeText","hash":{},"data":data})) != null ? stack1 : "")
9139    + "</a>\n\n<!--Press Ganey ratings desktop, only shows if the physician has ratings-->\n"
9140    + ((stack1 = (helpers.ifNotContains || (depth0 && depth0.ifNotContains) || alias2).call(alias1,(depth0 != null ? depth0.hideRatings : depth0),"true",{"name":"ifNotContains","hash":{},"fn":container.program(3, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
9141    + "</div>\n\n<div class=\"doctor-specialty\">"
9142    + alias3((helpers.parseSpecialty || (depth0 && depth0.parseSpecialty) || alias2).call(alias1,(depth0 != null ? depth0.groupsToTitles : depth0),{"name":"parseSpecialty","hash":{},"data":data}))
9143    + "</div>\n"
9144    + ((stack1 = (helpers.ifNotEmpty || (depth0 && depth0.ifNotEmpty) || alias2).call(alias1,(depth0 != null ? depth0.primaryAcademicTitle : depth0),{"name":"ifNotEmpty","hash":{},"fn":container.program(6, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
9145    + "\n<!--Press Ganey ratings mobile, only shows if the physician has ratings-->\n"
9146    + ((stack1 = (helpers.ifNotContains || (depth0 && depth0.ifNotContains) || alias2).call(alias1,(depth0 != null ? depth0.hideRatings : depth0),"true",{"name":"ifNotContains","hash":{},"fn":container.program(8, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
9147    + "\n</div>\n\n<div class=\"column-wrapper clearfix\">\n\n<!--Physician Image-->\n"
9148    + ((stack1 = (helpers.ifNotEmpty || (depth0 && depth0.ifNotEmpty) || alias2).call(alias1,(depth0 != null ? depth0.imageUrl : depth0),{"name":"ifNotEmpty","hash":{},"fn":container.program(11, data, 0),"inverse":container.program(13, data, 0),"data":data})) != null ? stack1 : "")
9149    + "\n\n<!--Professional Education-->\n<div class=\"professional-education-wrapper\">\n<!--Only shows education if there is education to show, the wrapper remains to keep proper spacing-->\n"
9150    + ((stack1 = (helpers.ifNotEmpty || (depth0 && depth0.ifNotEmpty) || alias2).call(alias1,(depth0 != null ? depth0.education : depth0),{"name":"ifNotEmpty","hash":{},"fn":container.program(15, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
9151    + "</div>\n\n<!--Practice Areas-->\n<div class=\"practices-wrapper\">\n\n<!--Only shows Practice Areas if there are practice areas to show, the wrapper remains to keep proper spacing-->\n"
9152    + ((stack1 = (helpers.ifHasAtLeastOnePractice || (depth0 && depth0.ifHasAtLeastOnePractice) || alias2).call(alias1,(depth0 != null ? depth0.num_of_conditions : depth0),(depth0 != null ? depth0.num_of_medical_tests : depth0),(depth0 != null ? depth0.num_of_treatments : depth0),{"name":"ifHasAtLeastOnePractice","hash":{},"fn":container.program(21, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
9153    + "\n<!--Shows only if the physician should have Make An Appointment-->\n"
9154    + ((stack1 = (helpers.ifEqual || (depth0 && depth0.ifEqual) || alias2).call(alias1,((stack1 = ((stack1 = (depth0 != null ? depth0.contactInfo : depth0)) != null ? stack1["0"] : stack1)) != null ? stack1.hasMakeAnAppointment : stack1),"true",{"name":"ifEqual","hash":{},"fn":container.program(26, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
9155    + "</div>\n\n</div>\n\n</div>\n</div>\n";
9156},"3":function(container,depth0,helpers,partials,data) {
9157    var stack1;
9158
9159  return ((stack1 = (helpers.ifNotEmpty || (depth0 && depth0.ifNotEmpty) || helpers.helperMissing).call(depth0 != null ? depth0 : (container.nullContext || {}),(depth0 != null ? depth0.avg_rating : depth0),{"name":"ifNotEmpty","hash":{},"fn":container.program(4, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "");
9160},"4":function(container,depth0,helpers,partials,data) {
9161    var stack1, helper, alias1=depth0 != null ? depth0 : (container.nullContext || {}), alias2=helpers.helperMissing, alias3="function", alias4=container.escapeExpression;
9162
9163  return "<a href=\""
9164    + ((stack1 = ((helper = (helper = helpers.url || (depth0 != null ? depth0.url : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"url","hash":{},"data":data}) : helper))) != null ? stack1 : "")
9165    + "#reviews-content\" class=\"ratings-wrapper hidden-xs\">\n<div class=\"star-rating\">\n<div style=\"width: "
9166    + alias4((helpers.getStarWidth || (depth0 && depth0.getStarWidth) || alias2).call(alias1,(depth0 != null ? depth0.avg_rating : depth0),{"name":"getStarWidth","hash":{},"data":data}))
9167    + "\"></div>\n</div>\n<div class=\"number-rating\">"
9168    + alias4(((helper = (helper = helpers.avg_rating || (depth0 != null ? depth0.avg_rating : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"avg_rating","hash":{},"data":data}) : helper)))
9169    + " out of 5</div>\n</a>\n";
9170},"6":function(container,depth0,helpers,partials,data) {
9171    var stack1;
9172
9173  return "<div class=\"academic-title\">"
9174    + ((stack1 = (helpers.formatAcademicTitle || (depth0 && depth0.formatAcademicTitle) || helpers.helperMissing).call(depth0 != null ? depth0 : (container.nullContext || {}),(depth0 != null ? depth0.primaryAcademicTitle : depth0),{"name":"formatAcademicTitle","hash":{},"data":data})) != null ? stack1 : "")
9175    + "</div>\n";
9176},"8":function(container,depth0,helpers,partials,data) {
9177    var stack1;
9178
9179  return ((stack1 = (helpers.ifNotEmpty || (depth0 && depth0.ifNotEmpty) || helpers.helperMissing).call(depth0 != null ? depth0 : (container.nullContext || {}),(depth0 != null ? depth0.avg_rating : depth0),{"name":"ifNotEmpty","hash":{},"fn":container.program(9, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "");
9180},"9":function(container,depth0,helpers,partials,data) {
9181    var stack1, helper, alias1=depth0 != null ? depth0 : (container.nullContext || {}), alias2=helpers.helperMissing, alias3="function", alias4=container.escapeExpression;
9182
9183  return "<a href=\""
9184    + ((stack1 = ((helper = (helper = helpers.url || (depth0 != null ? depth0.url : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"url","hash":{},"data":data}) : helper))) != null ? stack1 : "")
9185    + "#reviews-content\" class=\"ratings-wrapper-mobile\">\n<div class=\"star-rating\">\n<div style=\"width: "
9186    + alias4((helpers.getStarWidth || (depth0 && depth0.getStarWidth) || alias2).call(alias1,(depth0 != null ? depth0.avg_rating : depth0),{"name":"getStarWidth","hash":{},"data":data}))
9187    + "\"></div>\n</div>\n<div class=\"number-rating\">"
9188    + alias4(((helper = (helper = helpers.avg_rating || (depth0 != null ? depth0.avg_rating : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"avg_rating","hash":{},"data":data}) : helper)))
9189    + " out of 5</div>\n</a>\n";
9190},"11":function(container,depth0,helpers,partials,data) {
9191    var helper, alias1=depth0 != null ? depth0 : (container.nullContext || {}), alias2=helpers.helperMissing, alias3="function", alias4=container.escapeExpression;
9192
9193  return "<a href=\""
9194    + alias4(((helper = (helper = helpers.url || (depth0 != null ? depth0.url : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"url","hash":{},"data":data}) : helper)))
9195    + "\" class=\"profile-image\">\n<img src=\""
9196    + alias4(((helper = (helper = helpers.imageUrl || (depth0 != null ? depth0.imageUrl : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"imageUrl","hash":{},"data":data}) : helper)))
9197    + "/jcr:content/renditions/original.transform/280x280-gray/image.jpg\" alt=\""
9198    + alias4((helpers.decodeText || (depth0 && depth0.decodeText) || alias2).call(alias1,(depth0 != null ? depth0.displayName : depth0),{"name":"decodeText","hash":{},"data":data}))
9199    + "\">\n</a>\n";
9200},"13":function(container,depth0,helpers,partials,data) {
9201    var stack1, helper;
9202
9203  return "<a href=\""
9204    + ((stack1 = ((helper = (helper = helpers.url || (depth0 != null ? depth0.url : depth0)) != null ? helper : helpers.helperMissing),(typeof helper === "function" ? helper.call(depth0 != null ? depth0 : (container.nullContext || {}),{"name":"url","hash":{},"data":data}) : helper))) != null ? stack1 : "")
9205    + "\" class=\"profile-image no-img-available\"><span></span></a>\n";
9206},"15":function(container,depth0,helpers,partials,data) {
9207    var stack1, alias1=depth0 != null ? depth0 : (container.nullContext || {}), alias2=helpers.helperMissing;
9208
9209  return "<div class=\"professional-education-header\">PROFESSIONAL EDUCATION</div>\n\n<ul class=\"education-list\">\n"
9210    + ((stack1 = (helpers.foreach || (depth0 && depth0.foreach) || alias2).call(alias1,(depth0 != null ? depth0.education : depth0),{"name":"foreach","hash":{},"fn":container.program(16, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
9211    + "</ul>\n\n"
9212    + ((stack1 = (helpers.ifGreaterThan || (depth0 && depth0.ifGreaterThan) || alias2).call(alias1,((stack1 = (depth0 != null ? depth0.education : depth0)) != null ? stack1.length : stack1),3,{"name":"ifGreaterThan","hash":{},"fn":container.program(19, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "");
9213},"16":function(container,depth0,helpers,partials,data) {
9214    var stack1;
9215
9216  return ((stack1 = (helpers.ifLessThan || (depth0 && depth0.ifLessThan) || helpers.helperMissing).call(depth0 != null ? depth0 : (container.nullContext || {}),(depth0 != null ? depth0.$index : depth0),3,{"name":"ifLessThan","hash":{},"fn":container.program(17, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "");
9217},"17":function(container,depth0,helpers,partials,data) {
9218    var stack1, helper;
9219
9220  return "<li>"
9221    + ((stack1 = ((helper = (helper = helpers.value || (depth0 != null ? depth0.value : depth0)) != null ? helper : helpers.helperMissing),(typeof helper === "function" ? helper.call(depth0 != null ? depth0 : (container.nullContext || {}),{"name":"value","hash":{},"data":data}) : helper))) != null ? stack1 : "")
9222    + "</li>\n";
9223},"19":function(container,depth0,helpers,partials,data) {
9224    var helper;
9225
9226  return "<div class=\"full-education\">\n<a href=\""
9227    + container.escapeExpression(((helper = (helper = helpers.url || (depth0 != null ? depth0.url : depth0)) != null ? helper : helpers.helperMissing),(typeof helper === "function" ? helper.call(depth0 != null ? depth0 : (container.nullContext || {}),{"name":"url","hash":{},"data":data}) : helper)))
9228    + "#professionalSummary\">View Full Education</a>\n</div>\n";
9229},"21":function(container,depth0,helpers,partials,data) {
9230    var stack1, alias1=depth0 != null ? depth0 : (container.nullContext || {}), alias2=helpers.helperMissing;
9231
9232  return "<div class=\"practices-header\">PRACTICE AREAS</div>\n<ul class=\"practices-list\">\n"
9233    + ((stack1 = (helpers.foreachThreeCombined || (depth0 && depth0.foreachThreeCombined) || alias2).call(alias1,(depth0 != null ? depth0.conditions : depth0),(depth0 != null ? depth0.medical_tests : depth0),(depth0 != null ? depth0.treatments : depth0),{"name":"foreachThreeCombined","hash":{},"fn":container.program(22, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
9234    + "</ul>\n\n<!--Shows when there are 4 or more Practice Areas-->\n"
9235    + ((stack1 = (helpers.ifMoreThanFourPractices || (depth0 && depth0.ifMoreThanFourPractices) || alias2).call(alias1,(depth0 != null ? depth0.num_of_conditions : depth0),(depth0 != null ? depth0.num_of_medical_tests : depth0),(depth0 != null ? depth0.num_of_treatments : depth0),{"name":"ifMoreThanFourPractices","hash":{},"fn":container.program(24, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "");
9236},"22":function(container,depth0,helpers,partials,data) {
9237    var stack1;
9238
9239  return ((stack1 = (helpers.ifLessThan || (depth0 && depth0.ifLessThan) || helpers.helperMissing).call(depth0 != null ? depth0 : (container.nullContext || {}),(depth0 != null ? depth0.index : depth0),3,{"name":"ifLessThan","hash":{},"fn":container.program(17, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "");
9240},"24":function(container,depth0,helpers,partials,data) {
9241    var helper, alias1=depth0 != null ? depth0 : (container.nullContext || {}), alias2=helpers.helperMissing, alias3=container.escapeExpression;
9242
9243  return "<div class=\"total-practices\">\n<a href=\""
9244    + alias3(((helper = (helper = helpers.url || (depth0 != null ? depth0.url : depth0)) != null ? helper : alias2),(typeof helper === "function" ? helper.call(alias1,{"name":"url","hash":{},"data":data}) : helper)))
9245    + "#specializingIn\">View All "
9246    + alias3((helpers.addThreeNumbers || (depth0 && depth0.addThreeNumbers) || alias2).call(alias1,(depth0 != null ? depth0.num_of_conditions : depth0),(depth0 != null ? depth0.num_of_medical_tests : depth0),(depth0 != null ? depth0.num_of_treatments : depth0),{"name":"addThreeNumbers","hash":{},"data":data}))
9247    + " Practice Areas</a>\n</div>\n";
9248},"26":function(container,depth0,helpers,partials,data) {
9249    var stack1;
9250
9251  return ((stack1 = (helpers.ifNotContains || (depth0 && depth0.ifNotContains) || helpers.helperMissing).call(depth0 != null ? depth0 : (container.nullContext || {}),((stack1 = ((stack1 = (depth0 != null ? depth0.contactInfo : depth0)) != null ? stack1["0"] : stack1)) != null ? stack1.OfficeName : stack1),"Emergency Department",{"name":"ifNotContains","hash":{},"fn":container.program(27, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "");
9252},"27":function(container,depth0,helpers,partials,data) {
9253    var stack1, alias1=depth0 != null ? depth0 : (container.nullContext || {}), alias2=helpers.helperMissing;
9254
9255  return ((stack1 = (helpers.ifEqual || (depth0 && depth0.ifEqual) || alias2).call(alias1,(depth0 != null ? depth0.isapp : depth0),"true",{"name":"ifEqual","hash":{},"fn":container.program(28, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
9256    + ((stack1 = (helpers.ifEqual || (depth0 && depth0.ifEqual) || alias2).call(alias1,(depth0 != null ? depth0.isapp : depth0),"false",{"name":"ifEqual","hash":{},"fn":container.program(29, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "");
9257},"28":function(container,depth0,helpers,partials,data) {
9258    var stack1, alias1=depth0 != null ? depth0 : (container.nullContext || {}), alias2=helpers.helperMissing;
9259
9260  return ((stack1 = (helpers.ifEqual || (depth0 && depth0.ifEqual) || alias2).call(alias1,(depth0 != null ? depth0.specialtyCarePhysician : depth0),"false",{"name":"ifEqual","hash":{},"fn":container.program(29, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
9261    + ((stack1 = (helpers.ifEqual || (depth0 && depth0.ifEqual) || alias2).call(alias1,(depth0 != null ? depth0.specialtyCarePhysician : depth0),"true",{"name":"ifEqual","hash":{},"fn":container.program(31, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "");
9262},"29":function(container,depth0,helpers,partials,data) {
9263    var stack1, helper, alias1=depth0 != null ? depth0 : (container.nullContext || {}), alias2=helpers.helperMissing, alias3="function", alias4=container.escapeExpression;
9264
9265  return "<div class=\"make-appointment-btn-wrapper\">\n<a href=\""
9266    + alias4(((helper = (helper = helpers.getCurrentPagePath || (depth0 != null ? depth0.getCurrentPagePath : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"getCurrentPagePath","hash":{},"data":data}) : helper)))
9267    + "\" class=\"make-appointment-btn open-modal\" data-modalcontainer=\".make-an-appt\" data-npi=\""
9268    + ((stack1 = ((helper = (helper = helpers.npi || (depth0 != null ? depth0.npi : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"npi","hash":{},"data":data}) : helper))) != null ? stack1 : "")
9269    + "\" data-url=\""
9270    + alias4(((helper = (helper = helpers.url || (depth0 != null ? depth0.url : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"url","hash":{},"data":data}) : helper)))
9271    + "\">MAKE AN APPOINTMENT </a>\n</div>\n";
9272},"31":function(container,depth0,helpers,partials,data) {
9273    var helper;
9274
9275  return "<div>\n<a href=\""
9276    + container.escapeExpression(((helper = (helper = helpers.url || (depth0 != null ? depth0.url : depth0)) != null ? helper : helpers.helperMissing),(typeof helper === "function" ? helper.call(depth0 != null ? depth0 : (container.nullContext || {}),{"name":"url","hash":{},"data":data}) : helper)))
9277    + "\">Learn more about this provider</a>\n</div>\n";
9278},"33":function(container,depth0,helpers,partials,data) {
9279    var helper;
9280
9281  return "<!--View More button shows when there are more than 8 physicians-->\n<div class=\"row\">\n<div class=\"view-more-wrapper col-xs-12\">\n<a href=\""
9282    + container.escapeExpression(((helper = (helper = helpers.getL3ClinicPassThroughUrl || (depth0 != null ? depth0.getL3ClinicPassThroughUrl : depth0)) != null ? helper : helpers.helperMissing),(typeof helper === "function" ? helper.call(depth0 != null ? depth0 : (container.nullContext || {}),{"name":"getL3ClinicPassThroughUrl","hash":{},"data":data}) : helper)))
9283    + "\" class=\"btn view-more-btn\">View More</a>\n</div>\n</div>\n";
9284},"compiler":[7,">= 4.0.0"],"main":function(container,depth0,helpers,partials,data) {
9285    var stack1, alias1=depth0 != null ? depth0 : (container.nullContext || {}), alias2=helpers.helperMissing;
9286
9287  return "<div class=\"l3-doctor-profile container\">\n"
9288    + ((stack1 = (helpers.foreach || (depth0 && depth0.foreach) || alias2).call(alias1,depth0,{"name":"foreach","hash":{},"fn":container.program(1, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
9289    + ((stack1 = (helpers.ifGreaterThan || (depth0 && depth0.ifGreaterThan) || alias2).call(alias1,(depth0 != null ? depth0.length : depth0),8,{"name":"ifGreaterThan","hash":{},"fn":container.program(33, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
9290    + "</div>\n";
9291},"useData":true});
9292
9293this["JST"]["handlebars/latest_press_release.hbs"] = Handlebars.template({"1":function(container,depth0,helpers,partials,data) {
9294    var stack1, helper, alias1=depth0 != null ? depth0 : (container.nullContext || {}), alias2=helpers.helperMissing, alias3="function", alias4=container.escapeExpression;
9295
9296  return "<div class=\"press-article row\">\n<div class=\"article-media col-sm-4 col-xs-4\">\n"
9297    + ((stack1 = (helpers.ifNotEmpty || (depth0 && depth0.ifNotEmpty) || alias2).call(alias1,(depth0 != null ? depth0.imageUrl : depth0),{"name":"ifNotEmpty","hash":{},"fn":container.program(2, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
9298    + "</div>\n<div class=\"article-content col-sm-8 col-xs-8\">\n<a href=\""
9299    + alias4(((helper = (helper = helpers.url || (depth0 != null ? depth0.url : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"url","hash":{},"data":data}) : helper)))
9300    + "\" class=\"article-title\" data-aa-latest-press-release-links=\""
9301    + alias4((helpers.toLowerCase || (depth0 && depth0.toLowerCase) || alias2).call(alias1,(depth0 != null ? depth0.displayName : depth0),{"name":"toLowerCase","hash":{},"data":data}))
9302    + "\">\n"
9303    + alias4(((helper = (helper = helpers.displayName || (depth0 != null ? depth0.displayName : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"displayName","hash":{},"data":data}) : helper)))
9304    + "\n</a>\n<div class=\"article-date\">\n"
9305    + ((stack1 = (helpers.longDateFormatter || (depth0 && depth0.longDateFormatter) || alias2).call(alias1,(depth0 != null ? depth0.pubDate : depth0),{"name":"longDateFormatter","hash":{},"fn":container.program(7, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
9306    + "</div>\n</div>\n</div>\n";
9307},"2":function(container,depth0,helpers,partials,data) {
9308    var stack1, helper, alias1=depth0 != null ? depth0 : (container.nullContext || {}), alias2=helpers.helperMissing, alias3="function", alias4=container.escapeExpression;
9309
9310  return "<a href=\""
9311    + alias4(((helper = (helper = helpers.url || (depth0 != null ? depth0.url : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"url","hash":{},"data":data}) : helper)))
9312    + "\">\n<img class='lazyload article-media-image center-img' data-src=\""
9313    + alias4(((helper = (helper = helpers.imageUrl || (depth0 != null ? depth0.imageUrl : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"imageUrl","hash":{},"data":data}) : helper)))
9314    + ((stack1 = (helpers.ifNotContains || (depth0 && depth0.ifNotContains) || alias2).call(alias1,(depth0 != null ? depth0.imageUrl : depth0),"http",{"name":"ifNotContains","hash":{},"fn":container.program(3, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
9315    + "\">\n"
9316    + ((stack1 = (helpers.ifContains || (depth0 && depth0.ifContains) || alias2).call(alias1,(depth0 != null ? depth0.mediaType : depth0),"video",{"name":"ifContains","hash":{},"fn":container.program(5, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
9317    + "</a>\n";
9318},"3":function(container,depth0,helpers,partials,data) {
9319    return ".img.png";
9320},"5":function(container,depth0,helpers,partials,data) {
9321    return "<img class=\"lazyload media-play-button center-img\" data-src=\"/etc/clientlibs/shc/main/svg/play.svg\">\n";
9322},"7":function(container,depth0,helpers,partials,data) {
9323    return "";
9324},"compiler":[7,">= 4.0.0"],"main":function(container,depth0,helpers,partials,data) {
9325    var stack1;
9326
9327  return ((stack1 = helpers.each.call(depth0 != null ? depth0 : (container.nullContext || {}),((stack1 = (depth0 != null ? depth0.results : depth0)) != null ? stack1.data : stack1),{"name":"each","hash":{},"fn":container.program(1, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "");
9328},"useData":true});
9329
9330this["JST"]["handlebars/listing-filters-template.hbs"] = Handlebars.template({"1":function(container,depth0,helpers,partials,data) {
9331    return "<li>\n<a href=\"#\">"
9332    + container.escapeExpression((helpers.urlDecode || (depth0 && depth0.urlDecode) || helpers.helperMissing).call(
vendor: 16,384 bytes, lines 9332-9484
9332depth0 != null ? depth0 : (container.nullContext || {}),(depth0 != null ? depth0.value : depth0),{"name":"urlDecode","hash":{},"data":data}))
9333    + "</a>\n</li>\n";
9334},"3":function(container,depth0,helpers,partials,data) {
9335    var helper;
9336
9337  return "<li>\n<a href=\"#\">"
9338    + container.escapeExpression(((helper = (helper = helpers.value || (depth0 != null ? depth0.value : depth0)) != null ? helper : helpers.helperMissing),(typeof helper === "function" ? helper.call(depth0 != null ? depth0 : (container.nullContext || {}),{"name":"value","hash":{},"data":data}) : helper)))
9339    + "</a>\n</li>\n";
9340},"compiler":[7,">= 4.0.0"],"main":function(container,depth0,helpers,partials,data) {
9341    var stack1, alias1=depth0 != null ? depth0 : (container.nullContext || {});
9342
9343  return "<div class=\"col-sm-4\">\n<div id=\"topics-filter\" class=\"dropdown\">\n<div class=\"toggle\">\n<span class=\"text\">Topics</span>\n<div class=\"carat\">\n<span class=\"icon\"></span>\n</div>\n</div>\n<ul>\n<li>\n<a href=\"#\">All Topics</a>\n</li>\n"
9344    + ((stack1 = helpers.each.call(alias1,((stack1 = (depth0 != null ? depth0.facets : depth0)) != null ? stack1.topic : stack1),{"name":"each","hash":{},"fn":container.program(1, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
9345    + "</ul>\n</div>\n</div>\n<div class=\"col-sm-4\">\n<div id=\"conditions-filter\" class=\"dropdown\">\n<div class=\"toggle\">\n<span class=\"text\">Conditions</span>\n<div class=\"carat\">\n<span class=\"icon\"></span>\n</div>\n</div>\n<ul>\n<li>\n<a href=\"#\">All Conditions</a>\n</li>\n"
9346    + ((stack1 = helpers.each.call(alias1,((stack1 = (depth0 != null ? depth0.facets : depth0)) != null ? stack1.category : stack1),{"name":"each","hash":{},"fn":container.program(3, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
9347    + "</ul>\n</div>\n</div>\n<div class=\"col-sm-4\">\n<div id=\"date-filter\" class=\"dropdown\">\n<div class=\"toggle\">\n<span class=\"text\">Date</span>\n<div class=\"carat\">\n<span class=\"icon\"></span>\n</div>\n</div>\n<ul>\n<li>\n<a href=\"#\">All Dates</a>\n</li>\n"
9348    + ((stack1 = helpers.each.call(alias1,((stack1 = (depth0 != null ? depth0.facets : depth0)) != null ? stack1.year : stack1),{"name":"each","hash":{},"fn":container.program(3, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
9349    + "</ul>\n</div>\n</div>\n";
9350},"useData":true});
9351
9352this["JST"]["handlebars/listing-paginating-template.hbs"] = Handlebars.template({"1":function(container,depth0,helpers,partials,data) {
9353    var stack1, helper, alias1=depth0 != null ? depth0 : (container.nullContext || {}), alias2=helpers.helperMissing, alias3="function", alias4=container.escapeExpression;
9354
9355  return "<div class=\"result "
9356    + ((stack1 = (helpers.ifNotEmpty || (depth0 && depth0.ifNotEmpty) || alias2).call(alias1,(depth0 != null ? depth0.imageUrl : depth0),{"name":"ifNotEmpty","hash":{},"fn":container.program(2, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
9357    + "\">\n"
9358    + ((stack1 = (helpers.ifNotEmpty || (depth0 && depth0.ifNotEmpty) || alias2).call(alias1,(depth0 != null ? depth0.imageUrl : depth0),{"name":"ifNotEmpty","hash":{},"fn":container.program(4, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
9359    + "<div class=\"result-info\">\n<a href=\""
9360    + alias4(((helper = (helper = helpers.url || (depth0 != null ? depth0.url : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"url","hash":{},"data":data}) : helper)))
9361    + "\" class=\"presentation\" data-presentation-container=\".article-presentation\">"
9362    + ((stack1 = ((helper = (helper = helpers.displayName || (depth0 != null ? depth0.displayName : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"displayName","hash":{},"data":data}) : helper))) != null ? stack1 : "")
9363    + "</a>\n<span class=\"date\">"
9364    + alias4(((helper = (helper = helpers.pubDate || (depth0 != null ? depth0.pubDate : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"pubDate","hash":{},"data":data}) : helper)))
9365    + "</span>\n</div>\n</div>\n";
9366},"2":function(container,depth0,helpers,partials,data) {
9367    return "has-image";
9368},"4":function(container,depth0,helpers,partials,data) {
9369    var stack1, helper, alias1=depth0 != null ? depth0 : (container.nullContext || {}), alias2=helpers.helperMissing, alias3="function", alias4=container.escapeExpression;
9370
9371  return "<div class=\"image-wrapper "
9372    + alias4(((helper = (helper = helpers.imageShape || (depth0 != null ? depth0.imageShape : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"imageShape","hash":{},"data":data}) : helper)))
9373    + "\">\n<a href=\""
9374    + alias4(((helper = (helper = helpers.url || (depth0 != null ? depth0.url : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"url","hash":{},"data":data}) : helper)))
9375    + "\" class=\"result-img presentation\" data-presentation-container=\".article-presentation\">\n<img src=\""
9376    + alias4(((helper = (helper = helpers.imageUrl || (depth0 != null ? depth0.imageUrl : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"imageUrl","hash":{},"data":data}) : helper)))
9377    + ((stack1 = (helpers.ifNotContains || (depth0 && depth0.ifNotContains) || alias2).call(alias1,(depth0 != null ? depth0.imageUrl : depth0),"http",{"name":"ifNotContains","hash":{},"fn":container.program(5, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
9378    + "\" alt=\"\" class=\""
9379    + alias4(((helper = (helper = helpers.crop || (depth0 != null ? depth0.crop : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"crop","hash":{},"data":data}) : helper)))
9380    + "\" />\n"
9381    + ((stack1 = (helpers.ifEqual || (depth0 && depth0.ifEqual) || alias2).call(alias1,(depth0 != null ? depth0.mediaType : depth0),"video",{"name":"ifEqual","hash":{},"fn":container.program(7, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
9382    + "\n</a>\n</div>\n";
9383},"5":function(container,depth0,helpers,partials,data) {
9384    return ".transform/234x234/q82/image.png";
9385},"7":function(container,depth0,helpers,partials,data) {
9386    return "<span class=\"play-btn\"></span>";
9387},"compiler":[7,">= 4.0.0"],"main":function(container,depth0,helpers,partials,data) {
9388    var stack1;
9389
9390  return ((stack1 = helpers.each.call(depth0 != null ? depth0 : (container.nullContext || {}),((stack1 = (depth0 != null ? depth0.results : depth0)) != null ? stack1.data : stack1),{"name":"each","hash":{},"fn":container.program(1, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "");
9391},"useData":true});
9392
9393this["JST"]["handlebars/listing-template.hbs"] = Handlebars.template({"1":function(container,depth0,helpers,partials,data) {
9394    return "s";
9395},"3":function(container,depth0,helpers,partials,data) {
9396    var stack1, helper, alias1=depth0 != null ? depth0 : (container.nullContext || {}), alias2=helpers.helperMissing, alias3="function", alias4=container.escapeExpression;
9397
9398  return "<div class=\"result "
9399    + ((stack1 = (helpers.ifNotEmpty || (depth0 && depth0.ifNotEmpty) || alias2).call(alias1,(depth0 != null ? depth0.imageUrl : depth0),{"name":"ifNotEmpty","hash":{},"fn":container.program(4, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
9400    + "\">\n"
9401    + ((stack1 = (helpers.ifNotEmpty || (depth0 && depth0.ifNotEmpty) || alias2).call(alias1,(depth0 != null ? depth0.imageUrl : depth0),{"name":"ifNotEmpty","hash":{},"fn":container.program(6, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
9402    + "<div class=\"result-info\">\n<a href=\""
9403    + alias4(((helper = (helper = helpers.url || (depth0 != null ? depth0.url : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"url","hash":{},"data":data}) : helper)))
9404    + "\" class=\"presentation\" data-presentation-container=\".article-presentation\">"
9405    + ((stack1 = ((helper = (helper = helpers.displayName || (depth0 != null ? depth0.displayName : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"displayName","hash":{},"data":data}) : helper))) != null ? stack1 : "")
9406    + "</a>\n<span class=\"date\">"
9407    + alias4(((helper = (helper = helpers.pubDate || (depth0 != null ? depth0.pubDate : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"pubDate","hash":{},"data":data}) : helper)))
9408    + "</span>\n</div>\n</div>\n";
9409},"4":function(container,depth0,helpers,partials,data) {
9410    return "has-image";
9411},"6":function(container,depth0,helpers,partials,data) {
9412    var stack1, helper, alias1=depth0 != null ? depth0 : (container.nullContext || {}), alias2=helpers.helperMissing, alias3="function", alias4=container.escapeExpression;
9413
9414  return "<div class=\"image-wrapper "
9415    + alias4(((helper = (helper = helpers.imageShape || (depth0 != null ? depth0.imageShape : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"imageShape","hash":{},"data":data}) : helper)))
9416    + "\">\n<a href=\""
9417    + alias4(((helper = (helper = helpers.url || (depth0 != null ? depth0.url : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"url","hash":{},"data":data}) : helper)))
9418    + "\" class=\"result-img presentation\" data-presentation-container=\".article-presentation\">\n<img src=\""
9419    + alias4(((helper = (helper = helpers.imageUrl || (depth0 != null ? depth0.imageUrl : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"imageUrl","hash":{},"data":data}) : helper)))
9420    + ((stack1 = (helpers.ifNotContains || (depth0 && depth0.ifNotContains) || alias2).call(alias1,(depth0 != null ? depth0.imageUrl : depth0),"http",{"name":"ifNotContains","hash":{},"fn":container.program(7, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
9421    + "\" alt=\"\" class=\""
9422    + alias4(((helper = (helper = helpers.crop || (depth0 != null ? depth0.crop : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"crop","hash":{},"data":data}) : helper)))
9423    + "\" />\n"
9424    + ((stack1 = (helpers.ifEqual || (depth0 && depth0.ifEqual) || alias2).call(alias1,(depth0 != null ? depth0.mediaType : depth0),"video",{"name":"ifEqual","hash":{},"fn":container.program(9, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
9425    + "\n</a>\n</div>\n";
9426},"7":function(container,depth0,helpers,partials,data) {
9427    return ".transform/234x234/q82/image.png";
9428},"9":function(container,depth0,helpers,partials,data) {
9429    return "<span class=\"play-btn\"></span>";
9430},"compiler":[7,">= 4.0.0"],"main":function(container,depth0,helpers,partials,data) {
9431    var stack1, alias1=depth0 != null ? depth0 : (container.nullContext || {});
9432
9433  return "<span class=\"count\">"
9434    + container.escapeExpression(container.lambda(((stack1 = (depth0 != null ? depth0.general : depth0)) != null ? stack1.total : stack1), depth0))
9435    + " News Update"
9436    + ((stack1 = (helpers.ifNotEqual || (depth0 && depth0.ifNotEqual) || helpers.helperMissing).call(alias1,((stack1 = (depth0 != null ? depth0.general : depth0)) != null ? stack1.total : stack1),"1",{"name":"ifNotEqual","hash":{},"fn":container.program(1, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
9437    + " Found</span>\n"
9438    + ((stack1 = helpers.each.call(alias1,((stack1 = (depth0 != null ? depth0.results : depth0)) != null ? stack1.data : stack1),{"name":"each","hash":{},"fn":container.program(3, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "");
9439},"useData":true});
9440
9441this["JST"]["handlebars/media-listing-template.hbs"] = Handlebars.template({"1":function(container,depth0,helpers,partials,data) {
9442    return "s";
9443},"3":function(container,depth0,helpers,partials,data) {
9444    var stack1, helper, alias1=depth0 != null ? depth0 : (container.nullContext || {}), alias2=helpers.helperMissing, alias3="function", alias4=container.escapeExpression;
9445
9446  return "<div class=\"result "
9447    + ((stack1 = (helpers.ifNotEmpty || (depth0 && depth0.ifNotEmpty) || alias2).call(alias1,(depth0 != null ? depth0.imageUrl : depth0),{"name":"ifNotEmpty","hash":{},"fn":container.program(4, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
9448    + "\">\n"
9449    + ((stack1 = (helpers.ifNotEmpty || (depth0 && depth0.ifNotEmpty) || alias2).call(alias1,(depth0 != null ? depth0.imageUrl : depth0),{"name":"ifNotEmpty","hash":{},"fn":container.program(6, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
9450    + "<div class=\"result-info\">\n<a href=\""
9451    + alias4(((helper = (helper = helpers.url || (depth0 != null ? depth0.url : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"url","hash":{},"data":data}) : helper)))
9452    + "\" class=\"presentation\" data-presentation-container=\".article-presentation\">"
9453    + ((stack1 = ((helper = (helper = helpers.displayName || (depth0 != null ? depth0.displayName : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"displayName","hash":{},"data":data}) : helper))) != null ? stack1 : "")
9454    + "</a>\n<span class=\"date\">"
9455    + alias4(((helper = (helper = helpers.pubDate || (depth0 != null ? depth0.pubDate : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"pubDate","hash":{},"data":data}) : helper)))
9456    + "</span>\n</div>\n</div>\n";
9457},"4":function(container,depth0,helpers,partials,data) {
9458    return "has-image";
9459},"6":function(container,depth0,helpers,partials,data) {
9460    var stack1, helper, alias1=depth0 != null ? depth0 : (container.nullContext || {}), alias2=helpers.helperMissing, alias3="function", alias4=container.escapeExpression;
9461
9462  return "<div class=\"image-wrapper "
9463    + alias4(((helper = (helper = helpers.imageShape || (depth0 != null ? depth0.imageShape : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"imageShape","hash":{},"data":data}) : helper)))
9464    + "\">\n<a href=\""
9465    + alias4(((helper = (helper = helpers.url || (depth0 != null ? depth0.url : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"url","hash":{},"data":data}) : helper)))
9466    + "\" class=\"result-img presentation\" data-presentation-container=\".article-presentation\">\n<img src=\""
9467    + alias4(((helper = (helper = helpers.imageUrl || (depth0 != null ? depth0.imageUrl : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"imageUrl","hash":{},"data":data}) : helper)))
9468    + ((stack1 = (helpers.ifNotContains || (depth0 && depth0.ifNotContains) || alias2).call(alias1,(depth0 != null ? depth0.imageUrl : depth0),"http",{"name":"ifNotContains","hash":{},"fn":container.program(7, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
9469    + "\" alt=\"\" class=\""
9470    + alias4(((helper = (helper = helpers.crop || (depth0 != null ? depth0.crop : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"crop","hash":{},"data":data}) : helper)))
9471    + "\" />\n"
9472    + ((stack1 = (helpers.ifEqual || (depth0 && depth0.ifEqual) || alias2).call(alias1,(depth0 != null ? depth0.mediaType : depth0),"video",{"name":"ifEqual","hash":{},"fn":container.program(9, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
9473    + "\n</a>\n</div>\n";
9474},"7":function(container,depth0,helpers,partials,data) {
9475    return ".transform/234x234/q82/image.png";
9476},"9":function(container,depth0,helpers,partials,data) {
9477    return "<span class=\"play-btn\"></span>";
9478},"compiler":[7,">= 4.0.0"],"main":function(container,depth0,helpers,partials,data) {
9479    var stack1, alias1=depth0 != null ? depth0 : (container.nullContext || {});
9480
9481  return "<span class=\"count\">"
9482    + container.escapeExpression(container.lambda(((stack1 = (depth0 != null ? depth0.general : depth0)) != null ? stack1.total : stack1), depth0))
9483    + " Item"
9484    + ((stack1 = (helpers.ifNotEqual || (de
vendor: 47,337 bytes, lines 9484-9916
9484pth0 && depth0.ifNotEqual) || helpers.helperMissing).call(alias1,((stack1 = (depth0 != null ? depth0.general : depth0)) != null ? stack1.total : stack1),"1",{"name":"ifNotEqual","hash":{},"fn":container.program(1, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
9485    + " Found</span>\n"
9486    + ((stack1 = helpers.each.call(alias1,((stack1 = (depth0 != null ? depth0.results : depth0)) != null ? stack1.data : stack1),{"name":"each","hash":{},"fn":container.program(3, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "");
9487},"useData":true});
9488
9489this["JST"]["handlebars/newsroom-landing-list-template.hbs"] = Handlebars.template({"compiler":[7,">= 4.0.0"],"main":function(container,depth0,helpers,partials,data) {
9490    return "<div class=\"collection directory\">\nNewsroom Landing List Template Placeholder\n</div>\n";
9491},"useData":true});
9492
9493this["JST"]["handlebars/pc-error-template.hbs"] = Handlebars.template({"compiler":[7,">= 4.0.0"],"main":function(container,depth0,helpers,partials,data) {
9494    return "<div class=\"error-results-top\">\n<div class=\"error-results-title\">NO RESULTS FOUND</div>\n</div>\n<div class=\"ipc-error \">\n<p>Sorry, there were no search results that matched your criteria.\nYou may want to try your search again with a different criteria,\nsuch as a new region or specialty.</p>\n<div class=\"row error-see-more-link-row\">\n<div class=\"col-lg-12 col-md-12 col-sm-12 col-xs-12\">\n<a class=\"see-all-results\" href=\"#\"><div class=\"list-footer\">SEE ALL LOCATIONS</div></a>\n</div>\n</div>\n</div>\n";
9495},"useData":true});
9496
9497this["JST"]["handlebars/pc-info-window-template.hbs"] = Handlebars.template({"1":function(container,depth0,helpers,partials,data) {
9498    return " has-image";
9499},"3":function(container,depth0,helpers,partials,data) {
9500    var stack1, helper, alias1=depth0 != null ? depth0 : (container.nullContext || {}), alias2=helpers.helperMissing, alias3="function", alias4=container.escapeExpression;
9501
9502  return "<div class=\"image-container\">\n<img src=\""
9503    + alias4(((helper = (helper = helpers.image || (depth0 != null ? depth0.image : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"image","hash":{},"data":data}) : helper)))
9504    + ((stack1 = (helpers.ifNotContains || (depth0 && depth0.ifNotContains) || alias2).call(alias1,(depth0 != null ? depth0.image : depth0),"http",{"name":"ifNotContains","hash":{},"fn":container.program(4, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
9505    + "\" alt=\""
9506    + alias4(((helper = (helper = helpers.imageAltText || (depth0 != null ? depth0.imageAltText : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"imageAltText","hash":{},"data":data}) : helper)))
9507    + "\" class=\"info-window-image\"/>\n</div>\n";
9508},"4":function(container,depth0,helpers,partials,data) {
9509    return ".transform/221x221/q82/image.png";
9510},"6":function(container,depth0,helpers,partials,data) {
9511    var helper;
9512
9513  return container.escapeExpression(((helper = (helper = helpers.address2 || (depth0 != null ? depth0.address2 : depth0)) != null ? helper : helpers.helperMissing),(typeof helper === "function" ? helper.call(depth0 != null ? depth0 : (container.nullContext || {}),{"name":"address2","hash":{},"data":data}) : helper)))
9514    + "<br>\n";
9515},"compiler":[7,">= 4.0.0"],"main":function(container,depth0,helpers,partials,data) {
9516    var stack1, helper, alias1=depth0 != null ? depth0 : (container.nullContext || {}), alias2=helpers.helperMissing, alias3="function", alias4=container.escapeExpression;
9517
9518  return "<div class=\"info-window clearfix"
9519    + ((stack1 = (helpers.ifNotEmpty || (depth0 && depth0.ifNotEmpty) || alias2).call(alias1,(depth0 != null ? depth0.image : depth0),{"name":"ifNotEmpty","hash":{},"fn":container.program(1, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
9520    + "\">\n"
9521    + ((stack1 = (helpers.ifNotEmpty || (depth0 && depth0.ifNotEmpty) || alias2).call(alias1,(depth0 != null ? depth0.image : depth0),{"name":"ifNotEmpty","hash":{},"fn":container.program(3, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
9522    + "<div class=\"info-window-details"
9523    + ((stack1 = (helpers.ifNotEmpty || (depth0 && depth0.ifNotEmpty) || alias2).call(alias1,(depth0 != null ? depth0.image : depth0),{"name":"ifNotEmpty","hash":{},"fn":container.program(1, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
9524    + "\">\n<a href=\""
9525    + alias4(((helper = (helper = helpers.pagePath || (depth0 != null ? depth0.pagePath : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"pagePath","hash":{},"data":data}) : helper)))
9526    + "\" class=\"info-window-title\">"
9527    + alias4(((helper = (helper = helpers.title || (depth0 != null ? depth0.title : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"title","hash":{},"data":data}) : helper)))
9528    + "</a>\n<span class=\"info-window-address\">\n"
9529    + alias4(((helper = (helper = helpers.address || (depth0 != null ? depth0.address : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"address","hash":{},"data":data}) : helper)))
9530    + "<br>\n"
9531    + ((stack1 = (helpers.ifNotEmpty || (depth0 && depth0.ifNotEmpty) || alias2).call(alias1,(depth0 != null ? depth0.address2 : depth0),{"name":"ifNotEmpty","hash":{},"fn":container.program(6, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
9532    + "</span>\n<div class=\"address-line-2\">\n<span class=\"info-window-city\">"
9533    + alias4(((helper = (helper = helpers.city || (depth0 != null ? depth0.city : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"city","hash":{},"data":data}) : helper)))
9534    + ",</span>\n<span class=\"info-window-state\">"
9535    + alias4(((helper = (helper = helpers.state || (depth0 != null ? depth0.state : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"state","hash":{},"data":data}) : helper)))
9536    + "&nbsp"
9537    + alias4(((helper = (helper = helpers.zipcode || (depth0 != null ? depth0.zipcode : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"zipcode","hash":{},"data":data}) : helper)))
9538    + "</span><br>\n<span class=\"info-window-phone\"><a href=\"tel://"
9539    + alias4(((helper = (helper = helpers.phone || (depth0 != null ? depth0.phone : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"phone","hash":{},"data":data}) : helper)))
9540    + "\" class=\"pc-phone\">"
9541    + alias4(((helper = (helper = helpers.phone || (depth0 != null ? depth0.phone : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"phone","hash":{},"data":data}) : helper)))
9542    + "</a></span>\n</div>\n<a href=\""
9543    + alias4(((helper = (helper = helpers.locationDetails || (depth0 != null ? depth0.locationDetails : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"locationDetails","hash":{},"data":data}) : helper)))
9544    + "\" class=\"info-window-modal info-window-location open-modal-primary-care\">Getting&nbsp;Here&nbsp;</a>\n<a href=\""
9545    + alias4(((helper = (helper = helpers.pagePath || (depth0 != null ? depth0.pagePath : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"pagePath","hash":{},"data":data}) : helper)))
9546    + "\" class=\"info-window-modal info-window-location open-modal-primary-care\" data-modalcontainer=\".make-an-appt\">Make&nbsp;an&nbsp;Appointment&nbsp;</a>\n</div>\n</div>\n";
9547},"useData":true});
9548
9549this["JST"]["handlebars/practice-locations-list-handlebar.hbs"] = Handlebars.template({"1":function(container,depth0,helpers,partials,data) {
9550    var stack1, helper, alias1=depth0 != null ? depth0 : (container.nullContext || {}), alias2=helpers.helperMissing, alias3="function", alias4=container.escapeExpression;
9551
9552  return "<div class=\"row location-result\">\n<div class=\"col-lg-4 col-md-4 col-sm-4 col-xs-12\">\n<h4 class=\"blue-header\"><a href=\""
9553    + alias4(((helper = (helper = helpers.pagePath || (depth0 != null ? depth0.pagePath : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"pagePath","hash":{},"data":data}) : helper)))
9554    + "\">"
9555    + alias4(((helper = (helper = helpers.title || (depth0 != null ? depth0.title : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"title","hash":{},"data":data}) : helper)))
9556    + "</a></h4>\n<span>\n"
9557    + alias4(((helper = (helper = helpers.address || (depth0 != null ? depth0.address : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"address","hash":{},"data":data}) : helper)))
9558    + "<br>\n"
9559    + ((stack1 = (helpers.ifNotEmpty || (depth0 && depth0.ifNotEmpty) || alias2).call(alias1,(depth0 != null ? depth0.address2 : depth0),{"name":"ifNotEmpty","hash":{},"fn":container.program(2, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
9560    + "</span>\n<span>"
9561    + alias4(((helper = (helper = helpers.city || (depth0 != null ? depth0.city : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"city","hash":{},"data":data}) : helper)))
9562    + ", "
9563    + alias4(((helper = (helper = helpers.state || (depth0 != null ? depth0.state : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"state","hash":{},"data":data}) : helper)))
9564    + " "
9565    + alias4(((helper = (helper = helpers.zipcode || (depth0 != null ? depth0.zipcode : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"zipcode","hash":{},"data":data}) : helper)))
9566    + "</span>\n<span>Phone: <a href=\"tel://"
9567    + alias4(((helper = (helper = helpers.phone || (depth0 != null ? depth0.phone : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"phone","hash":{},"data":data}) : helper)))
9568    + "\">"
9569    + alias4(((helper = (helper = helpers.phone || (depth0 != null ? depth0.phone : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"phone","hash":{},"data":data}) : helper)))
9570    + "</a></span>\n<a href="
9571    + alias4(((helper = (helper = helpers.locationDetails || (depth0 != null ? depth0.locationDetails : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"locationDetails","hash":{},"data":data}) : helper)))
9572    + " class=\"open-modal-primary-care\"><h4 class=\"blue-header getting-here\">Getting Here</h4></a>\n</div>\n<div class=\"col-lg-4 col-md-4 col-sm-4 col-xs-12\">\n<h4>Services offered:</h4>\n<ul>"
9573    + ((stack1 = helpers.each.call(alias1,(depth0 != null ? depth0.specialties : depth0),{"name":"each","hash":{},"fn":container.program(4, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
9574    + "</ul>\n</div>\n<div class=\"col-lg-4 col-md-4 col-sm-4 col-xs-12 \">\n<button href=\""
9575    + alias4(((helper = (helper = helpers.relativePath || (depth0 != null ? depth0.relativePath : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"relativePath","hash":{},"data":data}) : helper)))
9576    + "\" class=\"btn inline-table btn-default open-modal-primary-care\" data-modalcontainer=\".make-an-appt\">MAKE AN APPOINTMENT</button>\n</div>\n</div>\n<hr>\n";
9577},"2":function(container,depth0,helpers,partials,data) {
9578    var helper;
9579
9580  return container.escapeExpression(((helper = (helper = helpers.address2 || (depth0 != null ? depth0.address2 : depth0)) != null ? helper : helpers.helperMissing),(typeof helper === "function" ? helper.call(depth0 != null ? depth0 : (container.nullContext || {}),{"name":"address2","hash":{},"data":data}) : helper)))
9581    + "<br>\n";
9582},"4":function(container,depth0,helpers,partials,data) {
9583    return "\n<li><span>"
9584    + container.escapeExpression(container.lambda((depth0 != null ? depth0.value : depth0), depth0))
9585    + "</span></li>\n";
9586},"compiler":[7,">= 4.0.0"],"main":function(container,depth0,helpers,partials,data) {
9587    var stack1;
9588
9589  return ((stack1 = helpers.each.call(depth0 != null ? depth0 : (container.nullContext || {}),depth0,{"name":"each","hash":{},"fn":container.program(1, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "");
9590},"useData":true});
9591
9592this["JST"]["handlebars/primary-care-handlebar-all.hbs"] = Handlebars.template({"1":function(container,depth0,helpers,partials,data) {
9593    var stack1;
9594
9595  return ((stack1 = helpers.each.call(depth0 != null ? depth0 : (container.nullContext || {}),(depth0 != null ? depth0.maplocations : depth0),{"name":"each","hash":{},"fn":container.program(2, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
9596    + "\n<div class=\"row see-more-link-row-all\">\n<div class=\"col-lg-12 col-md-12 col-sm-12 col-xs-12\">\n<a class=\"see-more-link-all\" href=\"#\"><div class=\"list-footer\">SEE MORE RESULTS</div></a>\n</div>\n</div>\n";
9597},"2":function(container,depth0,helpers,partials,data) {
9598    var stack1, helper, alias1=depth0 != null ? depth0 : (container.nullContext || {}), alias2=helpers.helperMissing, alias3="function", alias4=container.escapeExpression;
9599
9600  return ((stack1 = (helpers.ifGreaterThan || (depth0 && depth0.ifGreaterThan) || alias2).call(alias1,(data && data.index),"8",{"name":"ifGreaterThan","hash":{},"fn":container.program(3, data, 0),"inverse":container.program(6, data, 0),"data":data})) != null ? stack1 : "")
9601    + "<div class=\"col-lg-4 col-md-4 col-sm-4 col-xs-12\">\n<h4 class=\"blue-header\"><a href=\""
9602    + alias4(((helper = (helper = helpers.pagePath || (depth0 != null ? depth0.pagePath : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"pagePath","hash":{},"data":data}) : helper)))
9603    + "\">"
9604    + alias4(((helper = (helper = helpers.title || (depth0 != null ? depth0.title : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"title","hash":{},"data":data}) : helper)))
9605    + "</a></h4>\n<span>\n"
9606    + alias4(((helper = (helper = helpers.address || (depth0 != null ? depth0.address : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"address","hash":{},"data":data}) : helper)))
9607    + "<br>\n"
9608    + ((stack1 = (helpers.ifNotEmpty || (depth0 && depth0.ifNotEmpty) || alias2).call(alias1,(depth0 != null ? depth0.address2 : depth0),{"name":"ifNotEmpty","hash":{},"fn":container.program(8, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
9609    + "</span>\n<span>"
9610    + alias4(((helper = (helper = helpers.city || (depth0 != null ? depth0.city : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"city","hash":{},"data":data}) : helper)))
9611    + ", "
9612    + alias4(((helper = (helper = helpers.state || (depth0 != null ? depth0.state : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"state","hash":{},"data":data}) : helper)))
9613    + " "
9614    + alias4(((helper = (helper = helpers.zipcode || (depth0 != null ? depth0.zipcode : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"zipcode","hash":{},"data":data}) : helper)))
9615    + "</span>\n<span>Phone: <a href=\"tel://"
9616    + alias4(((helper = (helper = helpers.phone || (depth0 != null ? depth0.phone : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"phone","hash":{},"data":data}) : helper)))
9617    + "\" class=\"pc-phone\">"
9618    + alias4(((helper = (helper = helpers.phone || (depth0 != null ? depth0.phone : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"phone","hash":{},"data":data}) : helper)))
9619    + "</a></span>\n<a href="
9620    + alias4(((helper = (helper = helpers.locationDetails || (depth0 != null ? depth0.locationDetails : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"locationDetails","hash":{},"data":data}) : helper)))
9621    + " class=\"open-modal-primary-care\"><h4 class=\"blue-header getting-here\">Getting Here</h4></a>\n</div>\n<div class=\"col-lg-4 col-md-4 col-sm-4 col-xs-12\">\n<h4>Services offered:</h4>\n<ul>"
9622    + ((stack1 = helpers.each.call(alias1,(depth0 != null ? depth0.specialties : depth0),{"name":"each","hash":{},"fn":container.program(10, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
9623    + "</ul>\n</div>\n<div class=\"col-lg-4 col-md-4 col-sm-4 col-xs-12 \">\n<button href=\""
9624    + alias4(((helper = (helper = helpers.pagePath || (depth0 != null ? depth0.pagePath : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"pagePath","hash":{},"data":data}) : helper)))
9625    + "\" class=\"btn inline-table btn-default open-modal-primary-care\" data-modalcontainer=\".make-an-appt\">MAKE AN APPOINTMENT</button>\n</div>\n</div>\n\n"
9626    + ((stack1 = (helpers.ifGreaterThan || (depth0 && depth0.ifGreaterThan) || alias2).call(alias1,(data && data.index),"8",{"name":"ifGreaterThan","hash":{},"fn":container.program(12, data, 0),"inverse":container.program(14, data, 0),"data":data})) != null ? stack1 : "");
9627},"3":function(container,depth0,helpers,partials,data) {
9628    var stack1;
9629
9630  return "<div class=\"row location-result more "
9631    + ((stack1 = helpers["if"].call(depth0 != null ? depth0 : (container.nullContext || {}),(data && data.last),{"name":"if","hash":{},"fn":container.program(4, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
9632    + "\">\n";
9633},"4":function(container,depth0,helpers,partials,data) {
9634    return "last";
9635},"6":function(container,depth0,helpers,partials,data) {
9636    var stack1;
9637
9638  return "<div class=\"row location-result showing "
9639    + ((stack1 = (helpers.ifEqual || (depth0 && depth0.ifEqual) || helpers.helperMissing).call(depth0 != null ? depth0 : (container.nullContext || {}),8,(data && data.index),{"name":"ifEqual","hash":{},"fn":container.program(4, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
9640    + "\">\n";
9641},"8":function(container,depth0,helpers,partials,data) {
9642    var helper;
9643
9644  return container.escapeExpression(((helper = (helper = helpers.address2 || (depth0 != null ? depth0.address2 : depth0)) != null ? helper : helpers.helperMissing),(typeof helper === "function" ? helper.call(depth0 != null ? depth0 : (container.nullContext || {}),{"name":"address2","hash":{},"data":data}) : helper)))
9645    + "<br>\n";
9646},"10":function(container,depth0,helpers,partials,data) {
9647    return "\n<li><span>"
9648    + container.escapeExpression(container.lambda((depth0 != null ? depth0.value : depth0), depth0))
9649    + "</span></li>\n";
9650},"12":function(container,depth0,helpers,partials,data) {
9651    var stack1;
9652
9653  return "<hr class=\"more "
9654    + ((stack1 = helpers["if"].call(depth0 != null ? depth0 : (container.nullContext || {}),(data && data.last),{"name":"if","hash":{},"fn":container.program(4, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
9655    + "\">\n";
9656},"14":function(container,depth0,helpers,partials,data) {
9657    var stack1;
9658
9659  return "<hr class=\"showing "
9660    + ((stack1 = (helpers.ifEqual || (depth0 && depth0.ifEqual) || helpers.helperMissing).call(depth0 != null ? depth0 : (container.nullContext || {}),8,(data && data.index),{"name":"ifEqual","hash":{},"fn":container.program(4, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
9661    + "\">\n";
9662},"16":function(container,depth0,helpers,partials,data) {
9663    var stack1;
9664
9665  return ((stack1 = helpers.each.call(depth0 != null ? depth0 : (container.nullContext || {}),(depth0 != null ? depth0.maplocations : depth0),{"name":"each","hash":{},"fn":container.program(17, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "");
9666},"17":function(container,depth0,helpers,partials,data) {
9667    var stack1, helper, alias1=depth0 != null ? depth0 : (container.nullContext || {}), alias2=helpers.helperMissing, alias3="function", alias4=container.escapeExpression;
9668
9669  return "<div class=\"row location-result showing "
9670    + ((stack1 = helpers["if"].call(alias1,(data && data.last),{"name":"if","hash":{},"fn":container.program(4, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
9671    + "\">\n<div class=\"col-lg-4 col-md-4 col-sm-4 col-xs-12\">\n<h4 class=\"blue-header\">"
9672    + alias4(((helper = (helper = helpers.title || (depth0 != null ? depth0.title : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"title","hash":{},"data":data}) : helper)))
9673    + "</h4>\n<span>\n"
9674    + alias4(((helper = (helper = helpers.address || (depth0 != null ? depth0.address : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"address","hash":{},"data":data}) : helper)))
9675    + "<br>\n"
9676    + ((stack1 = (helpers.ifNotEmpty || (depth0 && depth0.ifNotEmpty) || alias2).call(alias1,(depth0 != null ? depth0.address2 : depth0),{"name":"ifNotEmpty","hash":{},"fn":container.program(8, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
9677    + "</span>\n<span>"
9678    + alias4(((helper = (helper = helpers.city || (depth0 != null ? depth0.city : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"city","hash":{},"data":data}) : helper)))
9679    + ", "
9680    + alias4(((helper = (helper = helpers.state || (depth0 != null ? depth0.state : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"state","hash":{},"data":data}) : helper)))
9681    + " "
9682    + alias4(((helper = (helper = helpers.zipcode || (depth0 != null ? depth0.zipcode : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"zipcode","hash":{},"data":data}) : helper)))
9683    + "</span>\n<span>Phone: <a href=\"tel://"
9684    + alias4(((helper = (helper = helpers.phone || (depth0 != null ? depth0.phone : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"phone","hash":{},"data":data}) : helper)))
9685    + "\" class=\"pc-phone\">"
9686    + alias4(((helper = (helper = helpers.phone || (depth0 != null ? depth0.phone : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"phone","hash":{},"data":data}) : helper)))
9687    + "</a></span>\n<a href="
9688    + alias4(((helper = (helper = helpers.locationDetails || (depth0 != null ? depth0.locationDetails : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"locationDetails","hash":{},"data":data}) : helper)))
9689    + " class=\"open-modal-primary-care\"><h4 class=\"blue-header getting-here\">Getting Here</h4></a>\n</div>\n<div class=\"col-lg-4 col-md-4 col-sm-4 col-xs-12\">\n<h4>Services offered:</h4>\n<ul>"
9690    + ((stack1 = helpers.each.call(alias1,(depth0 != null ? depth0.specialties : depth0),{"name":"each","hash":{},"fn":container.program(10, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
9691    + "</ul>\n</div>\n<div class=\"col-lg-4 col-md-4 col-sm-4 col-xs-12 \">\n<button href=\""
9692    + alias4(((helper = (helper = helpers.pagePath || (depth0 != null ? depth0.pagePath : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"pagePath","hash":{},"data":data}) : helper)))
9693    + "\" class=\"btn inline-table btn-default open-modal-primary-care\" data-modalcontainer=\".make-an-appt\">MAKE AN APPOINTMENT</button>\n</div>\n</div>\n<hr class=\"showing "
9694    + ((stack1 = helpers["if"].call(alias1,(data && data.last),{"name":"if","hash":{},"fn":container.program(4, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
9695    + "\">\n";
9696},"compiler":[7,">= 4.0.0"],"main":function(container,depth0,helpers,partials,data) {
9697    var stack1;
9698
9699  return ((stack1 = (helpers.ifGreaterThan || (depth0 && depth0.ifGreaterThan) || helpers.helperMissing).call(depth0 != null ? depth0 : (container.nullContext || {}),((stack1 = (depth0 != null ? depth0.maplocations : depth0)) != null ? stack1.length : stack1),9,{"name":"ifGreaterThan","hash":{},"fn":container.program(1, data, 0),"inverse":container.program(16, data, 0),"data":data})) != null ? stack1 : "");
9700},"useData":true});
9701
9702this["JST"]["handlebars/primary-care-handlebar.hbs"] = Handlebars.template({"1":function(container,depth0,helpers,partials,data) {
9703    var stack1;
9704
9705  return ((stack1 = helpers.each.call(depth0 != null ? depth0 : (container.nullContext || {}),depth0,{"name":"each","hash":{},"fn":container.program(2, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
9706    + "\n<div class=\"row see-more-link-row\">\n<div class=\"col-lg-12 col-md-12 col-sm-12 col-xs-12\">\n<a class=\"see-more-link\" href=\"#\"><div class=\"list-footer\">SEE MORE RESULTS</div></a>\n</div>\n</div>\n";
9707},"2":function(container,depth0,helpers,partials,data) {
9708    var stack1, helper, alias1=depth0 != null ? depth0 : (container.nullContext || {}), alias2=helpers.helperMissing, alias3=container.lambda, alias4=container.escapeExpression;
9709
9710  return ((stack1 = (helpers.ifGreaterThan || (depth0 && depth0.ifGreaterThan) || alias2).call(alias1,(data && data.index),"2",{"name":"ifGreaterThan","hash":{},"fn":container.program(3, data, 0),"inverse":container.program(6, data, 0),"data":data})) != null ? stack1 : "")
9711    + "<div class=\"col-lg-4 col-md-4 col-sm-4 col-xs-12\">\n<h4 class=\"blue-header\"><a href=\""
9712    + alias4(alias3(((stack1 = (depth0 != null ? depth0.chunk : depth0)) != null ? stack1.pagePath : stack1), depth0))
9713    + "\">"
9714    + alias4(alias3(((stack1 = (depth0 != null ? depth0.chunk : depth0)) != null ? stack1.title : stack1), depth0))
9715    + "</a></h4>\n<span class=\"zipcode\">("
9716    + alias4(((helper = (helper = helpers.inZip || (depth0 != null ? depth0.inZip : depth0)) != null ? helper : alias2),(typeof helper === "function" ? helper.call(alias1,{"name":"inZip","hash":{},"data":data}) : helper)))
9717    + ")</span>\n<span>\n"
9718    + alias4(alias3(((stack1 = (depth0 != null ? depth0.chunk : depth0)) != null ? stack1.address : stack1), depth0))
9719    + "<br>\n"
9720    + ((stack1 = (helpers.ifNotEmpty || (depth0 && depth0.ifNotEmpty) || alias2).call(alias1,((stack1 = (depth0 != null ? depth0.chunk : depth0)) != null ? stack1.address2 : stack1),{"name":"ifNotEmpty","hash":{},"fn":container.program(8, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
9721    + "</span>\n<span>"
9722    + alias4(alias3(((stack1 = (depth0 != null ? depth0.chunk : depth0)) != null ? stack1.city : stack1), depth0))
9723    + ", "
9724    + alias4(alias3(((stack1 = (depth0 != null ? depth0.chunk : depth0)) != null ? stack1.state : stack1), depth0))
9725    + " "
9726    + alias4(alias3(((stack1 = (depth0 != null ? depth0.chunk : depth0)) != null ? stack1.zipcode : stack1), depth0))
9727    + "</span>\n<span>Phone: <a href=\"tel://"
9728    + alias4(alias3(((stack1 = (depth0 != null ? depth0.chunk : depth0)) != null ? stack1.phone : stack1), depth0))
9729    + "\" class=\"pc-phone\">"
9730    + alias4(alias3(((stack1 = (depth0 != null ? depth0.chunk : depth0)) != null ? stack1.phone : stack1), depth0))
9731    + "</a></span>\n<a href="
9732    + alias4(alias3(((stack1 = (depth0 != null ? depth0.chunk : depth0)) != null ? stack1.locationDetails : stack1), depth0))
9733    + " class=\"open-modal-primary-care\"><h4 class=\"blue-header getting-here\">Getting Here</h4></a>\n</div>\n<div class=\"col-lg-4 col-md-4 col-sm-4 col-xs-12\">\n<h4>Services offered:</h4>\n<ul>"
9734    + ((stack1 = helpers.each.call(alias1,((stack1 = (depth0 != null ? depth0.chunk : depth0)) != null ? stack1.specialties : stack1),{"name":"each","hash":{},"fn":container.program(10, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
9735    + "</ul>\n</div>\n<div class=\"col-lg-4 col-md-4 col-sm-4 col-xs-12 \">\n<button href=\""
9736    + alias4(alias3(((stack1 = (depth0 != null ? depth0.chunk : depth0)) != null ? stack1.pagePath : stack1), depth0))
9737    + "\" class=\"btn inline-table btn-default open-modal-primary-care\" data-modalcontainer=\".make-an-appt\">MAKE AN APPOINTMENT</button>\n</div>\n</div>\n\n"
9738    + ((stack1 = (helpers.ifGreaterThan || (depth0 && depth0.ifGreaterThan) || alias2).call(alias1,(data && data.index),"2",{"name":"ifGreaterThan","hash":{},"fn":container.program(12, data, 0),"inverse":container.program(14, data, 0),"data":data})) != null ? stack1 : "");
9739},"3":function(container,depth0,helpers,partials,data) {
9740    var stack1;
9741
9742  return "<div class=\"row location-result more "
9743    + ((stack1 = helpers["if"].call(depth0 != null ? depth0 : (container.nullContext || {}),(data && data.last),{"name":"if","hash":{},"fn":container.program(4, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
9744    + "\">\n";
9745},"4":function(container,depth0,helpers,partials,data) {
9746    return "last";
9747},"6":function(container,depth0,helpers,partials,data) {
9748    var stack1;
9749
9750  return "<div class=\"row location-result showing "
9751    + ((stack1 = (helpers.ifEqual || (depth0 && depth0.ifEqual) || helpers.helperMissing).call(depth0 != null ? depth0 : (container.nullContext || {}),2,(data && data.index),{"name":"ifEqual","hash":{},"fn":container.program(4, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
9752    + "\">\n";
9753},"8":function(container,depth0,helpers,partials,data) {
9754    var stack1;
9755
9756  return container.escapeExpression(container.lambda(((stack1 = (depth0 != null ? depth0.chunk : depth0)) != null ? stack1.address2 : stack1), depth0))
9757    + "<br>\n";
9758},"10":function(container,depth0,helpers,partials,data) {
9759    return "\n<li><span>"
9760    + container.escapeExpression(container.lambda((depth0 != null ? depth0.value : depth0), depth0))
9761    + "</span></li>\n";
9762},"12":function(container,depth0,helpers,partials,data) {
9763    var stack1;
9764
9765  return "<hr class=\"more "
9766    + ((stack1 = helpers["if"].call(depth0 != null ? depth0 : (container.nullContext || {}),(data && data.last),{"name":"if","hash":{},"fn":container.program(4, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
9767    + "\">\n";
9768},"14":function(container,depth0,helpers,partials,data) {
9769    var stack1;
9770
9771  return "<hr class=\"showing "
9772    + ((stack1 = (helpers.ifEqual || (depth0 && depth0.ifEqual) || helpers.helperMissing).call(depth0 != null ? depth0 : (container.nullContext || {}),2,(data && data.index),{"name":"ifEqual","hash":{},"fn":container.program(4, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
9773    + "\">\n";
9774},"16":function(container,depth0,helpers,partials,data) {
9775    var stack1;
9776
9777  return ((stack1 = helpers.each.call(depth0 != null ? depth0 : (container.nullContext || {}),depth0,{"name":"each","hash":{},"fn":container.program(17, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "");
9778},"17":function(container,depth0,helpers,partials,data) {
9779    var stack1, helper, alias1=depth0 != null ? depth0 : (container.nullContext || {}), alias2=container.lambda, alias3=container.escapeExpression, alias4=helpers.helperMissing;
9780
9781  return "<div class=\"row location-result showing "
9782    + ((stack1 = helpers["if"].call(alias1,(data && data.last),{"name":"if","hash":{},"fn":container.program(4, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
9783    + "\">\n<div class=\"col-lg-4 col-md-4 col-sm-4 col-xs-12\">\n<h4 class=\"blue-header\"><a href=\""
9784    + alias3(alias2(((stack1 = (depth0 != null ? depth0.chunk : depth0)) != null ? stack1.pagePath : stack1), depth0))
9785    + "\">"
9786    + alias3(alias2(((stack1 = (depth0 != null ? depth0.chunk : depth0)) != null ? stack1.title : stack1), depth0))
9787    + "</a></h4>\n<span class=\"zipcode\">("
9788    + alias3(((helper = (helper = helpers.inZip || (depth0 != null ? depth0.inZip : depth0)) != null ? helper : alias4),(typeof helper === "function" ? helper.call(alias1,{"name":"inZip","hash":{},"data":data}) : helper)))
9789    + ")</span>\n<span>\n"
9790    + alias3(alias2(((stack1 = (depth0 != null ? depth0.chunk : depth0)) != null ? stack1.address : stack1), depth0))
9791    + "<br>\n"
9792    + ((stack1 = (helpers.ifNotEmpty || (depth0 && depth0.ifNotEmpty) || alias4).call(alias1,((stack1 = (depth0 != null ? depth0.chunk : depth0)) != null ? stack1.address2 : stack1),{"name":"ifNotEmpty","hash":{},"fn":container.program(8, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
9793    + "</span>\n<span>"
9794    + alias3(alias2(((stack1 = (depth0 != null ? depth0.chunk : depth0)) != null ? stack1.city : stack1), depth0))
9795    + ", "
9796    + alias3(alias2(((stack1 = (depth0 != null ? depth0.chunk : depth0)) != null ? stack1.state : stack1), depth0))
9797    + " "
9798    + alias3(alias2(((stack1 = (depth0 != null ? depth0.chunk : depth0)) != null ? stack1.zipcode : stack1), depth0))
9799    + "</span>\n<span>Phone: <a href=\"tel://"
9800    + alias3(alias2(((stack1 = (depth0 != null ? depth0.chunk : depth0)) != null ? stack1.phone : stack1), depth0))
9801    + "\" class=\"pc-phone\">"
9802    + alias3(alias2(((stack1 = (depth0 != null ? depth0.chunk : depth0)) != null ? stack1.phone : stack1), depth0))
9803    + "</a></span>\n<a href="
9804    + alias3(alias2(((stack1 = (depth0 != null ? depth0.chunk : depth0)) != null ? stack1.locationDetails : stack1), depth0))
9805    + " class=\"open-modal-primary-care\"><h4 class=\"blue-header getting-here\">Getting Here</h4></a>\n</div>\n<div class=\"col-lg-4 col-md-4 col-sm-4 col-xs-12\">\n<h4>Services offered:</h4>\n<ul>"
9806    + ((stack1 = helpers.each.call(alias1,((stack1 = (depth0 != null ? depth0.chunk : depth0)) != null ? stack1.specialties : stack1),{"name":"each","hash":{},"fn":container.program(10, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
9807    + "</ul>\n</div>\n<div class=\"col-lg-4 col-md-4 col-sm-4 col-xs-12 \">\n<button href=\""
9808    + alias3(alias2(((stack1 = (depth0 != null ? depth0.chunk : depth0)) != null ? stack1.pagePath : stack1), depth0))
9809    + "\" class=\"btn inline-table btn-default open-modal-primary-care\" data-modalcontainer=\".make-an-appt\">MAKE AN APPOINTMENT</button>\n</div>\n</div>\n<hr class=\"showing "
9810    + ((stack1 = helpers["if"].call(alias1,(data && data.last),{"name":"if","hash":{},"fn":container.program(4, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
9811    + "\">\n";
9812},"compiler":[7,">= 4.0.0"],"main":function(container,depth0,helpers,partials,data) {
9813    var stack1;
9814
9815  return ((stack1 = (helpers.ifGreaterThan || (depth0 && depth0.ifGreaterThan) || helpers.helperMissing).call(depth0 != null ? depth0 : (container.nullContext || {}),(depth0 != null ? depth0.length : depth0),3,{"name":"ifGreaterThan","hash":{},"fn":container.program(1, data, 0),"inverse":container.program(16, data, 0),"data":data})) != null ? stack1 : "");
9816},"useData":true});
9817
9818this["JST"]["handlebars/profilePhysicianTemplate.hbs"] = Handlebars.template({"1":function(container,depth0,helpers,partials,data) {
9819    var stack1;
9820
9821  return ((stack1 = (helpers.ifEqual || (depth0 && depth0.ifEqual) || helpers.helperMissing).call(depth0 != null ? depth0 : (container.nullContext || {}),(depth0 != null ? depth0.hideRating : depth0),"false",{"name":"ifEqual","hash":{},"fn":container.program(2, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "");
9822},"2":function(container,depth0,helpers,partials,data) {
9823    var helper, alias1=depth0 != null ? depth0 : (container.nullContext || {}), alias2=helpers.helperMissing, alias3="function", alias4=container.escapeExpression;
9824
9825  return "<div class='availability_rating col-sm-4'>\n<div class=\"acceptingPatient\">\n</div>\n<div class=\"starRatings clearfix\">\n<div class=\"rating_bar\">\n<div style=\"width:"
9826    + alias4(((helper = (helper = helpers.percentage || (depth0 != null ? depth0.percentage : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"percentage","hash":{},"data":data}) : helper)))
9827    + "%\"></div>\n</div>\n<span>"
9828    + alias4(((helper = (helper = helpers.avg_rating || (depth0 != null ? depth0.avg_rating : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"avg_rating","hash":{},"data":data}) : helper)))
9829    + " out of 5 </span>\n</div>\n</div>\n";
9830},"compiler":[7,">= 4.0.0"],"main":function(container,depth0,helpers,partials,data) {
9831    var stack1, helper, alias1=depth0 != null ? depth0 : (container.nullContext || {}), alias2=helpers.helperMissing, alias3="function", alias4=container.escapeExpression;
9832
9833  return "<div class=\"container\" >\n<div class='detail-header clearfix'>\n<div class='name_title col-sm-7'>\n<h3 class='physician'>"
9834    + ((stack1 = ((helper = (helper = helpers.name || (depth0 != null ? depth0.name : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"name","hash":{},"data":data}) : helper))) != null ? stack1 : "")
9835    + "</h3>\n<span>"
9836    + alias4(((helper = (helper = helpers.title || (depth0 != null ? depth0.title : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"title","hash":{},"data":data}) : helper)))
9837    + "</span>\n</div>\n<a href='JavaScript:void(0);' class='close'></a>\n"
9838    + ((stack1 = helpers["if"].call(alias1,(depth0 != null ? depth0.avg_rating : depth0),{"name":"if","hash":{},"fn":container.program(1, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
9839    + "</div>\n<div class='detail-content col-sm-12 clearboth '>\n"
9840    + ((stack1 = container.invokePartial(partials.conditionsTreated,depth0,{"name":"conditionsTreated","data":data,"helpers":helpers,"partials":partials,"decorators":container.decorators})) != null ? stack1 : "")
9841    + ((stack1 = container.invokePartial(partials.clinicLocations,depth0,{"name":"clinicLocations","data":data,"helpers":helpers,"partials":partials,"decorators":container.decorators})) != null ? stack1 : "")
9842    + "<div class='paddle'></div>\n</div>\n<a href='"
9843    + alias4(((helper = (helper = helpers.path || (depth0 != null ? depth0.path : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"path","hash":{},"data":data}) : helper)))
9844    + ".html#summary-content' class='btn' role='button'>View Full Profile</a>\n</div>\n";
9845},"usePartial":true,"useData":true});
9846
9847this["JST"]["handlebars/profileStaffTemplate.hbs"] = Handlebars.template({"compiler":[7,">= 4.0.0"],"main":function(container,depth0,helpers,partials,data) {
9848    var stack1, helper, alias1=depth0 != null ? depth0 : (container.nullContext || {}), alias2=helpers.helperMissing, alias3="function", alias4=container.escapeExpression;
9849
9850  return "<div class=\"container\" >\n<div class='detail-header'>\n<h3 class='physician'>"
9851    + ((stack1 = ((helper = (helper = helpers.name || (depth0 != null ? depth0.name : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"name","hash":{},"data":data}) : helper))) != null ? stack1 : "")
9852    + "</h3>\n<a href='JavaScript:void(0);' class='close'></a>\n<span>"
9853    + alias4(((helper = (helper = helpers.jobTitle || (depth0 != null ? depth0.jobTitle : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"jobTitle","hash":{},"data":data}) : helper)))
9854    + "</span>\n</div>\n<div class='detail-content clearboth'>\n<div class='col-xl-12 col-lg-12 col-md-12 col-sm-12 col-xs-12 education clearboth'>\n"
9855    + ((stack1 = ((helper = (helper = helpers.bio || (depth0 != null ? depth0.bio : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"bio","hash":{},"data":data}) : helper))) != null ? stack1 : "")
9856    + "\n</div>\n</div>\n<a href='"
9857    + alias4(((helper = (helper = helpers.path || (depth0 != null ? depth0.path : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"path","hash":{},"data":data}) : helper)))
9858    + ".html' class='btn' role='button'>View Full Profile</a>\n</div>\n";
9859},"useData":true});
9860
9861this["JST"]["handlebars/searchCategoriesTemplate.hbs"] = Handlebars.template({"compiler":[7,">= 4.0.0"],"main":function(container,depth0,helpers,partials,data) {
9862    return "<div id=\"search-nav\" class=\"row\">\n<ul class=\"col-sm-12\">\n<li class=\"all\">\n<a class=\"all-results-link hidden-xs\" href=\"#\">All&nbsp;Results</a>\n<a href=\"#\" class=\"all-results-link visible-xs\">All</a>\n</li>\n<li>\n<a class=\"doctors-filter-link\" href=\"#\">Doctors & Providers</a>\n</li>\n<li>\n<a class=\"conditions-filter-link\" href=\"#\">Conditions&nbsp;&amp;&nbsp;Treatments</a>\n</li>\n<li>\n<a class=\"clinics-filter-link\" href=\"#\">Clinics</a>\n</li>\n<li>\n<a class=\"more\" href=\"#\">More<span class=\"icon\"></span></a>\n<ul class=\"search-nav-more-container\">\n<li class=\"arrow\"></li>\n<li>\n<a class=\"trials-filter-link\" href=\"#\">Clinical Trials</a>\n</li>\n<li>\n<a class=\"stories-filter-link\" href=\"#\">Stories</a>\n</li>\n<li>\n<a class=\"events-filter-link\" href=\"#\">Events</a>\n</li>\n</ul>\n</li>\n</ul>\n</div>\n";
9863},"useData":true});
9864
9865this["JST"]["handlebars/searchbar-conditions-treatments.hbs"] = Handlebars.template({"1":function(container,depth0,helpers,partials,data) {
9866    var helper, alias1=depth0 != null ? depth0 : (container.nullContext || {}), alias2=helpers.helperMissing, alias3="function", alias4=container.escapeExpression;
9867
9868  return "<option value=\""
9869    + alias4(((helper = (helper = helpers.title || (depth0 != null ? depth0.title : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"title","hash":{},"data":data}) : helper)))
9870    + "\" data-url=\""
9871    + alias4(((helper = (helper = helpers.url || (depth0 != null ? depth0.url : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"url","hash":{},"data":data}) : helper)))
9872    + "\">"
9873    + alias4(((helper = (helper = helpers.title || (depth0 != null ? depth0.title : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"title","hash":{},"data":data}) : helper)))
9874    + "</option>\n";
9875},"compiler":[7,">= 4.0.0"],"main":function(container,depth0,helpers,partials,data) {
9876    var stack1;
9877
9878  return "<option value=\"\"></option>\n"
9879    + ((stack1 = helpers.each.call(depth0 != null ? depth0 : (container.nullContext || {}),((stack1 = (depth0 != null ? depth0.results : depth0)) != null ? stack1.data : stack1),{"name":"each","hash":{},"fn":container.program(1, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "");
9880},"useData":true});
9881
9882this["JST"]["handlebars/siteFeedbackTemplate.hbs"] = Handlebars.template({"1":function(container,depth0,helpers,partials,data) {
9883    var helper, alias1=depth0 != null ? depth0 : (container.nullContext || {}), alias2=helpers.helperMissing, alias3="function", alias4=container.escapeExpression;
9884
9885  return "To: "
9886    + alias4(((helper = (helper = helpers.requestorName || (depth0 != null ? depth0.requestorName : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"requestorName","hash":{},"data":data}) : helper)))
9887    + " &lt;"
9888    + alias4(((helper = (helper = helpers.requestorEmail || (depth0 != null ? depth0.requestorEmail : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"requestorEmail","hash":{},"data":data}) : helper)))
9889    + "&gt;";
9890},"compiler":[7,">= 4.0.0"],"main":function(container,depth0,helpers,partials,data) {
9891    var stack1, helper, alias1=depth0 != null ? depth0 : (container.nullContext || {}), alias2=helpers.helperMissing, alias3="function", alias4=container.escapeExpression;
9892
9893  return "<div id=\"site-feedback\">\n<h3>"
9894    + alias4(((helper = (helper = helpers.mainHeader || (depth0 != null ? depth0.mainHeader : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"mainHeader","hash":{},"data":data}) : helper)))
9895    + "</h3>\n<div class=\"row\">\n<div class=\"col-xs-12\">\n<h4>"
9896    + alias4(((helper = (helper = helpers.modalHeader || (depth0 != null ? depth0.modalHeader : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"modalHeader","hash":{},"data":data}) : helper)))
9897    + "</h4>\n<p>"
9898    + alias4(((helper = (helper = helpers.modalBody || (depth0 != null ? depth0.modalBody : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"modalBody","hash":{},"data":data}) : helper)))
9899    + "</p>\n<form name=\"feedbackform\">\n"
9900    + ((stack1 = helpers["if"].call(alias1,(depth0 != null ? depth0.requestorName : depth0),{"name":"if","hash":{},"fn":container.program(1, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
9901    + "\n<h4>Name (Optional)</h4>\n<input type=\"text\"\nname=\"feedbackUsername\"\nid=\"feedbackUsername\"\nplaceholder=\"Your Name\"\nvalue=\""
9902    + alias4(((helper = (helper = helpers.reviewerName || (depth0 != null ? depth0.reviewerName : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"reviewerName","hash":{},"data":data}) : helper)))
9903    + "\"/>\n<h4>Email (required)</h4>\n<input type=\"text\"\nname=\"feedbackEmail\"\nid=\"feedbackEmail\"\nplaceholder=\"[email protected]\"\nvalue=\""
9904    + alias4(((helper = (helper = helpers.reviewerEmail || (depth0 != null ? depth0.reviewerEmail : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"reviewerEmail","hash":{},"data":data}) : helper)))
9905    + "\"/>\n<input type=\"hidden\"\nname=\"pageTitle\"\nid=\"pageTitle\"\nvalue=\""
9906    + alias4(((helper = (helper = helpers.pageTitle || (depth0 != null ? depth0.pageTitle : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"pageTitle","hash":{},"data":data}) : helper)))
9907    + "\"/>\n<h4>Comment (required)</h4>\n<textarea name=\"comments\" id=\"feedbackComment\" placeholder=\"Your comment here.\"></textarea>\n<h4>Page Url</h4>\n<input type=\"text\" name=\"feedbackEnteredUrl\" id=\"feedbackEnteredUrl\" value=\""
9908    + alias4(((helper = (helper = helpers.feedbackEnteredUrl || (depth0 != null ? depth0.feedbackEnteredUrl : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"feedbackEnteredUrl","hash":{},"data":data}) : helper)))
9909    + "\"/>\n<br/>\n<input type=\"hidden\" name=\"action\" value=\"postIssue\"/>\n<div id=\"feedbackErrorMessage\"></div>\n<button class=\"btn\" id=\"submit-feedback\">Submit</button>\n</form>\n</div>\n</div>\n</div>\n";
9910},"useData":true});
9911
9912this["JST"]["handlebars/small-info-menu-template.hbs"] = Handlebars.template({"1":function(container,depth0,helpers,partials,data) {
9913    var stack1, helper, alias1=depth0 != null ? depth0 : (container.nullContext || {}), alias2=helpers.helperMissing, alias3="function", alias4=container.escapeExpression;
9914
9915  return "<div class=\"small-info-menu "
9916    + ((stack1 = (helpers.ifEven || (depth0 && depth0.ifEven) || alias2).call(alias1,(data && data.index),{"n
9916ame":"ifEven","hash":{},"fn":container.program(2, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
9917    + "\">\n"
9918    + ((stack1 = (helpers.ifEqual || (depth0 && depth0.ifEqual) || alias2).call(alias1,(depth0 != null ? depth0.markerLetter : depth0),"0",{"name":"ifEqual","hash":{},"fn":container.program(4, data, 0),"inverse":container.program(6, data, 0),"data":data})) != null ? stack1 : "")
9919    + "<div class=\"info-window-details\">\n<a href=\""
9920    + alias4(((helper = (helper = helpers.pagePath || (depth0 != null ? depth0.pagePath : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"pagePath","hash":{},"data":data}) : helper)))
9921    + "\" class=\"small-info-menu-title\">"
9922    + alias4(((helper = (helper = helpers.title || (depth0 != null ? depth0.title : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"title","hash":{},"data":data}) : helper)))
9923    + "</a><br />\n<span class=\"small-info-window-address\">\n"
9924    + alias4(((helper = (helper = helpers.address || (depth0 != null ? depth0.address : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"address","hash":{},"data":data}) : helper)))
9925    + "<br>\n"
9926    + ((stack1 = (helpers.ifNotEmpty || (depth0 && depth0.ifNotEmpty) || alias2).call(alias1,(depth0 != null ? depth0.address2 : depth0),{"name":"ifNotEmpty","hash":{},"fn":container.program(8, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
9927    + "</span>\n<span class=\"small-info-window-city\">"
9928    + alias4(((helper = (helper = helpers.city || (depth0 != null ? depth0.city : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"city","hash":{},"data":data}) : helper)))
9929    + "</span>\n<span class=\"small-info-window-state\">"
9930    + alias4(((helper = (helper = helpers.state || (depth0 != null ? depth0.state : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"state","hash":{},"data":data}) : helper)))
9931    + "</span>\n<span class=\"small-info-window-zipcode\">"
9932    + alias4(((helper = (helper = helpers.zipcode || (depth0 != null ? depth0.zipcode : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"zipcode","hash":{},"data":data}) : helper)))
9933    + "</span><br />\n<a href=\""
9934    + alias4(((helper = (helper = helpers.locationDetails || (depth0 != null ? depth0.locationDetails : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"locationDetails","hash":{},"data":data}) : helper)))
9935    + "\" class=\"info-window-modal small-info-window-location\">Getting Here</a>\n</div>\n</div>\n";
9936},"2":function(container,depth0,helpers,partials,data) {
9937    return "odd-gray";
9938},"4":function(container,depth0,helpers,partials,data) {
9939    return "<img src=\"/etc/clientlibs/shc/main/img/Maps/pins/Star/star_active.svg\" class=\"letter-marker-image\"/>\n";
9940},"6":function(container,depth0,helpers,partials,data) {
9941    var helper;
9942
9943  return "<img src=\"/etc/clientlibs/shc/main/img/Maps/pins/Alphabets/"
9944    + container.escapeExpression(((helper = (helper = helpers.markerLetter || (depth0 != null ? depth0.markerLetter : depth0)) != null ? helper : helpers.helperMissing),(typeof helper === "function" ? helper.call(depth0 != null ? depth0 : (container.nullContext || {}),{"name":"markerLetter","hash":{},"data":data}) : helper)))
9945    + ".svg\" class=\"letter-marker-image\"/>\n";
9946},"8":function(container,depth0,helpers,partials,data) {
9947    var helper;
9948
9949  return container.escapeExpression(((helper = (helper = helpers.address2 || (depth0 != null ? depth0.address2 : depth0)) != null ? helper : helpers.helperMissing),(typeof helper === "function" ? helper.call(depth0 != null ? depth0 : (container.nullContext || {}),{"name":"address2","hash":{},"data":data}) : helper)))
9950    + "<br>\n";
9951},"compiler":[7,">= 4.0.0"],"main":function(container,depth0,helpers,partials,data) {
9952    var stack1;
9953
9954  return ((stack1 = helpers.each.call(depth0 != null ? depth0 : (container.nullContext || {}),depth0,{"name":"each","hash":{},"fn":container.program(1, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "");
9955},"useData":true});
9956
9957this["JST"]["handlebars/sortDropdownTemplate.hbs"] = Handlebars.template({"compiler":[7,">= 4.0.0"],"main":function(container,depth0,helpers,partials,data) {
9958    return "<div class=\"type-filter\">\n<a href=\"#\" class=\"sort-menu-toggle\">Sort By Relevance<span></span></a>\n<ul id=\"relevance-menu\" class=\"sort-menu hidden\">\n<li class=\"arrow\"></li>\n<li>\n<a href=\"#\" class=\"active sort-option\" data-sort-value=\"relevance\" data-sort-name=\"Sort By Relevance\">Relevance</a>\n</li>\n<li>\n<a href=\"#\" class=\"sort-option\" data-sort-value=\"alpha\" data-sort-name=\"Sort By Alphabet\">Alphabet</a>\n</li>\n</ul>\n</div>\n";
9959},"useData":true});
9960
9961this["JST"]["handlebars/summaryTileTemplate.hbs"] = Handlebars.template({"compiler":[7,">= 4.0.0"],"main":function(container,depth0,helpers,partials,data) {
9962    var helper, alias1=depth0 != null ? depth0 : (container.nullContext || {}), alias2=helpers.helperMissing, alias3="function", alias4=container.escapeExpression;
9963
9964  return "<div class='summary-content card'>\n<div class='overlay'></div>\n<span class='totalCount "
9965    + alias4(((helper = (helper = helpers.componentID || (depth0 != null ? depth0.componentID : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"componentID","hash":{},"data":data}) : helper)))
9966    + "'>"
9967    + alias4(((helper = (helper = helpers.totalCount || (depth0 != null ? depth0.totalCount : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"totalCount","hash":{},"data":data}) : helper)))
9968    + "</span>\n<h3>"
9969    + alias4(((helper = (helper = helpers.title || (depth0 != null ? depth0.title : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"title","hash":{},"data":data}) : helper)))
9970    + "</h3>\n<a href='#'>View All</a>\n</div>\n";
9971},"useData":true});
9972// Shared UI objects.
9973SHC.Namespace(SHC, "SHC.ui");
9974
9975// breakpoints matched to global.less
9976SHC.ui.ScreenSizes = {
9977    "medium": 768,
9978    "large": 1024
9979};
9980
9981SHC.ui.detectScreenMode = function () {
9982    var breaks = SHC.ui.ScreenSizes,
9983        width = window.innerWidth;
9984    if (width < breaks.medium) {
9985        SHC.ui.screenMode = "small";
9986    } else if (width >= breaks.medium && width < breaks.large) {
9987        SHC.ui.screenMode = "medium";
9988    } else {
9989        SHC.ui.screenMode = "large";
9990    }
9991};
9992
9993SHC.ui.setScreenSizes = function () {
9994    SHC.ui.viewportWidth = viewportSize.getWidth();
9995
9996    /* Nothing currently checks the viewportHeight.  If we need it in the future we should use this. */
9997    // SHC.ui.viewportHeight = viewportSize.getHeight();
9998};
9999
10000// Sitewide Resize Handler
10001// default is "large"
10002SHC.ui.onResizeHandler = function () {
10003    SHC.ui.detectScreenMode();
10004    SHC.ui.setScreenSizes();
10005    $(this).trigger('resizeEnd');
10006};
10007
10008// true if input placeholders are
10009// supported by browser.
10010SHC.ui.placeholderSupported = function () {
10011    var i = document.createElement('input');
10012    return 'placeholder' in i;
10013};
10014
10015// in case inlined definition is not available from preload.jsp
10016function shcDOMContentLoaded(fn) {
10017    if (document.readyState === "complete" || document.readyState === "interactive") { setTimeout(fn, 1); } else { document.addEventListener("DOMContentLoaded", fn); }
10018}
10019
10020// Setup a throttled event handler for onresize event.
10021// Determine screen size and set SHC.ui.screenMode global value.
10022shcDOMContentLoaded(function () {
10023    SHC.ui.detectScreenMode();
10024    SHC.ui.setScreenSizes();
10025    SHC.ui.cssBoxShadow = SHC.util.getCssProperty(['boxShadow', 'MozBoxShadow', 'WebkitBoxShadow']);
10026    $(window).resize(SHC.util.throttle(SHC.ui.onResizeHandler, 200));
10027});
10028
10029SHC.Namespace(SHC, "SHC.ui.TouchSurface");
10030SHC.ui.TouchSurface = new SHC.Class();
10031
10032/**
10033 * @fileOverview shc.ui.TouchSurface is a touch event detection
10034 * tool for mobile devices.
10035 * @author Kyo Suayan
10036 * @module shc.ui.TouchSurface
10037 *
10038 * @example
10039 * var touchSurface = new shc.ui.TouchSurface(el, yourFunction);
10040 *
10041 */
10042
10043SHC.ui.TouchSurface.include({
10044
10045    /**
10046     * @instance
10047     * @param el
10048     * @param callback
10049     */
10050    init: function(el, callback) {
10051        "use strict";
10052        try {
10053            var that = this;
10054            this.touchSurface = el;
10055            this.direction = 'none';
10056            this.swipeType = 'none';
10057            this.startX = null;
10058            this.startY = null;
10059            this.distX = null;
10060            this.distY = null;
10061            this.threshold = 50; //required min distance traveled to be considered swipe
10062            this.restraint = 50; // maximum distance allowed at the same time in perpendicular direction
10063            this.allowedTime = 500; // maximum time allowed to travel that distance
10064            this.elapsedTime = null;
10065            this.startTime = null;
10066            this.touchHandler = callback || function(evt, dir, phase, swipetype, distance){};
10067
10068            this.touchSurface.addEventListener('touchstart', function(e){ that.onTouchStart(e); }, false);
10069            this.touchSurface.addEventListener('touchmove', function(e){ that.onTouchMove(e); }, false);
10070            this.touchSurface.addEventListener('touchend', function(e){ that.onTouchEnd(e); }, false);
10071        } catch(err) {}
10072    },
10073
10074    /**
10075     * Unbind event listeners.
10076     */
10077    removeEventListeners: function() {
10078        try {
10079            this.touchSurface.removeEventListener('touchstart');
10080            this.touchSurface.removeEventListener('touchmove');
10081            this.touchSurface.removeEventListener('touchend');
10082        } catch(err) {}
10083    },
10084
10085    /**
10086     *
10087     */
10088    debug: function() {
10089        console.log("----------------");
10090        console.log("startX", this.startX, "startY", this.startY);
10091        console.log("x", this.distX, "y", this.distY, this.axis, this.direction);
10092    },
10093
10094    /**
10095     * Touch start event handler.
10096     * @param e
10097     */
10098    onTouchStart: function(e) {
10099        var touchObj = e.changedTouches[0];
10100        e.preventDefault();
10101        this.axis = null;
10102        this.direction = 'none';
10103        this.swipeType = 'none';
10104        this.startX = touchObj.pageX;
10105        this.startY = touchObj.pageY;
10106        // record time when finger first makes contact with surface
10107        this.startTime = new Date().getTime();
10108        // fire callback function with params direction="none", phase="start", swipetype="none" etc
10109        this.touchHandler(e, 'none', 'start', this.swipeType, 0);
10110    },
10111
10112    /**
10113     * Touch move event handler.
10114     * @param e
10115     */
10116    onTouchMove: function(e) {
10117        var touchObj = e.changedTouches[0];
10118        e.preventDefault();
10119
10120        // get horizontal dist traveled by finger while in contact with surface
10121        this.distX = touchObj.pageX - this.startX;
10122        // get vertical dist traveled by finger while in contact with surface
10123        this.distY = touchObj.pageY - this.startY;
10124
10125        // if distance traveled horizontally is greater than vertically, consider this a horizontal movement
10126        if (!this.axis) {
10127            this.axis =  (Math.abs(this.distX) > Math.abs(this.distY)) ? "horizontal" : "vertical";
10128        }
10129
10130        if (this.axis === 'horizontal') {
10131            this.direction = (this.distX < 0) ? 'left' : 'right';
10132            // fire callback function with params direction="left|right", phase="move", swipetype="none" etc
10133            this.touchHandler(e, this.direction, 'move', this.swipeType, this.distX);
10134            e.preventDefault();
10135            // else consider this a vertical movement
10136        } else {
10137            this.direction = (this.distY < 0) ? 'up' : 'down';
10138            // fire callback function with params direction="up|down", phase="move", swipetype="none" etc
10139            this.touchHandler(e, this.direction, 'move', this.swipeType, this.distY);
10140        }
10141        // this.debug();
10142    },
10143
10144    /**
10145     * Touch end event handler.
10146     * @param e
10147     */
10148    onTouchEnd: function(e) {
10149        e.preventDefault();
10150        // get time elapsed
10151
10152        this.elapsedTime = new Date().getTime() - this.startTime;
10153        // first condition for swipe met
10154        if (this.elapsedTime <= this.allowedTime) {
10155            // 2nd condition for horizontal swipe met
10156            if (Math.abs(this.distX) >= this.threshold &&
10157                Math.abs(this.distY) <= this.restraint){
10158                // set swipeType to either "left" or "right"
10159                this.swipeType = this.direction;
10160                // 2nd condition for vertical swipe met
10161            } else if (Math.abs(this.distY) >= this.threshold &&
10162                Math.abs(this.distX) <= this.restraint){
10163                // set swipeType to either "top" or "down"
10164                this.swipeType = this.direction;
10165            }
10166        }
10167        // Fire callback function with params direction="left|right|up|down", phase="end", swipetype=direction
10168        var distance = (this.direction === 'left' || this.direction === 'right') ? this.distX : this.distY;
10169        this.touchHandler(e, this.direction, 'end', this.swipeType, distance);
10170    }
10171});
10172SHC.Namespace(SHC, "SHC.ui.Tile");
10173SHC.ui.Tile = new SHC.Class();
10174
10175SHC.ui.Tile.include({
10176
10177    /**
10178     * @param parent selector
10179     * @param elementAttributes to pass to div.
10180     * @returns {*}
10181     */
10182    init: function(parent, elementAttributes) {
10183        "use strict";
10184        this.height = 0;
10185        this.jq = $("<div/>", elementAttributes)
10186            .appendTo(parent);
10187        return this;
10188    },
10189    /**
10190     * call transit.js for smoother animations.
10191     * @param attr
10192     */
10193    transition: function(attr) {
10194        this.jq.transition(attr);
10195    },
10196
10197    /**
10198     * declare a jQuery Event Handler.
10199     * @param eventType
10200     * @param eventHandler
10201     */
10202    on: function(eventType, selector, eventHandler) {
10203        if (eventType && typeof eventHandler === 'function') {
10204            this.jq.on(eventType, selector, eventHandler);
10205        }
10206    },
10207
10208    data: function(key,value) {
10209        if (this.jq) {
10210            this.jq.data(key,value);
10211        }
10212    },
10213
10214    /**
10215     * @param height
10216     */
10217    setHeight: function(height){
10218        this.height = height;
10219    },
10220    /**
10221     * Default behavior: do nothing.
10222     */
10223    preload: function() {
10224    },
10225    /**
10226     * A basic jQuery .show() call.
10227     */
10228    show: function(){
10229        // render as square
10230        if(!(SHC.ui.Search.DirectoryUtil.isDirectoryPage())) {
10231            this.jq.height(this.height);
10232            this.jq.width(this.height);
10233        }
10234        this.jq.show();
10235    }
10236
10237});
10238var gaName;
10239
10240function getGoogleAnalyticsName() {
10241	var gaExists = false;
10242	if (typeof ga !== "undefined") {
10243		if (typeof ga.getAll !== "undefined") {
10244			gaExists = true;
10245			var tr = ga.getAll(),
10246				trCnt = tr.length;
10247			while(trCnt--) {
10248				gaName = tr[trCnt].get("name");
10249				//console.log('universal tracker with name: ' + tr[trCnt].get('name'));
10250			}
10251		}
10252	}
10253	if (!gaExists) {
10254		checkGoogleAnalyticsName();
10255	}
10256}
10257
10258function checkGoogleAnalyticsName() {
10259	setTimeout(function() {
10260		getGoogleAnalyticsName();
10261	}, 500);
10262}
10263
10264jQuery(document).ready(function() {
10265	checkGoogleAnalyticsName();
10266
10267    // Requires swipe of 45 pixels before jQuery swipe will execute
10268    jQuery.event.special.swipe.horizontalDistanceThreshold = 45;
10269});
10270jQuery(document).ready(function(){
10271
10272
10273    //fires a custom event 'smallBreakpointChange' if a change from small to anything larger or vice versa
10274    var currentSize = "";
10275    var reinit = function(){
10276        //if we get in here: we are in LARGE
10277        if (!jQuery("#checkBootStrapXS") || !jQuery("#checkBootStrapXS").is(":hidden")) {   
10278            if(!(currentSize === 'notSmall')){
10279                currentSize = 'notSmall';
10280                $(document).data('size', 'notSmall').trigger('smallBreakpointChange');
10281            }                    
10282        }   else {
10283            //if we are in here: we are in SMALL
10284            if(!(currentSize === 'small')){
10285                currentSize = 'small';
10286                $(document).data('size', 'small').trigger('smallBreakpointChange');
10287            }  
10288        }  
10289    };
10290    var doit;
10291    $(window).on('resizeEnd', function() {
10292        clearTimeout(doit);
10293        doit = setTimeout(reinit, 250);
10294    });
10295
10296    // override default anchor linking and also ensure clicking the same anchor twice in a row works
10297    var anchorLinks = jQuery("a");
10298    anchorLinks.each(function() {
10299        var thisAnchor = jQuery(this);
10300        thisAnchor.on('click', function(e) {
10301            if (window.location.pathname === this.pathname) {
10302                if (window.location.hash !== this.hash) {
10303                    history.pushState(null, null, this.href);
10304                }
10305                $(window).trigger('anchorclick');
10306            }
10307        });
10308    });
10309
10310    var trialPassthroughLinks = $('a[href*="application/ct.html/&sp_trialLocks"]');
10311    if (trialPassthroughLinks) {
10312        for (var i = 0; i < trialPassthroughLinks.length; i++) {
10313            var trialPassthrough = trialPassthroughLinks[i];
10314            var urlPath = window.location.pathname;
10315            var newUrl = "";
10316            var linkedUrl = $(trialPassthrough).attr('href');
10317            if (linkedUrl.length > 0 && linkedUrl.indexOf('application/ct.html/&sp_trialLocks') > -1) {
10318                // remove .html extension if it exists after the suffix or parameters
10319                var includesPath = linkedUrl.indexOf('%7C/') >= 0 ? true : false;
10320                newUrl = (linkedUrl.endsWith('.html') && !includesPath ? linkedUrl.slice(0, -5) : linkedUrl);
10321                if(!includesPath) {
10322                    newUrl += '%7C';
10323                    if (urlPath.indexOf('/content/shc/en') > -1) {
10324                        newUrl += urlPath.split('/content/shc/en')[1];
10325                    } else {
10326                        newUrl += urlPath;
10327                    }
10328                }
10329                $(trialPassthrough).attr('href', newUrl);
10330            }
10331        }
10332    }
10333
10334    //Prevents older versions of IE11 from loading a cached page using the back button
10335    $('#main #control-dropdown-toggle').on('click', function() {
10336        var template = $('#shc-search-title').attr('data-page-template');
10337        if (template.indexOf('clinicaltrials_search') > -1) {
10338            var activeControlItem = $('#control-dropdown-desktop .control-item.active');
10339            activeControlItem.removeClass('active');
10340            var trialsControlItem = $('#control-dropdown-desktop .control-item.trials');
10341            trialsControlItem.addClass('active');
10342        }
10343    });
10344});
10345//Prevents Sarfari from loading a cached page using the back button
10346jQuery(window).bind("pageshow", function(event) {
10347    if (event.originalEvent.persisted) {
10348        window.location.reload()
10349    }
10350});
10351
10352function setSkipToMainContentLinkTarget() {
10353	const $skipToMainContentLink = document.querySelector('.skip-to-main-content-link');
10354
10355	if ($skipToMainContentLink) {
10356		const $searchInpagenav = document.querySelector('#shc-search-title');
10357		const $subnav = document.querySelector('.subnav');
10358        //stanfordlab test directory, test details, test updates, skip target is main-content
10359        const $mainContent = document.querySelector('#main-content');
10360
10361		if ($subnav) { // If there is a subnav, set the skip to main content link to point to the first subnav link
10362			const $firstSubnavLink = $subnav.querySelector('a');
10363			$firstSubnavLink?.setAttribute('id', 'first-subnav-link');
10364			$skipToMainContentLink.setAttribute('href', '#first-subnav-link');
10365			$skipToMainContentLink.addEventListener('click', function() {
10366				$firstSubnavLink?.focus();
10367			});
10368		} else if ($searchInpagenav?.offsetHeight > 15) { // If the search-inpagenav is visible, set the skip to main content link to point to it
10369			$skipToMainContentLink.setAttribute('href', '#shc-search-title');
10370			$skipToMainContentLink.addEventListener('click', function() {
10371				$searchInpagenav?.focus();
10372			});
10373		} else if ($mainContent) {
10374		    $skipToMainContentLink.setAttribute('href', '#main-content');
10375		} else {
10376			$skipToMainContentLink.setAttribute('href', '#main-container');
10377			$skipToMainContentLink.addEventListener('click', function() {
10378				document.querySelector('#main-container')?.focus();
10379			});
10380		}
10381	}
10382}
10383
10384function onDocumentReady() {
10385	setSkipToMainContentLinkTarget();
10386}
10387
10388if (document.readyState !== 'loading') {
10389	onDocumentReady();
10390} else {
10391	document.addEventListener('DOMContentLoaded', onDocumentReady);
10392}
10393
10394(function (SHC, $) {
10395    "use strict";
10396    /**
10397     * Namespace for exporting global variables
10398     * to be consumed by third party tracking services.
10399     */
10400    SHC.Namespace(SHC, "SHC.exports");
10401    SHC.exports.searchTerm = "";
10402    var getSearchTerm = function() {
10403        var str = window.location.href,
10404            found = str.match(/search-results\.html\/(.*)$/),
10405            term = (found && found[1]) ? found[1] : "";
10406        if (term) {
10407            term = decodeURI(term.replace(/\#/,""));
10408        }
10409        return term;
10410    };
10411    /**
10412     * Make this available on Page Load.
10413     */
10414    $(function(){
10415        // currently consumed by foresee:
10416        SHC.exports.searchTerm = getSearchTerm();
10417        // add your other exports in this section.
10418    });
10419}(SHC, jQuery));
10420
10421
10422// Externalized. corpPartner is scraped by LP.
10423var getCorpPartner = function () {
10424    var corpPartner = null,
10425        url = window.location.href;
10426    if (url.indexOf("/partners/") > -1) {
10427        var name = url.split("/partners/")[1];
10428        if (name && name.length > 0) {
10429            name = name.replace(".html", " ");
10430            corpPartner = {
10431                scope: 'session',
10432                name: 'corpPartner',
10433                value: name
10434            };
10435        }
10436    }
10437    return corpPartner;
10438};
10439
10440var corpPartner = getCorpPartner();
10441
10442$(document).ready(function () {
10443    var elementsToAnimate = $('.shc-animated');
10444
10445    if (elementsToAnimate.length) {
10446        if (window.TweenLite === undefined) {
10447            var getTweenLite = function () {
10448                $.getScript('/etc/clientlibs/shc/main/js/vendor/gsap/TweenLite.min.js')
10449                    .done(animateComponents)
10450                    .fail(function (jqxhr, settings, exception) {
10451                        console.error("TweenLite:", exception);
10452                    });
10453            };
10454            $.getScript('/etc/clientlibs/shc/main/js/vendor/gsap/CSSPlugin.min.js')
10455                .done(getTweenLite)
10456                .fail(function (jqxhr, settings, exception) {
10457                    console.error("CSSPlugin:", exception);
10458                });
10459        } else {
10460            animateComponents();
10461        }
10462    }
10463
10464    function animateComponents() {
10465        elementsToAnimate.each(function (idx, element) {
10466            var hasAnimated = false;
10467            var $element = $(element);
10468            var animationType = $element.data('animation-type') || 'fadeInUp';
10469            var animateOnce = $element.data('animate-once') || false;
10470            var animationDistance = $element.data('animation-distance') || 20;
10471            var animationDuration = $element.data('animation-duration') || 1;
10472
10473            var animationFrom = {
10474                opacity: 0,
10475                y: animationDistance,
10476                x: 0
10477            };
10478            var animationTo = {
10479                opacity: 1,
10480                y: 0,
10481                x: 0
10482            };
10483
10484            if (animationType.indexOf('fadeOut') !== -1) {
10485                animationFrom.opacity = 1;
10486                animationFrom.y = 0;
10487                animationTo.opacity = 0;
10488                animationTo.y = animationType.indexOf('Down') !== -1 ? animationDistance : -animationDistance;
10489            } else {
10490                if (animationType.indexOf('Right') !== -1) {
10491                    animationFrom.y = 0;
10492                    animationFrom.x = -animationDistance;
10493                    animationTo.y = 0;
10494                    animationTo.x = 0;
10495                } else if (animationType.indexOf('Down') !== -1) {
10496                    animationFrom.y = -animationDistance;
10497                    animationTo.y = 0;
10498                } else if (animationType.indexOf('Left') !== -1) {
10499                    animationFrom.y = 0;
10500                    animationFrom.x = animationDistance;
10501                    animationTo.y = 0;
10502                    animationTo.x = 0;
10503                }
10504            }
10505
10506            $element.inViewport(function (px) {
10507                if (px) {
10508                    if (!hasAnimated) {
10509                        hasAnimated = true;
10510                        TweenLite.fromTo(this, animationDuration, animationFrom, animationTo);
10511                    }
10512                } else {
10513                    if (hasAnimated) {
10514                        hasAnimated = animateOnce ? hasAnimated : !hasAnimated;
10515                    }
10516                    if (!animateOnce) {
10517                        // Reset animation
10518                        TweenLite.to(this, 0, animationFrom);
10519                    }
10520                }
10521            });
10522        });
10523    }
10524});
10525
10526shcDOMContentLoaded(function() {
10527
10528    var $offcanvasToggle = $('[data-toggle=offcanvas]'),
10529        $offcanvas = $('.row-offcanvas, body, html'),
10530        $sidebarOffcanvas = $('.sidebar-offcanvas'),
10531        $menu = $('.masthead_menu #menu'),
10532        $body = $('body'),
10533        $mainContainer = $('#main-container'),
10534        $main = $('#main');
10535
10536
10537    $offcanvasToggle.on('click', function(e) {
10538        if($(this).hasClass("active")) {
10539            adjustMastheadWidthOnMenuToggle();
10540            animateSidebarClose();
10541        } else {
10542            adjustMastheadWidthOnMenuToggle();
10543            $sidebarOffcanvas.animate({
10544                left: '0',
10545                duration: 400
10546            });
10547            $('.row-offcanvas, body, html').switchClass("", "open-offcanvas", 400);
10548            if (SHC.ui.screenMode == "small"){
10549                mobileAdjustments('open');
10550            } else {
10551                desktopAdjustments('open');
10552            }
10553        }
10554    });
10555
10556    $body.on('click', function(e) {
10557        closeMenu('clickbody', e);
10558    });
10559
10560    $body.on('swipeleft.hamburger', function(e) {
10561        closeMenu('swipeleft', e);
10562    });
10563
10564    //find the length of the masthead links to determine if they can be displayed in tablet view
10565    function adjustMastheadLinks() {
10566        var windowWidth = $(window).width();
10567        var isStanfordLabNav = $('.stanford-lab.global-navigation').length ? true : false;
10568        //don't adjust stanford lab navigation links
10569        if (windowWidth <= 1024 && !isStanfordLabNav) {
10570            var mastheadWidth = $('#masthead-nav').width(),
10571                mastheadDropdownLinksWidth = 0,
10572                tabletViewLinkWidth = 0,
10573                showTabletLinksWidth = 0;
10574            $('#masthead-nav li.masthead-dropdown').each(function (i, e) {
10575                mastheadDropdownLinksWidth = mastheadDropdownLinksWidth + $(e).width();
10576            });
10577
10578            $('#masthead-nav li.masthead-link').each(function (i, e) {
10579                tabletViewLinkWidth = tabletViewLinkWidth + $(e).width();
10580                $(e).show();
10581            });
10582
10583            if (tabletViewLinkWidth >= (mastheadWidth - mastheadDropdownLinksWidth)) {
10584                $('#masthead-nav li.masthead-link').each(function (i, e) {
10585                    showTabletLinksWidth = showTabletLinksWidth + $(e).width();
10586                    if (showTabletLinksWidth <= (mastheadWidth - mastheadDropdownLinksWidth)) {
10587                        $(e).show();
10588                    } else {
10589                        $(e).hide();
10590                    }
10591                });
10592            }
10593        }
10594    }
10595    adjustMastheadLinks();
10596
10597    //Sets the directory view to List when navigating with the Masthead or Hamburger menu
10598    $('#masthead-nav, #menu-main-nav').on('click', 'a.directory-link, li.masthead-link a', function(e) {
10599        SHC.util.setCookie('activeView', 'list', 1, "/");
10600        const linkText = e.currentTarget.text ? e.currentTarget.text.toLowerCase() : "";
10601        stanford.analytics.send(stanford.analytics.createNavigationEvent("global header", e.currentTarget.text, linkText, 'navigation'));
10602    });
10603
10604    //Passes drawer link info to data layer when drawer link is clicked
10605    $('#drawers .drawer').on('click', 'a, input[type="submit"]', function(e) {
10606        let parentText = $("#masthead-nav").find(".masthead-dropdown.active").text().trim();
10607        let text = e.currentTarget.hasAttribute("type") ? e.currentTarget.value : e.currentTarget.text;
10608            stanford.analytics.send(stanford.analytics.createNavigationEvent("global header", parentText, text.trim().toLowerCase(), 'navigation'));
10609    });
10610
10611    //Sets the directory view to List when navigating with links in the Footer
10612    $('.placemat-main-links').on('click', 'li.footer-list-header a', function() {
10613        SHC.util.setCookie('activeView', 'list', 1, "/");
10614    });
10615
10616    $('.masthead_menu_link').on('click', 'a', function(e){
10617        const linkText = e.currentTarget.text ? e.currentTarget.text.toLowerCase() : "";
10618        stanford.analytics.send(stanford.analytics.createNavigationEvent("global hamburger", e.currentTarget.text, linkText, 'navigation'));
10619    });
10620
10621    $('.masthead_menu_revealbox').on('click', function(){
10622        let text,
10623            parentText;
10624
10625        if ($(this).hasClass('masthead_menu_sub_link')) {
10626            let parentElement = $(this).prevAll('.masthead_menu_revealbox').not('.masthead_menu_sub_link').first();
10627            parentText = parentElement.find('a').text();
10628            text = $(this).find('a').text();
10629        } else {
10630            text = $(this).find('a').text();
10631        }
10632        stanford.analytics.send(stanford.analytics.createNavigationEvent("global hamburger", parentText || text, text, 'navigation'));
10633    });
10634
10635    //Reset active view to list if navigated away from directories
10636    if(!SHC.ui.Search.DirectoryUtil.isDirectoryPage() && !SHC.util.isClinicPage() && !SHC.util.isDoctorProfilePage()) {
10637        SHC.util.setCookie('activeView', 'list', 1, "/");
10638    }
10639
10640    function closeMenu(trigger, e) {
10641        if($offcanvasToggle.hasClass("active")) {
10642            if($(e.target).closest($sidebarOffcanvas).length === 0 && $(e.target).closest($offcanvasToggle).length === 0) {
10643                adjustMastheadWidthOnOffClick();
10644                animateSidebarClose();
10645                var $ulID = $('#subnav-masthead-nav');
10646                $ulID.css({margin: "0 auto", width: "100%"});
10647                //for ipad screensizes
10648                if(Modernizr.mq('(min-width: 768px)') && Modernizr.mq('(max-width: 1023px)')) {
10649                    subnavHideShowHelper();
10650                    $ulID.animate({paddingRight: "30px"}, 400);
10651                }
10652
10653                //for desktop screensizes
10654                if(Modernizr.mq('(min-width: 1024px)')) {
10655                    subnavHideShowHelper();
10656                    $ulID.animate({paddingRight: "0"}, 400);
10657                }
10658                if(trigger === 'swipeleft') {
10659                    $('.menu-toggle').removeClass("hovering");
10660                }
10661            }
10662        }
10663    }
10664
10665    function animateSidebarClose() {
10666        $offcanvas.switchClass("open-offcanvas", "", 400);
10667        $sidebarOffcanvas.animate({
10668            left: '-240px',
10669            duration: 400
10670        });
10671        if (SHC.ui.screenMode == "small"){
10672            mobileAdjustments('close');
10673        } else {
10674            desktopAdjustments('close');
10675        }
10676    }
10677
10678    function mobileAdjustments(direction) {
10679        if(SHC.util.isAndroid()) {
10680            if(direction === 'open') {
10681                $mainContainer.css('position', 'fixed');
10682                $sidebarOffcanvas.css('overflow-y', 'scroll');
10683                $sidebarOffcanvas.scrollTop(0);
10684            } else {
10685                $mainContainer.css('position', 'inherit');
10686                $sidebarOffcanvas.css('overflow-y', 'initial');
10687            }
10688        } else if(SHC.util.isIOS()) {
10689            if(direction === 'open') {
10690                $sidebarOffcanvas.css('overflow-y', 'scroll');
10691                $mainContainer.css('position', 'fixed');
10692                $mainContainer.css('overflow', 'hidden');
10693                $main.css('position', 'fixed');
10694                $sidebarOffcanvas.scrollTop(0);
10695            } else {
10696                $sidebarOffcanvas.css('overflow-y', 'initial');
10697                if(SHC.ui.screenMode === 'small'){
10698                    $mainContainer.css('position', 'inherit');
10699                    $mainContainer.css('max-width', '100%');
10700                    $mainContainer.css('overflow', 'hidden');
10701                }
10702                $main.css('position', 'absolute');
10703            }
10704        }
10705    }
10706
10707    function desktopAdjustments(direction) {
10708        if ($menu.height() > window.innerHeight) {
10709            if (direction === 'open') {
10710                $sidebarOffcanvas.addClass('hide-scrollbar');
10711                $sidebarOffcanvas.css('overflow-y', 'scroll');
10712                $sidebarOffcanvas.scrollTop(0);
10713            } else {
10714                $sidebarOffcanvas.removeClass('hide-scrollbar');
10715                $mainContainer.css('position', 'inherit');
10716                $sidebarOffcanvas.css('overflow-y', 'hidden');
10717            }
10718        }
10719    }
10720
10721    function adjustMastheadWidthOnMenuToggle() {
10722        mastHeadMenuToggleHelper();
10723        subnavMenuToggleHelper("#subnavigation-bar", "#subnav-masthead-nav");
10724    }
10725
10726    function mastHeadMenuToggleHelper() {
10727        var menu = $('.masthead-affixed .menu-toggle');
10728        if(menu.hasClass('active')) {
10729            //expand when menu closes
10730            $('.masthead-affixed').animate({left: "0", width: "100%"}, 400);
10731            $('#masthead').animate({left: "0", width: "100%"}, 400);
10732            $('.subnav-items.desktop').animate({left: "0", width: "100%"}, 400);
10733            $('#masthead-nav').css({margin: "0 auto", width: "100%"});
10734            if(Modernizr.mq('(min-width: 1024px)') && Modernizr.mq('(max-width: 1140px)')) {
10735                $('.masthead-dropdown').show();
10736            }
10737        }
10738        else {
10739            $('.masthead-affixed').animate({left: "240", width: ($(window).width() - 240) + "px"}, 400);
10740            $('#masthead').animate({left: "240", width: ($(window).width() - 240) + "px"}, 400);
10741            $('.subnav-items.desktop').animate({left: "240", width: ($(window).width() - 240) + "px"}, 400);
10742            if(Modernizr.mq('(min-width: 1024px)') && Modernizr.mq('(max-width: 1140px)')) {
10743                $('.masthead-dropdown').hide();
10744            }
10745
10746            if(Modernizr.mq('(min-width: 768px)') && Modernizr.mq('(max-width: 1023px)')) {
10747                $('#masthead-nav').animate({margin: "0", width: ($(window).width() - 240) + "px"}, 400);
10748                $('#masthead > .container').css("padding-left", "10px");
10749            }
10750        }
10751    }
10752
10753    function subnavHideShowHelper() {
10754        $('.subnav-item').hide();
10755        $('.about-clinical-trial').show();
10756        $('.find-clinical-trial').show();
10757        $('.patient-stories').show();
10758    }
10759
10760    function subnavMenuToggleHelper(containerIDString, ulIDString) {
10761        var $containerID = $(containerIDString);
10762        var $ulID = $(ulIDString);
10763        if($containerID.length && $ulID.length) {
10764            var menu = $('.masthead-affixed .menu-toggle');
10765            if(menu.hasClass('active')) {
10766                //expand when menu closes
10767                $containerID.animate({left: "0", width: "100%"}, 400);
10768                //for ipad screensizes
10769                if(Modernizr.mq('(min-width: 768px)') && Modernizr.mq('(max-width: 1023px)')) {
10770                    subnavHideShowHelper();
10771                    $ulID.animate({paddingRight: "30px"}, 400);
10772                }
10773
10774                //for desktop screensizes
10775                if(Modernizr.mq('(min-width: 1024px)')) {
10776                    subnavHideShowHelper();
10777                    $ulID.animate({paddingRight: "0"}, 400);
10778                }
10779            }
10780            else {
10781                //for ipad screensizes
10782                if(Modernizr.mq('(min-width: 768px)') && Modernizr.mq('(max-width: 1023px)')) {
10783                    $('.subnav-item').hide();
10784                    $('.about-clinical-trial').show();
10785                    $('.find-clinical-trial').show();
10786                    $ulID.animate({paddingRight: "270px"}, 400);
10787                }
10788
10789                //for desktop screensizes
10790                if(Modernizr.mq('(min-width: 1024px)')) {
10791                    subnavHideShowHelper();
10792                    $ulID.animate({paddingRight: "270px"}, 400);
10793                }
10794            }
10795        }
10796    }
10797
10798    function adjustMastheadWidthOnOffClick() {
10799        var menu = $('.masthead-affixed .menu-toggle');
10800        if(menu.hasClass('active')) {
10801            //expand when menu closes
10802            $('.masthead-affixed').animate({left: "0", width: "100%"}, 400);
10803            $('#masthead').animate({left: "0", width: "100%"}, 400);
10804            $('.subnav-items.desktop').animate({left: "0", width: "100%"}, 400);
10805            $('#masthead-nav').css({margin: "0 auto", width: "100%"});
10806            $('a.menu-toggle').removeClass('active');
10807            $('.menu-toggle span.hidden-xs').text('Menu');
10808            if($(window).width() >= 1024 && $(window).width() <= 1140) {
10809                $('.masthead-dropdown').show();
10810            }
10811        }
10812        else {
10813            $('.masthead-affixed').animate({left: "240", width: ($(window).width() - 240) + "px"}, 400);
10814            $('#masthead').animate({left: "240", width: ($(window).width() - 240) + "px"}, 400);
10815            $('a.menu-toggle').removeClass('active');
10816            $('.menu-toggle span.hidden-xs').text('Menu');
10817            if($(window).width() >= 1024 && $(window).width() <= 1140) {
10818                $('.masthead-dropdown').hide();
10819            }
10820            if($(window).width() >= 768 && $(window).width() <= 1023) {
10821                $('#masthead-nav').animate({margin: "0", width: ($(window).width() - 240) + "px"}, 400);
10822                $('#masthead > .container').css("padding-left", "10px");
10823            }
10824        }
10825    }
10826
10827    function setActivePage() {
10828        var path = SHC.util.adjustPath(location.pathname);
10829        var menu_link_selector = "#menu-main-nav .masthead_menu_link a, #menu-secondary-nav .masthead-menu-revealbox a";
10830
10831        $(menu_link_selector).each(function(i, e) {
10832            var linkLocation = $(e).attr('href');
10833            if(linkLocation) {
10834                linkLocation = SHC.util.getPathFromUrl(SHC.util.adjustPath(linkLocation));
10835                if(linkLocation !== "" && linkLocation !== "/" && path.indexOf(linkLocation) > -1) {
10836                    $(e).addClass("active");
10837                    // break the loop
10838                    return false;
10839                }
10840            }
10841        });
10842    }
10843
10844    setActivePage();
10845
10846    $(window).on('resize', function() {
10847        var windowWidth = $(window).width();
10848        if ($("#main").hasClass("open-offcanvas") !== true){
10849            adjustMastheadLinks();
10850        }
10851        if($('.menu-toggle').hasClass('active')) {
10852            $('#masthead').css({left: "240", width: ($(window).width() - 240) + "px"});
10853        }
10854        if(windowWidth >= 1024 && windowWidth < 1140) {
10855            if($('.menu-toggle').hasClass('active')) {
10856                $('.masthead-dropdown').hide();
10857                $('#masthead-nav').css({width: "100%", margin: "0 auto"});
10858                $('#masthead > .container').css("padding-left", "20px");
10859            } else {
10860                $('.masthead-dropdown').show();
10861            }
10862        } else if(windowWidth > 1140) {
10863            $('.masthead-dropdown').show();
10864        }
10865        if(Modernizr.mq('(min-width: 768px)') && Modernizr.mq('(max-width: 1023px)')) {
10866            if($('.menu-toggle').hasClass('active')) {
10867                $('#masthead-nav').css({width: ($(window).width() - 240) + "px", margin: "0"})
10868                $('#masthead > .container').css("padding-left", "10px");
10869            } else {
10870                $('#masthead-nav').css({width: "100%", margin: "0 auto"})
10871                $('#masthead > .container').css("padding-left", "20px");
10872            }
10873        }
10874        if(Modernizr.mq('(max-width: 767px)')) {
10875            $('#masthead-wrapper').hide();
10876        }
10877        else {
10878            $('#masthead-wrapper').show();
10879        }
10880    });
10881    if(navigator.userAgent.match(/(iPod|iPhone|iPad)/)) {
10882        $('#sidebar').css('z-index', 100);
10883    }
10884});
10885
10886shcDOMContentLoaded(function() {
10887
10888    if (jQuery(".masthead").length) {
10889        var masthead = new SHC.ui.Masthead();
10890    }
10891
10892    var subNav = $('#subnavigation-bar');
10893    var $subnavRibbon = $('#subnav-masthead-nav');
10894    var carat = $('#subnav-masthead-nav span.carat');
10895    var currentLinkParams = window.location.href.split("/");
10896    var url = window.location.href;
10897
10898    //Check for the presence of application/ct.html, about.html, /trials/, and maunal trials
10899    if( url.indexOf( 'about.html' ) > 0 && url.indexOf( 'trials' ) > 0 ) {
10900
10901        $( '.subnav-ct' ).find( 'a.about-clinical-trial-link' ).addClass( 'activesection' );
10902
10903    } else if( url.indexOf( 'application/ct.html' ) > 0 || url.indexOf( 'trials.html' ) > 0 ) {
10904
10905        $( '.subnav-ct' ).find( 'a.find-clinical-trial-link' ).addClass( 'activesection' );
10906
10907    } else if( url.indexOf( 'manual' ) > 0 && url.indexOf( 'trials' ) > 0 ) {
10908
10909        $( '.subnav-ct' ).find( 'a.find-clinical-trial-link' ).addClass( 'activesection' );
10910    }
10911
10912    //helper function to determine if a valid clinicaltrials.gov trial exists in window href
10913    var isValidTrialHelper = function(params) {
10914        for (var i = 0; i < params.length; i++) {
10915            if (params[i].indexOf("NCT") > -1) {
10916                return true
10917            }
10918        }
10919        return false;
10920    };
10921
10922    var highlightLink = function(params, screenSize) {
10923        //remove active if exists on any item
10924        var subnavItems;
10925        if (screenSize === 'small') {
10926            subnavItems = $('#mobile-items').find('.mobile-subnav-item');
10927        } else if (screenSize === 'medium') {
10928            subnavItems = $subnavRibbon.find('.subnav-item');
10929        }
10930        subnavItems.removeClass('activesection');
10931
10932        // about page, about.html, highlight "About Clinical Trials"
10933        if (params.indexOf("about.html") > -1 || params.indexOf("about.html#") > -1) {
10934            subnavItems.find("a.about-clinical-trial-link").addClass("activesection");
10935        } else if (params.indexOf("about.html?wcmmode=disabled") > -1 || params.indexOf("about.html?wcmmode=disabled#") > -1) {
10936            subnavItems.find("a.about-clinical-trial-link").addClass("activesection");
10937        }
10938        // find a clinical trial, application/ct.html, highlight "Find a Clinical Trial"
10939        else if (params.indexOf("application/ct.html") > -1 || params.indexOf("application/ct.html#") > -1) {
10940            subnavItems.find("a.find-clinical-trial-link").addClass("activesection");
10941        } else if (params.indexOf("application/ct.html?wcmmode=disabled") > -1 || params.indexOf("application/ct.html?wcmmode=disabled#") > -1) {
10942            subnavItems.find("a.find-clinical-trial-link").addClass("activesection");
10943        }
10944        // if manual trials, highlight "Find a Clinical Trial"
10945        else if (params.indexOf("manual") > -1 && params.indexOf("trials") > -1) {
10946            subnavItems.find("a.find-clinical-trial-link").addClass("activesection");
10947        }
10948        // if from clinicaltrials.gov trials, highlight "Find a Clinical Trial"
10949        else if (params.indexOf("trials") > -1 && isValidTrialHelper(params)) {
10950            subnavItems.find("a.find-clinical-trial-link").addClass("activesection");
10951        }
10952
10953    };
10954
10955
10956    //helper function to manipulate and construct More DOM
10957
10958    var implementMoreItem = function(items) {
10959        for (var i = 0; i < items.length; i++) {
10960            var el = $(items[i]).remove();
10961            el.removeClass('subnav-item').addClass('more-subnav-item');
10962            $('#more-items-list').append(el);
10963        }
10964    };
10965
10966    //for mobile screen sizes
10967    if (SHC.ui.screenMode === 'small' && carat) {
10968        if (carat.length > 0) {
10969            subNav.after('<div id="mobile-items-view" class="row" style="display: none"><div class="col-xs-12"> <ul id="mobile-items"></ul></div></div>');
10970            var subnavItems = $subnavRibbon.find('.subnav-item');
10971            for (var i = 0; i < subnavItems.length; i++) {
10972                var item = $(subnavItems[i]).removeClass('subnav-item').addClass('mobile-subnav-item');
10973                $('#mobile-items').append(item);
10974            }
10975
10976            var caratClickCallback = function() {
10977                var mobileItemsView = $('#mobile-items-view');
10978                if (carat.hasClass('carat')) {
10979                    carat.removeClass('carat').addClass('close-carat');
10980                    subNav.addClass('mobile-items-open');
10981                    mobileItemsView.show();
10982                } else {
10983                    carat.removeClass('close-carat').addClass('carat');
10984                    subNav.removeClass('mobile-items-open');
10985                    mobileItemsView.hide();
10986                }
10987            };
10988
10989            // highlight the appropriate link based on current page
10990            highlightLink(currentLinkParams, 'small');
10991
10992            carat.click(caratClickCallback);
10993        }
10994    }
10995
10996    // Determine if "More" sub-nav item is needed, for large screens
10997    if (SHC.ui.screenMode !== 'small') {
10998        //just in case, hide it
10999        $subnavRibbon.css('visibility', 'hidden');
11000        var subnavWidth = $subnavRibbon.width();
11001        var $subnavItems = $subnavRibbon.find('.subnav-item');
11002        var $moreItem = $('#more-item');
11003        var $moreItemsContainer = $('#more-items-container');
11004        var itemWidthRunningSum = 0;
11005        var moreItems = [];
11006
11007        // highlight the appropriate link based on current page
11008        highlightLink(currentLinkParams, 'medium');
11009
11010        //disable this more dropdown functionality for now
11011        if (false) {
11012
11013           // calculate the running width of each of the items in subnav-masthead-nav to determine if More is needed
11014            $subnavItems.each(function() {
11015                var currentItem = $(this);
11016                if (!currentItem.hasClass('more-item')) {
11017                    itemWidthRunningSum += currentItem.width();
11018                    if (itemWidthRunningSum > subnavWidth - 200) {
11019                        moreItems.push(currentItem);
11020                    }
11021                }
11022            });
11023
11024            //show More if moreItems than ul can fit
11025            if (moreItems.length > 0) {
11026                implementMoreItem(moreItems);
11027                $moreItem.show();
11028            }
11029        }
11030        if (Modernizr.mq('(min-width: 768px)') && Modernizr.mq('(max-width: 1023px)')) {
11031            $('#subnav-masthead-nav').css('paddingRight', '30px');
11032        }
11033
11034       // either way, finally set visibility to visible, once DOM manipulations are finished to avoid flash of content
11035        $subnavRibbon.css('visibility', 'visible');
11036
11037       // click handler for More button
11038        $moreItem.off('click').on('click', function(e) {
11039            e.preventDefault();
11040
11041           if ($moreItem.hasClass('active')) {
11042                $moreItem.removeClass('active');
11043                $moreItemsContainer.hide();
11044            } else {
11045                $moreItem.addClass('active');
11046                $moreItemsContainer.insertAfter($moreItem);
11047                $moreItemsContainer.show();
11048            }
11049        });
11050    }
11051});
11052
11053/*
11054 * To change this license header, choose License Headers in Project Properties.
11055 * To change this template file, choose Tools | Templates
11056 * and open the template in the editor.
11057 */
11058
11059/*! http://mths.be/placeholder v2.0.8 by @mathias */
11060;(function(window, document, $) {
11061
11062    // Opera Mini v7 doesn’t support placeholder although its DOM seems to indicate so
11063    var isOperaMini = Object.prototype.toString.call(window.operamini) === '[object OperaMini]';
11064    var isInputSupported = 'placeholder' in document.createElement('input') && !isOperaMini;
11065    var isTextareaSupported = 'placeholder' in document.createElement('textarea') && !isOperaMini;
11066    var prototype = $.fn;
11067    var valHooks = $.valHooks;
11068    var propHooks = $.propHooks;
11069    var hooks;
11070    var placeholder;
11071
11072    if (isInputSupported && isTextareaSupported) {
11073
11074        placeholder = prototype.placeholder = function() {
11075            return this;
11076        };
11077
11078        placeholder.input = placeholder.textarea = true;
11079
11080    } else {
11081        placeholder = prototype.placeholder = function() {
11082            var $this = this;
11083            $this
11084                .filter((isInputSupported ? 'textarea' : ':input') + '[placeholder]')
11085                .not('.placeholder')
11086                .bind({
11087                    'focus.placeholder': clearPlaceholder,
11088                    'blur.placeholder': setPlaceholder
11089                })
11090                .data('placeholder-enabled', true)
11091                .trigger('blur.placeholder');
11092            return $this;
11093        };
11094
11095        placeholder.input = isInputSupported;
11096        placeholder.textarea = isTextareaSupported;
11097
11098        hooks = {
11099            'get': function(element) {
11100                var $element = $(element);
11101
11102                var $passwordInput = $element.data('placeholder-password');
11103                if ($passwordInput) {
11104                    return $passwordInput[0].value;
11105                }
11106
11107                return $element.data('placeholder-enabled') && $element.hasClass('placeholder') ? '' : element.value;
11108            },
11109            'set': function(element, value) {
11110                var $element = $(element);
11111
11112                var $passwordInput = $element.data('placeholder-password');
11113                if ($passwordInput) {
11114                    return $passwordInput[0].value = value;
11115                }
11116
11117                if (!$element.data('placeholder-enabled')) {
11118                    return element.value = value;
11119                }
11120                if (value === '') {
11121                    element.value = value;
11122                    // Issue #56: Setting the placeholder causes problems if the element continues to have focus.
11123                    if (element !== safeActiveElement()) {
11124                        // We can't use `triggerHandler` here because of dummy text/password inputs :(
11125                        setPlaceholder.call(element);
11126                    }
11127                } else if ($element.hasClass('placeholder')) {
11128                    clearPlaceholder.call(element, true, value) || (element.value = value);
11129                } else {
11130                    element.value = value;
11131                }
11132                // `set` can not return `undefined`; see http://jsapi.info/jquery/1.7.1/val#L2363
11133                return $element;
11134            }
11135        };
11136
11137        if (!isInputSupported) {
11138            valHooks.input = hooks;
11139            propHooks.value = hooks;
11140        }
11141        if (!isTextareaSupported) {
11142            valHooks.textarea = hooks;
11143            propHooks.value = hooks;
11144        }
11145
11146        shcDOMContentLoaded(function() {
11147            // Look for forms
11148            $(document).delegate('form', 'submit.placeholder', function() {
11149                // Clear the placeholder values so they don't get submitted
11150                var $inputs = $('.placeholder', this).each(clearPlaceholder);
11151                setTimeout(function() {
11152                    $inputs.each(setPlaceholder);
11153                }, 10);
11154            });
11155        });
11156
11157        // Clear placeholder values upon page reload
11158        $(window).bind('beforeunload.placeholder', function() {
11159            $('.placeholder').each(function() {
11160                this.value = '';
11161            });
11162        });
11163
11164    }
11165
11166    function args(elem) {
11167        // Return an object of element attributes
11168        var newAttrs = {};
11169        var rinlinejQuery = /^jQuery\d+$/;
11170        $.each(elem.attributes, function(i, attr) {
11171            if (attr.specified && !rinlinejQuery.test(attr.name)) {
11172                newAttrs[attr.name] = attr.value;
11173            }
11174        });
11175        return newAttrs;
11176    }
11177
11178    function clearPlaceholder(event, value) {
11179        var input = this;
11180        var $input = $(input);
11181        if (input.value === $input.attr('placeholder') && $input.hasClass('placeholder')) {
11182            if ($input.data('placeholder-password')) {
11183                $input = $input.hide().next().show().attr('id', $input.removeAttr('id').data('placeholder-id'));
11184                // If `clearPlaceholder` was called from `$.valHooks.input.set`
11185                if (event === true) {
11186                    return $input[0].value = value;
11187                }
11188                $input.focus();
11189            } else {
11190                input.value = '';
11191                $input.removeClass('placeholder');
11192                input === safeActiveElement() && input.select();
11193            }
11194        }
11195    }
11196
11197    function setPlaceholder() {
11198        var $replacement;
11199        var input = this;
11200        var $input = $(input);
11201        var id = this.id;
11202        if (input.value === '') {
11203            if (input.type === 'password') {
11204                if (!$input.data('placeholder-textinput')) {
11205                    try {
11206                        $replacement = $input.clone().attr({ 'type': 'text' });
11207                    } catch(e) {
11208                        $replacement = $('<input>').attr($.extend(args(this), { 'type': 'text' }));
11209                    }
11210                    $replacement
11211                        .removeAttr('name')
11212                        .data({
11213                            'placeholder-password': $input,
11214                            'placeholder-id': id
11215                        })
11216                        .bind('focus.placeholder', clearPlaceholder);
11217                    $input
11218                        .data({
11219                            'placeholder-textinput': $replacement,
11220                            'placeholder-id': id
11221                        })
11222                        .before($replacement);
11223                }
11224                $input = $input.removeAttr('id').hide().prev().attr('id', id).show();
11225                // Note: `$input[0] != input` now!
11226            }
11227            $input.addClass('placeholder');
11228            $input[0].value = $input.attr('placeholder');
11229        } else {
11230            $input.removeClass('placeholder');
11231        }
11232    }
11233
11234    function safeActiveElement() {
11235        // Avoid IE9 `document.activeElement` of death
11236        // https://github.com/mathiasbynens/jquery-placeholder/pull/99
11237        try {
11238            return document.activeElement;
11239        } catch (exception) {}
11240    }
11241
11242}(this, document, jQuery));
11243
11244
11245
11246
11247shcDOMContentLoaded(function() {
11248    if (jQuery("#in-page-nav-wrapper").length) {
11249        SHC.ui.InPageNavigation = new SHC.ui.InPageNav('#in-page-nav-wrapper');
11250    }
11251});
11252
11253shcDOMContentLoaded(function(){
11254    if(jQuery('.doctor-profile') && jQuery('.doctor-profile').length > 0) {
11255        // var modal = new SHC.ui.PhyscianProfile("#read-more");   
11256        var imageErrorHandler = function(e) {
11257            $(this).attr("src", "/etc/clientlibs/shc/main/img/shc-logo-profiledeck.jpg");
11258        };
11259        var img = $("#profilePhoto");
11260        img.on("error", imageErrorHandler);
11261        img.attr("src", img.attr("src"));
11262        jQuery("#modal").addClass("doc-modal");
11263    }
11264    if (sessionStorage.getItem("doctorPagination") && sessionStorage.getItem("prevSearchPage")) {
11265        $('.result-nav').removeClass('hidden');
11266        var doctorPagination = JSON.parse(sessionStorage.getItem("doctorPagination")).results.data,
11267            resultIndex = -1,
11268            prevResult = "",
11269            nextResult = "";
11270
11271
11272        for (var i = 0; i < doctorPagination.length; i++) {
11273            if (doctorPagination[i].url.endsWith(window.location.pathname)) {
11274                resultIndex = i;
11275                break;
11276            }
11277        }
11278        if (resultIndex > -1) {
11279            prevResult = resultIndex > 0 ? doctorPagination[i-1].url : prevResult;
11280            nextResult = resultIndex < doctorPagination.length-1 ? doctorPagination[i+1].url : nextResult;
11281        }
11282
11283        if (nextResult === "") {
11284            $('span.next-phys').removeClass('hidden');
11285        } else {
11286            $('a.next-phys').attr('href', nextResult).removeClass('hidden');
11287        }
11288        if (prevResult === "") {
11289            $('span.prev-phys').removeClass('hidden');
11290        } else {
11291            $('a.prev-phys').attr('href', prevResult).removeClass('hidden');
11292        }
11293        $('.search-return').attr('href', sessionStorage.getItem("prevSearchPage"));
11294    }
11295});
11296
11297
11298
11299
11300shcDOMContentLoaded(function() {
11301    if (jQuery(".thematic-panel-component").length) {
11302        var thematicPanel = new SHC.ui.ThematicPanel(".thematic-panel-component");
11303
11304        // Aspect ratio fix:
11305        // add "portrait" class when aspect ratio is vertical
11306        jQuery(".thematic-panel-component .image-floater img").each(
11307            function (idx, el) {
11308                var jq = jQuery(el);
11309                jq.on("load", function () {
11310                    if (jq.width() / jq.height() < 1) {
11311                        jq.addClass("portrait");
11312                    }
11313                });
11314            }
11315        );
11316
11317        jQuery(document).on('ready',function(){
11318            if(SHC.ui.screenMode !== 'small'){
11319                lazyload();
11320            }
11321        });
11322    
11323        jQuery(window).on('resizeEnd',function(){
11324            if(SHC.ui.screenMode !== 'small'){
11325                lazyload();
11326            }
11327        });
11328    
11329        var lazyload = function(){
11330            var parent = jQuery(".thematic-panel-component");
11331            if (parent.length) {
11332                parent.find('img.lazy-load').each(function(){
11333                    var imagePath = jQuery(this).attr('data-attr-src');
11334                    jQuery(this).attr('src', imagePath);
11335                });
11336            }
11337        };
11338    }
11339});
11340
11341$(function () {
11342  var debounce = function (fn) {
11343    var timeout;
11344    return function () {
11345      var context = this;
11346      var args = arguments;
11347
11348      if (timeout) {
11349        cancelAnimationFrame(timeout);
11350      }
11351
11352      timeout = requestAnimationFrame(function () {
11353        fn.apply(context, args);
11354      });
11355    };
11356  };
11357
11358  function onResize() {
11359    var opts = {};
11360    if (window.innerWidth < SHC.ui.ScreenSizes.large) {
11361      opts.height = 60;
11362      opts.wrap = 'word';
11363    }
11364    $('.tag-feed-item .description').dotdotdot(opts);
11365  }
11366  $(window).resize(debounce(onResize));
11367  onResize();
11368});
11369
11370shcDOMContentLoaded(function() {
11371    var StoryGallery = {
11372        init: function() {
11373            var _that = this;
11374            $(window).on('load', function(e) {
11375                if(window.location.href.indexOf('/presentation-mode/') > -1) {
11376                    $('#presentation-mode .close').on('click', function(e) {
11377                        _that.buildStoryGallery();
11378                    });
11379                } else {
11380                    _that.buildStoryGallery();
11381                }
11382            });
11383        },
11384        buildStoryGallery: function() {
11385            this.VISIBLE_STORIES = 8;
11386            var _that = this;
11387            $('.story-gallery').each(function(e) {
11388                var $gallery = $(this);
11389                _that.formatElements($gallery);
11390                $(window).on('resizeEnd', function (e) {
11391                    _that.formatElements($gallery);
11392                });
11393                _that.selectTab($gallery, _that.VISIBLE_STORIES);
11394            });
11395            _that.attachBindings();
11396
11397        },
11398        formatElements: function($gallery) {
11399            //truncate and add ellipsis to overflowing titles
11400            $gallery.find('.story-title').each(function(e) {
11401                $(this).dotdotdot();
11402            });
11403
11404            //reformat label menu to fit screen
11405            var $tabs = $gallery.find('.row.tabs .tab'),
11406                $more = $gallery.find('.tab.more .more-tabs'),
11407                $moreTabs = $more.find('.tab'),
11408                $tabContainer = $gallery.find('.row.tabs'),
11409                totalWidth = 0,
11410                moreWidth = 120,
11411                containerWidth = $tabContainer.width() - moreWidth;
11412            //return any tabs in more back to main tab row
11413            for(var i = $moreTabs.length - 1; i > -1; i--) {
11414                $tabContainer.append($moreTabs.get(i));
11415            }
11416            $more.closest('.tab.more').addClass('hidden');
11417            //append the tabs back to the tab row
11418            for(var i = 0; i < $tabs.length; i++) {
11419                $tabContainer.append($tabs.get(i));
11420            }
11421            //subtract one at a time until tolerable width, add subtracted to list
11422            for(var i = 0; i < $tabs.length - 1; i++) {
11423                var $tab = $($tabs.get(i));
11424                totalWidth += $tab.outerWidth(true);
11425                if(totalWidth >= containerWidth) {
11426                    $more.append($tab);
11427                    $more.closest('.tab.more').removeClass('hidden');
11428                }
11429            }
11430        },
11431        selectTab: function ($gallery, visibleStories) {
11432            //hide irrelevant stories
11433            $gallery.find('.stories .hidden, .stories .relevant').each(function(e) {
11434                $(this).removeClass('hidden').removeClass('relevant');
11435            });
11436            var activeTab = $gallery.find('.row.tabs .tab.active span').text();
11437            if (activeTab !== "All") {
11438                $gallery.find('.story').each(function(e) {
11439                    var $this = $(this),
11440                        isRelevant = false;
11441                    $this.find('.story-label').each(function(e) {
11442                        if ($(this).text() === activeTab) {
11443                            isRelevant = true;
11444                        }
11445                    });
11446                    if (!isRelevant) {
11447                        $this.addClass('hidden');
11448                    }
11449                });
11450            }
11451
11452            //hide any relevant stories past visibleStories
11453            var $relevantStories = $gallery.find('.story:not(.hidden)');
11454            if ($relevantStories.length > visibleStories) {
11455                for (var i = visibleStories; i < $relevantStories.length; i++) {
11456                    $($relevantStories.get(i)).addClass('hidden').addClass('relevant');
11457                }
11458            }
11459
11460            //hide irrelevant labels
11461            $gallery.find('.stories:not(.hidden) .story-label').each(function(e) {
11462                var $this = $(this);
11463                if(activeTab === "All") {
11464                    //if not first span
11465                    if(!$this.is(':first-of-type')) {
11466                        $this.addClass('hidden');
11467                    }
11468                } else {
11469                    if($this.text() !== activeTab) {
11470                        $this.addClass('hidden');
11471                    }
11472                }
11473            });
11474
11475            //show/hide view more btn
11476            var totalRelevantStories = $gallery.find('.story:not(.hidden), .story.hidden.relevant').length,
11477                $viewMore = $gallery.find('.row.more');
11478            if(visibleStories >= totalRelevantStories) {
11479                $viewMore.addClass('hidden');
11480            } else {
11481                $viewMore.removeClass('hidden');
11482            }
11483        },
11484        attachBindings: function() {
11485            var _that = this;
11486
11487            //menu more button
11488            $('.story-gallery .tab.more').on('click', function(e) {
11489                var $this = $(this);
11490
11491                $this.toggleClass('open');
11492            });
11493
11494            //menu click
11495            $('.story-gallery').on('click', '.tab:not(.more)', function(e) {
11496                var $this = $(this),
11497                    $gallery = $this.closest('.story-gallery'),
11498                    $row = $this.closest('.row');
11499
11500                $row.find('.tab.active').removeClass('active');
11501                $gallery.find('.tab.open').toggleClass('open');
11502                $this.addClass('active');
11503                _that.selectTab($this.closest('.story-gallery'), _that.VISIBLE_STORIES);
11504            });
11505
11506            //show more stories with view more
11507            $('.story-gallery .row.more .btn').on('click', function(e) {
11508                var $this = $(this),
11509                    $gallery = $this.closest('.story-gallery'),
11510                    newVisibleStories = $gallery.find('.story:not(.hidden)').length + _that.VISIBLE_STORIES;
11511
11512                _that.selectTab($gallery, newVisibleStories);
11513            });
11514
11515            new SHC.ui.PresentationMode($('.story-gallery').find('.presentation'), true);
11516        }
11517    }.init();
11518});
11519
11520$(function () {
11521    var labMasthead = $('.masthead-cmp.stanfordlab');
11522
11523    if (labMasthead.size() > 0) {
11524        var hamburgerButton = labMasthead.find('.hamburger-icon');
11525        var openHamburgerMenu = function (e) {
11526            e.preventDefault();
11527            e.stopPropagation();
11528            hamburgerButton.toggleClass('open');
11529            labMasthead.toggleClass('menu-open');
11530        }
11531        var headerLogoAnimation = function () {
11532            var animStart = 35;
11533            var animEnd = 40;
11534            scrollPosition = $(window).scrollTop();
11535
11536            // scrollPosition conditional for logo, masthead size, and fallback conditions
11537            if (!jQuery('#modal-container').is(':visible') && $(window).width() > 767) {
11538                if (scrollPosition < animEnd) {
11539                    labMasthead.removeClass('collapsed');
11540                    labMasthead.find('.menu-icon-wrapper').addClass('visible-xs');
11541                } else {
11542                    labMasthead.addClass('collapsed');
11543                    labMasthead.find('.menu-icon-wrapper').removeClass('visible-xs');
11544                }
11545            }
11546        };
11547
11548        $(window).on('scroll', function () {
11549            headerLogoAnimation();
11550        });
11551
11552        hamburgerButton.off().on('click', openHamburgerMenu);
11553    }
11554});
11555jQuery(function(){
11556    if (jQuery(".aem-AuthorLayer-Edit").length>0) {
11557        jQuery(".wrapper-sticky").removeClass("wrapper-sticky");
11558    }
11559});
11560
11561$(function(){
11562    var loadTemplate = function(targetSelector, incomingdata, template) {
11563        jQuery(targetSelector).prepend(template(incomingdata));
11564    };
11565
11566    var createSpUrl = function(searchingFor){
11567        var searchVer = document.querySelector('meta[name="shc-search-version"]').content || "v1";
11568        var searchUrl = "/bin/api/"+searchVer+"/search.json";
11569        switch(searchingFor){
11570            case 'search-conditions-treatments':
11571                return searchUrl + '?do=organic_conds_txs&sp_s=sp_displayName&sp_c=750&x2=sp_isPatientEd&q2=true';
11572
11573            case 'search-conditions':
11574                return searchUrl + '/?do=organic_conds_txs&sp_s=sp_displayName&sp_c=750&x1=sp_type&q1=condition&x2=sp_isPatientEd&q2=true';
11575
11576            case 'search-treatments':
11577                return searchUrl + '/?do=organic_conds_txs&sp_s=sp_displayName&sp_c=750&x1=sp_type&q1=treatment&x2=sp_isPatientEd&q2=true';
11578
11579            case 'search-related':
11580                return searchUrl + '/?do=organic_conds_txs' + getRelatedSearchParams() + '&x3=sp_isPatientEd&q3=true&sp_s=sp_displayName&sp_c=750';
11581        }
11582    };
11583
11584    var getRelatedSearchParams = function(){
11585        var query = '';
11586        var metaConditionName = $('meta[name="sp_conditionName"]').attr('content');
11587        var metaTreatmentName = $('meta[name="sp_treatmentName"]').attr('content');
11588        var parentPageTitle = $('meta[name="parentPageTitle"]').attr('content');
11589
11590        if(typeof metaConditionName !== 'undefined' && metaConditionName.length > 0){
11591            query = '&x1=sp_type&q1=treatment&x2=sp_conditions&q2=' + metaConditionName;
11592
11593        }else if(typeof metaTreatmentName !== 'undefined' && metaTreatmentName.length > 0){
11594            query = '&x1=sp_type&q1=condition&x2=sp_treatments&q2=' + metaTreatmentName;
11595
11596        }else if(typeof parentPageTitle !== 'undefined' && parentPageTitle != ''){
11597            if(window.location.href.indexOf('medical-conditions') > 1){
11598                query = '&x1=sp_type&q1=treatment&x2=sp_conditions&q2=' + parentPageTitle;
11599            }else if(window.location.href.indexOf('medical-treatments') > 1){
11600                query = '&x1=sp_type&q1=condition&x2=sp_treatments&q2=' + parentPageTitle;
11601            }
11602        }
11603        return query;
11604    };
11605
11606    var makeRequest = function(spUrl, $targetSelector, $searchbarContainer){
11607        SHC.searchRequest = jQuery.ajax({
11608            url: spUrl,
11609            dataType: "jsonp",
11610            jsonp: 'callback',
11611            contentType: "application/json",
11612            success: function (data) {
11613                loadTemplate($targetSelector, data, JST["handlebars/searchbar-conditions-treatments.hbs"]);
11614                makeInputBox($searchbarContainer);
11615            }
11616        });
11617    };
11618
11619    var makeInputBox = function($searchbarContainer){
11620        $($searchbarContainer.find('select.select-auto-complete')).selectToAutocomplete();
11621        $searchbarContainer.removeClass('on-load-hidden');
11622        var $inputBox = $($searchbarContainer.find('input.select-auto-complete'));
11623        $inputBox.val('');
11624
11625        jQuery.ui.autocomplete.prototype._resizeMenu = function () {
11626            var ul = this.menu.element;
11627            ul.outerWidth(this.element.outerWidth());
11628        };
11629    };
11630
11631    var treatmentBoxMakeVisible = function(container){
11632        var $searchbarContainer = container.find('.searchbar-container');
11633        var $searchbarSelect = $searchbarContainer.find('select');
11634        var $searchbarArrow = $searchbarContainer.find('.submit-arrow');
11635        makeRequest(createSpUrl($searchbarArrow.attr('data-attr-search')), $searchbarSelect, $searchbarContainer);
11636    };
11637
11638    var loadBar = function(container){
11639        var $searchbarParent;
11640        if(container === null || container === ''){
11641            $searchbarParent = $('.searchbar-conditions-treatments');
11642        }else{
11643            $searchbarParent = container.find('.searchbar-conditions-treatments');
11644        }
11645
11646        if($searchbarParent.length > 0){
11647            $searchbarParent.each(function(){
11648                var $searchbarContainer = $(this).find('.searchbar-container');
11649                var $submitArrow = $searchbarContainer.find('.submit-arrow');
11650                var $selectBox = $searchbarContainer.find('select.select-auto-complete');
11651                var searchingFor = $submitArrow.attr('data-attr-search');
11652
11653                //do not attach if searchbar is inside non-visible treatment box
11654                if($searchbarContainer.closest('.treatment_box_container').length < 1 &&
11655                    $searchbarContainer.closest('.care_team_tabs').length < 1 ){
11656                    makeRequest(createSpUrl(searchingFor), $selectBox, $searchbarContainer);
11657                }
11658            });
11659        }
11660    };
11661
11662    $(window).on('load', function(){
11663        loadBar(null);
11664    });
11665
11666    $('#main').on('focus', '.searchbar-container input.select-auto-complete', function(){
11667        $(this).keydown();
11668    });
11669
11670    $('#main').on('click', '.searchbar-container input.select-auto-complete', function(){
11671        if(this.value === $(this).closest('.searchbar-container').find('select').attr('placeholder')){
11672            this.value = '';
11673            $(this).keydown();
11674        }
11675    });
11676
11677    $('#main').on('click', '.searchbar-container .submit-arrow', function(){
11678        var $clickParent = $(this).parent();
11679        var selectedOption = $clickParent.find('option:selected');
11680        var inputBox = $($clickParent.find('input.select-auto-complete')).val();
11681
11682        if(inputBox === 'Stanford Health Library'){
11683            window.open('http://healthlibrary.stanford.edu');
11684        }else if (inputBox !=='' && selectedOption.val() !== '') {
11685            window.location.href = selectedOption.attr('data-url').split('.html').join('/patient-care-resources.html');
11686        }
11687    });
11688
11689    //the treatment box uses cloning to bring content to visibility, the plugin needs to be attached after the element is brought to visibility
11690    //this custom event captures when a non visible tab containing a searchbar is brought to visibility and creates it by calling the plugin
11691    $(window).on('searchbarInTreatmentBox', function(event){
11692        if(SHC.ui.screenMode === "small"){
11693            var mobileVisible;
11694            if(event.mobile1.is(':visible')){
11695                mobileVisible = event.mobile1;
11696            }else if(event.mobile2.is(':visible')){
11697                mobileVisible = event.mobile2;
11698            }else if(event.mobile3.is(':visible')){
11699                mobileVisible = event.mobile3;
11700            }else if(event.mobile4.is(':visible')){
11701                mobileVisible = event.mobile4;
11702            }
11703            if(typeof mobileVisible !== 'undefined'){
11704                treatmentBoxMakeVisible(mobileVisible);
11705            }
11706        }else{
11707            treatmentBoxMakeVisible(event.desktopContainer);
11708        }
11709    });
11710
11711    $(window).on('searchbarInTabnav', function(){
11712        loadBar($('#tabbed-nav-content-wrapper'));
11713    });
11714});
11715$(document).ready(function () {
11716    $('.review_carousel_cc').each(function () {
11717        var carousel = new SHC.ui.ReviewCarousel(this);
11718    });
11719});
11720shcDOMContentLoaded(function () {
11721    if (jQuery(".reveal-box").length) {
11722        var revealBoxes = new SHC.ui.RevealBox(".reveal-box");
11723    }
11724});
11725$(document).ready(function () {
11726    var itemsLength = 3;
11727
11728    $('.prev-arrow').click(function () {
11729        if (!$(this).hasClass('disabled')) {
11730            var relatedContent = $(this).closest('.relatedcontent'),
11731                relatedItems = $(relatedContent).find('.related-content-item'),
11732                pagination = $(relatedContent).find('.pagination'),
11733                x = Number($(pagination).attr('data-x')),
11734                prevArrow = $(relatedContent).find('.prev-arrow'),
11735                nextArrow = $(relatedContent).find('.next-arrow');
11736            $(relatedItems).slice(0, x).removeClass('active');
11737
11738            if (x % 3 === 0) {
11739                x = (x - 3 <= 3) ? 3 : x - 3;
11740            } else {
11741                var topNumber = x % 3;
11742                x = x - topNumber;
11743            }
11744
11745            $(relatedItems).slice(0, x).addClass('active');
11746            var newY = (x - 3 < 3) ? 0 : x - 3;
11747            $(relatedItems).slice(0, newY).removeClass('active');
11748            if ($(relatedItems).first().is(":visible")) {
11749                $(prevArrow).addClass('disabled');
11750            } else {
11751                $(prevArrow).removeClass('disabled');
11752            }
11753            $(pagination).attr('data-x', x);
11754            $(pagination).attr('data-y', newY);
11755            var currentPage = Number($(relatedContent).find('.pagination-start').text());
11756            var pageEnd = Number($(relatedContent).find('.pagination-end').text());
11757            var newPage = currentPage - 1 <= 1 ? 1 : currentPage - 1;
11758            if (newPage !== pageEnd) {
11759                $(nextArrow).removeClass('disabled');
11760            }
11761            $(relatedContent).find('.pagination-start').text(newPage);
11762        }
11763    });
11764
11765    $('.next-arrow').click(function () {
11766        if (!$(this).hasClass('disabled')) {
11767            var relatedContent = $(this).closest('.relatedcontent'),
11768                relatedItems = $(relatedContent).find('.related-content-item'),
11769                pagination = $(relatedContent).find('.pagination'),
11770                x = Number($(pagination).attr('data-x')),
11771                prevArrow = $(relatedContent).find('.prev-arrow'),
11772                nextArrow = $(relatedContent).find('.next-arrow'),
11773                newX = (x + 3 <= relatedItems.length) ? x + 3 : relatedItems.length;
11774
11775            $(relatedItems).slice(0, newX).addClass('active');
11776            $(relatedItems).slice(0, x).removeClass('active');
11777            if ($(relatedItems).last().is(":visible")) {
11778                $(nextArrow).addClass('disabled');
11779            } else {
11780                $(nextArrow).removeClass('disabled');
11781            }
11782            $(pagination).attr('data-x', newX);
11783            $(pagination).attr('data-y', x);
11784            var currentPage = Number($(relatedContent).find('.pagination-start').text());
11785            var pageEnd = Number($(relatedContent).find('.pagination-end').text());
11786            var newPage = currentPage + 1 >= pageEnd ? pageEnd : currentPage + 1;
11787            if (newPage <= pageEnd && newPage !== 1) {
11788                $(prevArrow).removeClass('disabled');
11789            }
11790            $(relatedContent).find('.pagination-start').text(newPage);
11791        }
11792    });
11793
11794    function initializeRelatedContentPagination() {
11795        $('.relatedcontent').each(function (index, relatedContent) {
11796            var pagination = $(relatedContent).find('.pagination');
11797            var relatedItems = $(relatedContent).find('.related-content-item');
11798            for (var i = 0; i < relatedItems.length; i++) {
11799                if (i < 3) {
11800                    $(relatedItems).eq(i).addClass('active');
11801                }
11802            }
11803            $(pagination).attr('data-x', 3);
11804            $(pagination).attr('data-y', 0);
11805            $(relatedContent).find('.prev-arrow').addClass('disabled');
11806            $(relatedContent).find('.pagination-start').text(1);
11807            var items = (Math.ceil($(relatedItems).length / 3));
11808            $(relatedContent).find('.pagination-end').text(items || 1);
11809            if (items === null || items === 1) {
11810                $(relatedContent).find('.next-arrow').addClass('disabled');
11811            }
11812            if (relatedItems.length <= 3) {
11813                $(relatedContent).find('.prev-arrow').hide();
11814                $(relatedContent).find('.next-arrow').hide()
11815            }
11816        });
11817    }
11818
11819    function updateItemSize() {
11820        $('.relatedcontent').each(function (index, relatedContent) {
11821            var relatedItems = $(relatedContent).find('.related-content-item');
11822            var largerItem = relatedItems.length <= 2;
11823            if (largerItem) {
11824                for (var i = 0; i < relatedItems.length; i++) {
11825                    $(relatedItems).eq(i).removeClass('col-sm-4');
11826                    $(relatedItems).eq(i).removeClass('col-md-4');
11827                    $(relatedItems).eq(i).removeClass('col-xs-8');
11828                    $(relatedItems).eq(i).addClass('col-xs-12');
11829                    $(relatedItems).eq(i).addClass('col-sm-6');
11830                    $(relatedItems).eq(i).addClass('col-md-6');
11831                }
11832            }
11833        });
11834    }
11835
11836
11837    function init() {
11838        if ($(window).width() > 760) {
11839            initializeRelatedContentPagination();
11840        }
11841        updateItemSize();
11842    }
11843
11844    init();
11845});
11846shcDOMContentLoaded(function() {
11847    if($('#quizcontainer').length) {
11848        var quiz = new SHC.ui.Quiz('#quizcontainer');
11849    }
11850});
11851shcDOMContentLoaded(function() {
11852    if($(".primary-care-tool").length) {
11853        var primaryCareTool = new SHC.ui.primaryCareTool(".primary-care-tool");
11854    }
11855});
11856shcDOMContentLoaded(function() {
11857    if($('.practice-locations-list').length) {
11858        $.each($('.practice-locations-list'), function() {
11859            var hubPath = $(this).attr('hubPath');
11860            if(hubPath) {
11861                var practiceLocationsList;
11862                var splitSlashArray = hubPath.split('/');
11863                var l2Name = splitSlashArray[splitSlashArray.length - 1];
11864                practiceLocationsList = new SHC.ui.Map(function() {
11865                    practiceLocationsList.doLocationListRequest(l2Name);
11866                });
11867            }
11868        });
11869    }
11870});
11871/**
11872 * Created by mlivingston on 8/24/17.
11873 */
11874jQuery(function() {
11875    var url = window.location.href;
11876    var queryParam = window.location.search.split("?")[1];
11877    var cookieWebPage = url.split('/')[url.split('/').length -1].split('?')[0].split('.')[0];
11878    var cookieName = cookieWebPage + "phonenumbercookie";
11879    if (queryParam) {
11880        if (queryParam.indexOf("ecid=calltrack-dis-na-dpst--30s-Jun17-na") > -1) {
11881            SHC.util.setCookie(cookieName, "(650) 822-0418", 7, "/");
11882        } else if (queryParam.indexOf("ecid=calltrack-dis-pawk-dpvd--15s-Jun17-na") > -1) {
11883            SHC.util.setCookie(cookieName, "(650) 665-5082", 7, "/");
11884        } else if (queryParam.indexOf("ecid=calltrack3-dis-na-dpst--30s-Jun17-na") > -1) {
11885            SHC.util.setCookie(cookieName, "(650) 263-8474", 7, "/");
11886        } else if (queryParam.indexOf("ecid=calltrack-radio-pawk-radiad--300x250-Jun17-na") > -1) {
11887            SHC.util.setCookie(cookieName, "(650) 249-9301", 7, "/");
11888        } else if (queryParam.indexOf("&kwcid=adwords&campaignid=012345678&adgroup=01234567890&keyword=calltracking&matchtype=e&position=1t1") > -1) {
11889            SHC.util.setCookie(cookieName, "(650) 665-5862", 7, "/");
11890        } else if (queryParam.indexOf("&kwcid=adwords&campaignid=123456789&adgroup=0987654321&keyword=samplead&matchtype=e&position=1t1") > -1) {
11891            SHC.util.setCookie(cookieName, "(650) 667-8994", 7, "/");
11892        } else if (queryParam.indexOf("ecid=calltrack-olm-contra-prnt-all-fulpg-Jun17-yeung") > -1) {
11893            SHC.util.setCookie(cookieName, "(650) 433-3791", 7, "/");
11894        } else if (queryParam.indexOf("ecid=calltrack2-olm-eastbayon-prnt-all-hafpg-Jun17-chandler") > -1) {
11895            SHC.util.setCookie(cookieName, "(650) 460-3305", 7, "/");
11896        }
11897    }
11898
11899    if ($('.phone-number-from-component').length) {
11900        $.each(document.cookie.split(/; */), function() {
11901            var splitCookie = this.split('=');
11902            var cookieKey = splitCookie[0];
11903            if (cookieKey === cookieName) {
11904                var callTrackingCookie = SHC.util.getCookie(cookieKey);
11905                if (callTrackingCookie !== "") {
11906                    $('.phone-number-from-component').text(callTrackingCookie);
11907                    $('.phone-number-from-component').attr('href', "tel://" + callTrackingCookie);
11908                }
11909            }
11910        });
11911    }
11912
11913});
11914$( function() {
11915	if( window.location.href.indexOf( 'medical-conditions' ) > -1 ) {
11916		var activeContainer = $( '.mm-content-container' ),
11917			activeTitleContainer = activeContainer.find( '.mm-titles-container' ),
11918			titleContainer = activeContainer.find( '.mmtitle-container:last-child' ),
11919			activeTitle = titleContainer.find( '.section-title' );
11920
11921		activeTitle.addClass( 'active' );
11922		titleContainer.addClass( 'active' );
11923	}
11924
11925	setTimeout( function() {
11926		var editMode = $( '.editing' );
11927		if( editMode.length > 0 ) {
11928			$( '.mm-innerwrap > div' ).not( '.editing' ).addClass( 'parsys-placeholder' );
11929		}
11930	}, 1600);
11931});
11932
11933$(document).on( 'unload', function() {
11934	setTimeout( function() {
11935		var editMode = $( '.editing' );
11936		if( editMode.length > 0 ) {
11937			$( '.mm-innerwrap > div' ).not( '.editing' ).addClass( 'parsys-placeholder' );
11938		}
11939	}, 1600);
11940
11941});
11942$(document).ready(function () {
11943    setTimeout(function () {
11944        if (jQuery('#presentation-player').length > 0) {
11945            $('#presentation-player').YTPlayer({
11946                fitToBackground: false,
11947                mute: false,
11948                repeat: false,
11949                playerVars: {
11950                    autoplay: 1,
11951                    controls: 1,
11952                    modestbranding: 1,
11953                    rel: 0,
11954                    showinfo: 0
11955                }
11956            });
11957        }
11958    }, 1000);
11959});
11960$(document).ready(function () {
11961    if (jQuery('#content-player').length > 0) {
11962        $('#content-player').YTPlayer({
11963            fitToBackground: false,
11964            mute: false,
11965            repeat: false,
11966            playerVars: {
11967                autoplay: 1,
11968                controls: 1,
11969                modestbranding: 1,
11970                rel: 0,
11971                showinfo: 0
11972            }
11973        });
11974    }
11975});
11976shcDOMContentLoaded(function(){
11977    //show insurance link if NOT coming from cisco or intel shca page
11978    var queryString = window.location.href.split('?fromMicro=')[1];
11979    if (!queryString || (queryString.indexOf("cisco") === -1 && queryString.indexOf("intel") === -1)) {
11980        $('a.doctor-profile-insurance-link').removeClass('hidden');
11981    }
11982
11983    //remove doctor make an appointment modal insurance link if on cisco or intel
11984    var path = window.location.pathname;
11985    $(window).on('doctorMakeApptModalLoaded', function() {
11986        if (path.indexOf('cisco') === -1 && path.indexOf('connectedcareca') === -1) {
11987            $('#modal-container .clinic-link.clinic-insurance').removeClass('hidden');
11988        }
11989    });
11990});
11991shcDOMContentLoaded(function(){
11992    if(jQuery('.doctor-profile') && jQuery('.doctor-profile').length > 0) {
11993        var modal = new SHC.ui.PhyscianProfile("#read-more");   
11994        var imageErrorHandler = function(e) {
11995            $(this).attr("src", "/etc/clientlibs/shc/main/img/shc-logo-profiledeck.jpg");
11996        };
11997        var img = $("#profilePhoto");
11998        img.on("error", imageErrorHandler);
11999        img.attr("src", img.attr("src"));
12000        jQuery("#modal").addClass("doc-modal");
12001        new SHC.ui.Modal('.tooltip');
12002    }
12003});
12004
12005
12006shcDOMContentLoaded(function () {
12007  var physicianProfileContainer = $('.physician-profile-container');
12008  var bioFulltext = '';
12009  var bioFullHtml = '';
12010  if (physicianProfileContainer.length) {
12011    //fill stars based on rating
12012    var fillStars = function () {
12013      var innerStars = $('.inner-stars');
12014      $.each(innerStars, function (i, innerStar) {
12015        if (innerStar) {
12016          var rating = innerStar.dataset.avgRating;
12017          var filledStars = innerStar.querySelector('.filled-stars');
12018          var emptyStars = innerStar.querySelector('.empty-stars');
12019
12020          if (filledStars && emptyStars) {
12021            if (rating >= 0 && rating <= 5) {
12022              filledStars.style.width =
12023                (rating / 5) * emptyStars.offsetWidth + 'px';
12024            } else {
12025              innerStar.remove();
12026            }
12027          }
12028        }
12029      });
12030    };
12031
12032    var setUpViewAllBio = function () {
12033      var bioText = $('.bio-txt'),
12034        viewMoreLink = $('.view-more-link');
12035      if (bioText.length) {
12036        bioFulltext = bioText.text();
12037        bioFullHtml = bioText.get(0).innerHTML;
12038        setBioChar();
12039
12040        viewMoreLink.on('click', function () {
12041          if (bioText.text() !== bioFulltext) {
12042            bioText.html(bioFullHtml);
12043            viewMoreLink.addClass('open');
12044          }
12045        });
12046        viewMoreLink.on('keydown', function () {
12047            if (event.key === 'Enter') {
12048                $(this).click();
12049            }
12050        });
12051      }
12052    };
12053
12054    //truncates bio text height at 3 lines and adds ellipsis
12055    var setBioChar = function () {
12056      var bioText = $('.bio-txt'),
12057        width = bioText.width(),
12058        viewMoreLink = $('.view-more-link');
12059
12060      var wordWidth = width >= 660 ? 7.25 : 6.6;
12061      var char = (width / wordWidth) * 3;
12062
12063      if (bioFulltext.length > char) {
12064        var bioTextShort = SHC.util.ellipsis(bioFulltext, char);
12065        bioText.text(bioTextShort);
12066        viewMoreLink.removeClass('open');
12067      } else {
12068        viewMoreLink.addClass('open');
12069      }
12070    };
12071
12072    var viewMoreReviews = function () {
12073      var viewMoreReviewsLink = $('.view-more-reviews');
12074      var overflow = $('.reviews-list-overflow');
12075
12076      viewMoreReviewsLink.on('click', function (event) {
12077        event.preventDefault();
12078        if (overflow.hasClass('open')) {
12079          overflow.removeClass('open');
12080          viewMoreReviewsLink.html('View More Patient Reviews');
12081        } else {
12082          overflow.addClass('open');
12083          viewMoreReviewsLink.html('View Fewer Patient Reviews');
12084        }
12085      });
12086    };
12087
12088
12089var updateFeedbackTracking = function () {
12090  $(document).on('click', '.review-summary-feedback .thumb-btn', function () {
12091    const $btn = $(this);
12092    const $container = $btn.closest('.feedback-actions');
12093    const isAlreadySelected = $btn.hasClass('selected');
12094    const feedbackType = $btn.data('feedback');
12095
12096    if (!feedbackType) {
12097      console.warn('Feedback type missing');
12098      return;
12099    }
12100
12101    let physicianId = $('.physician-profile-title[itemprop="name"]').text().trim();
12102
12103    let state;
12104
12105    if (isAlreadySelected) {
12106      $btn.removeClass('selected').addClass('unselected');
12107      state = 'unselected';
12108    } else {
12109      $container.find('.thumb-btn').removeClass('selected');
12110      $btn.removeClass('unselected').addClass('selected');
12111      state = 'selected';
12112    }
12113
12114    if (window.adobeDataLayer && window.stanford && stanford.analytics) {
12115      stanford.analytics.send(
12116        stanford.analytics.createComponentClickButton(
12117          feedbackType,
12118          "feedback",
12119          "ai patient review summary",
12120          null,
12121          physicianId,
12122          state
12123        )
12124      );
12125    }
12126  });
12127};
12128
12129    var registerEvents = function () {
12130      // referring physicians dropdown
12131      $('.referring-physicians .referring-dropdown').on(
12132        'click',
12133        function (event) {
12134          var referringPhysicianDropdown = $(
12135            '.referring-dropdown .dropdown-menu'
12136          );
12137          if (referringPhysicianDropdown.hasClass('open')) {
12138            closeDropdown(referringPhysicianDropdown);
12139          } else {
12140            referringPhysicianDropdown.slideDown(300, function () {
12141              referringPhysicianDropdown.addClass('open');
12142            });
12143          }
12144        }
12145      );
12146      $('a.anchor-link').on('click', function (event) {
12147        event.preventDefault();
12148        var targetElement = $(event.target);
12149        if (targetElement.hasClass('dropdown-item')) {
12150          var dropDownMenu = targetElement.closest('.dropdown-menu');
12151          closeDropdown(dropDownMenu);
12152        }
12153      });
12154
12155    var toggleRatingInfoTooltip = function(tooltip) {
12156        if(tooltip.css('display') == 'none') {
12157            tooltip.css('display', 'block');
12158            var thisTooltipId = tooltip.attr('id');
12159            //hide other tooltips
12160            $('.physician-ratings.accordion-content.open .stars-container .ratings-container .ratings-modal')
12161                .each(function(i, ele){
12162                    if (ele.id != thisTooltipId) {
12163                        $(ele).css('display','none');
12164                    }
12165                });
12166        } else {
12167            tooltip.css('display', 'none');
12168        }
12169    };
12170    //handle rating question mark icon click
12171    $('.ratings-container > .ratings-info').on('focus focusout mouseenter mouseleave', function (event) {
12172            let tooltip = $(this).parent().find('.ratings-modal');
12173            toggleRatingInfoTooltip(tooltip);
12174    });
12175      //handle ratings accordion
12176      $('.category-label').on('click', function (event) {
12177        event.preventDefault();
12178        var target = event.target;
12179        var accordion = $(target).hasClass('accordion')
12180          ? target
12181          : event.target.querySelector('.accordion');
12182        var physicianRatings = $('.physician-ratings');
12183        if ($(accordion).hasClass('open')) {
12184          physicianRatings.slideUp(300, function () {
12185            $(accordion).removeClass('open');
12186            physicianRatings.removeClass('open');
12187            physicianRatings.parent().find('#ratings-accordion').attr('aria-expanded','false');
12188          });
12189        } else {
12190          physicianRatings.slideDown(300, function () {
12191            fillStars();
12192            $(accordion).addClass('open');
12193            physicianRatings.addClass('open');
12194            physicianRatings.parent().find('#ratings-accordion').attr('aria-expanded','true');
12195          });
12196        }
12197      });
12198
12199      // close dropdown when clicked outside
12200      $(document).on('click', function (event) {
12201        var targetElement = $(event.target);
12202        if (!targetElement.closest('.referring-physicians').length) {
12203          var referringPhysicianDropdown = $(
12204            '.referring-dropdown .dropdown-menu'
12205          );
12206          closeDropdown(referringPhysicianDropdown);
12207        }
12208      });
12209
12210      $('.category-label').on('keydown', function (event) {
12211          if (event.key === 'Enter') {
12212              $(this).click();
12213          }
12214      });
12215      //handle navigation clicks
12216      $('.navigation-section a').on('click', function (event) {
12217        event.preventDefault();
12218        var navigateToSectionId = $(event.target).attr('href');
12219        var firstAccordion = $(navigateToSectionId)
12220          .find('.headline .accordion')
12221          .first();
12222        if (firstAccordion.length && !firstAccordion.hasClass('open')) {
12223          toggleAccordion(firstAccordion);
12224        }
12225      });
12226
12227      //handle view more/all links
12228      $('.accordion-content .view-all-link a').on('click', function (event) {
12229            event.preventDefault();
12230
12231            var targetElement = $(event.target);
12232
12233            //var category = targetElement.parent().parent().find('.headline').text().trim();
12234            var hiddenSection = targetElement
12235              .closest('.list-wrapper')
12236              .find('.hidden-items');
12237            if (hiddenSection.is(':visible')) {
12238              hiddenSection.slideUp(1000, function () {
12239                targetElement.html(targetElement.html().replace('Fewer', 'More'));
12240              });
12241            } else {
12242              hiddenSection.slideDown(1000, function () {
12243                targetElement.html(targetElement.html().replace('More', 'Fewer'));
12244
12245              });
12246            }
12247      });
12248      //handle headline accordion
12249      $('.headline').on('click', function (event) {
12250        event.preventDefault();
12251        var target = event.target;
12252        if (!$(target).hasClass('accordion')) {
12253          target = $(target).hasClass('subtitle')
12254            ? $(target).next()
12255            : target.querySelector('.accordion');
12256        }
12257        toggleAccordion($(target));
12258      });
12259      $('.headline').on('keydown', function (event) {
12260        if (event.key === 'Enter') {
12261            $(this).click();
12262        }
12263      });
12264      //clinical trials tab toggle
12265      $('.clinical-trials-tab-nav a').on('click', function (event) {
12266        event.preventDefault();
12267        var targetLink = $(event.target);
12268        if (targetLink.hasClass('active')) {
12269          return;
12270        }
12271        if (targetLink.hasClass('open-trials')) {
12272          $('.tab-content .open-trials').show();
12273          $('.clinical-trials-tab-nav a.open-trials').removeAttr('tabindex');
12274          $('.clinical-trials-tab-nav a.open-trials').attr('aria-selected','true');
12275          $('.tab-content .closed-trials').hide();
12276          $('.clinical-trials-tab-nav a').toggleClass('active');
12277          $('.clinical-trials-tab-nav a.closed-trials').attr('aria-selected','false');
12278          $('.clinical-trials-tab-nav a.closed-trials').attr('tabindex','-1');
12279        } else if (targetLink.hasClass('closed-trials')) {
12280          $('.tab-content .open-trials').hide();
12281          $('.clinical-trials-tab-nav a.closed-trials').removeAttr('tabindex');
12282          $('.clinical-trials-tab-nav a.closed-trials').attr('aria-selected','true');
12283          $('.tab-content .closed-trials').show();
12284          $('.clinical-trials-tab-nav a').toggleClass('active');
12285          $('.clinical-trials-tab-nav a.open-trials').attr('aria-selected','false');
12286          $('.clinical-trials-tab-nav a.open-trials').attr('tabindex','-1');
12287        }
12288      });
12289      $('.clinical-trials-tab-nav a').on('keydown', function (event) {
12290
12291      var targetLink = $(event.target);
12292        switch(event.key) {
12293            case 'Enter': $(this).click(); break;
12294            case ' ': $(this).click(); break;
12295            case 'ArrowLeft':
12296                if (targetLink.hasClass('open-trials')) {
12297                     $('.clinical-trials-tab-nav a.closed-trials').removeAttr('tabindex');
12298                     $('.clinical-trials-tab-nav a.closed-trials').focus();
12299                } else {
12300                    $('.clinical-trials-tab-nav a.open-trials').removeAttr('tabindex');
12301                    $('.clinical-trials-tab-nav a.open-trials').focus();
12302                }
12303                break;
12304            case 'ArrowRight':
12305                if (targetLink.hasClass('closed-trials')) {
12306                     $('.clinical-trials-tab-nav a.open-trials').removeAttr('tabindex');
12307                     $('.clinical-trials-tab-nav a.open-trials').focus();
12308                } else {
12309                    $('.clinical-trials-tab-nav a.closed-trials').removeAttr('tabindex');
12310                    $('.clinical-trials-tab-nav a.closed-trials').focus();
12311                }
12312                break;
12313            case 'Home': $('.clinical-trials-tab-nav a.open-trials').removeAttr('tabindex'); $('.clinical-trials-tab-nav a.open-trials').focus(); break;
12314            case 'End':  $('.clinical-trials-tab-nav a.closed-trials').removeAttr('tabindex'); $('.clinical-trials-tab-nav a.closed-trials').focus(); break;
12315            default: break;
12316        }
12317      });
12318    };
12319    var closeDropdown = function (dropDownMenu) {
12320      dropDownMenu.slideUp(300, function () {
12321        dropDownMenu.removeClass('open');
12322      });
12323    };
12324    var toggleAccordion = function (targetElement) {
12325      var isOpen = targetElement.hasClass('open');
12326      var isPracticeLocation = targetElement.closest(
12327        '.practice-locations'
12328      ).length;
12329      // only open one section at a time (except for items within practice locations
12330      if (!isOpen) {
12331        var currentlyOpen = targetElement
12332          .closest('section')
12333          .find('.accordion-content.open');
12334        if (currentlyOpen.length && !isPracticeLocation) {
12335          currentlyOpen.slideUp(300, function () {
12336            currentlyOpen.removeClass('open');
12337
12338            var openAccordionHeader = targetElement
12339              .closest('section')
12340              .find('.headline .accordion.open');
12341
12342            openAccordionHeader.removeClass('open');
12343
12344            openAccordionHeader.parent().parent().attr('aria-expanded','false');
12345          });
12346        }
12347        var nextToOpen = targetElement
12348          .closest('.summary-section')
12349          .find('.accordion-content');
12350        nextToOpen.slideDown(300, function () {
12351          nextToOpen.addClass('open');
12352          targetElement.addClass('open');
12353          nextToOpen.parent().find('.headline').attr('aria-expanded','true');
12354        });
12355      } else {
12356        var nextToClose = targetElement
12357          .closest('.summary-section')
12358          .find('.accordion-content');
12359        nextToClose.slideUp(300, function () {
12360          nextToClose.removeClass('open');
12361          targetElement.removeClass('open');
12362          nextToClose.parent().find('.headline').attr('aria-expanded','false');
12363        });
12364      }
12365    };
12366    // add extra top offset to sections with anchor links when emergency banner exists on top
12367    var adjustTopOffsetForAnchorLinks = function () {
12368      var hasEmergencyBanner = $('#new-emergency-alert').length;
12369      var offsetHeight = document.querySelector('.masthead-affixed').offsetHeight;
12370      if (hasEmergencyBanner) {
12371        $('.doctor-profile__body-section .section').addClass('extra-offset');
12372        offsetHeight += document.querySelector('#new-emergency-alert').offsetHeight;
12373      }
12374
12375      var hashLocation = document.getElementById(window.location.hash.substring(1));
12376      if (hashLocation) {
12377        hashLocation.style.scrollMarginTop = offsetHeight + 'px';
12378      }
12379    };
12380
12381    var setUpAPPTooltip = function () {
12382      if ($('.app-tooltip').length) {
12383        new SHC.ui.Modal('.app-tooltip');
12384        $('.app-tooltip').click(function () {
12385          $('#modal').addClass('app-tooltip-modal');
12386        });
12387        $('#modal .close-modal').click(function () {
12388          $('#modal').removeClass('app-tooltip-modal');
12389        });
12390      }
12391    };
12392
12393    var handleAnchorInUrl = function () {
12394      var locationSections = document.querySelectorAll('.location.summary-section');
12395      if (locationSections.length > 0) {
12396        var hashLocation = document.getElementById(window.location.hash.substring(1));
12397        if (hashLocation) {
12398          hashLocation.querySelector('.headline').click();
12399        } else {
12400          locationSections[0].querySelector('.headline').click();
12401        }
12402      }
12403    }
12404
12405    fillStars();
12406    setUpViewAllBio();
12407    registerEvents();
12408    viewMoreReviews();
12409    updateFeedbackTracking();
12410    $(window).resize(function () {
12411      fillStars();
12412      setBioChar();
12413    });
12414    adjustTopOffsetForAnchorLinks();
12415    setUpAPPTooltip();
12416    handleAnchorInUrl();
12417  }
12418});
12419
12420shcDOMContentLoaded(function () {
12421  if (
12422    jQuery('#download-print-modal') &&
12423    jQuery('#download-print-modal').length > 0
12424  ) {
12425    //add a css class to parent modal element for new look for the download and print modals
12426    //TODO: will need to refactor this if business wants to update all modals to have the new look and feel
12427    $('.print-icon').click(updateModal);
12428    var updateModal = function () {
12429      $('#modal').addClass('download-print-modal');
12430    };
12431    //back to default state when the modal is closed
12432    $('#modal .close-modal').click(function () {
12433      $('#modal').removeClass('download-print-modal');
12434    });
12435
12436    var printClicked = false;
12437    var vc_only_flag = $('.vc-only-flag').data('vc-only');
12438    var isValleyCareOnly = vc_only_flag === 'true' || vc_only_flag === true;
12439
12440    var showPrintDownloadIcons = function () {
12441      if (!isValleyCareOnly) {
12442        $('#download-print-modal .open-modal').removeClass('hidden');
12443      }
12444    };
12445    var cleanPrintDownloadModalLinks = function () {
12446      var printModalUrl = window.location.pathname;
12447      if (!printModalUrl.includes('downloadprintmodal')) {
12448        printModalUrl = printModalUrl.replace(
12449          '.html',
12450          '.downloadprintmodal.print.html'
12451        );
12452      }
12453      $('#download-print-modal .print-icon').attr('href', printModalUrl);
12454    };
12455
12456    //handle download/print click
12457    var handlePrintDownload = function () {
12458      function printFrameContent(frameId) {
12459        window.frames[frameId].focus();
12460        window.frames[frameId].print();
12461        // reset flag
12462        printClicked = false;
12463      }
12464
12465      var handlePdfPrint = function (printFrameID, htmlUrl) {
12466        var pdfIframe = '';
12467        var style = 'border:none; margin:0; padding:0; height: 0; width: 0;';
12468        if (SHC.util.isIE()) {
12469          pdfIframe =
12470            '<object data="' +
12471            htmlUrl +
12472            '" name="' +
12473            printFrameID +
12474            '" id="' +
12475            printFrameID +
12476            '" style="' +
12477            style +
12478            '" type="text/html">';
12479        } else {
12480          pdfIframe =
12481            '<iframe src="' +
12482            htmlUrl +
12483            '" name="' +
12484            printFrameID +
12485            '" id="' +
12486            printFrameID +
12487            '" style="' +
12488            style +
12489            '"></iframe>';
12490        }
12491        $(document.body).append(pdfIframe);
12492        setTimeout(function () {
12493          printFrameContent(printFrameID);
12494        }, 500);
12495      };
12496
12497      $('.profile-content .download-print-btn.print').on(
12498        'click',
12499        function (event) {
12500          event.preventDefault();
12501          // prevent multiple clicks on print button
12502          if (!printClicked) {
12503            printClicked = true;
12504            // will be used for getting correct pdf url
12505            var summaryOrFull = $(event.target)
12506              .closest('.profile-content')
12507              .hasClass('summary')
12508              ? 'summary'
12509              : 'full';
12510            var printFrameID = 'print_frame_' + summaryOrFull;
12511            var printFrame = document.getElementById(printFrameID);
12512            var htmlUrl = document.location.pathname.replace(
12513              'html',
12514              summaryOrFull + '.html'
12515            );
12516            if (printFrame) {
12517              printFrameContent(printFrameID);
12518            } else {
12519              handlePdfPrint(printFrameID, htmlUrl);
12520            }
12521          }
12522        }
12523      );
12524    };
12525
12526    showPrintDownloadIcons();
12527    cleanPrintDownloadModalLinks();
12528
12529    var observer = new MutationObserver(handlePrintDownload);
12530    // configuration of the observer:
12531    var config = {
12532      attributes: true,
12533      childList: true,
12534      characterData: true,
12535      subtree: true,
12536    };
12537    var modalContent = document.getElementById('modal-content');
12538    observer.observe(modalContent, config);
12539  }
12540});
12541
12542if (document.querySelectorAll('.physician-profile-container .bio-sidebar-wrapper a.open-modal')) {
12543  var initializeProfileAppointmentClickEvents = function() {
12544    const apptButtonsList = document.querySelectorAll('.physician-profile-container a.open-modal');
12545    if (apptButtonsList.length > 0) {
12546      let nameNode = ".bio-sidebar-wrapper .physician-profile-title";
12547      let providerName = document.querySelector(nameNode).innerText;
12548
12549      apptButtonsList.forEach(
12550        function(apptButtonItem) {
12551          if (apptButtonItem) {
12552            let modalType = apptButtonItem.getAttribute('data-modalcontainer');
12553            if (modalType == '.make-an-appt') {
12554              let btnText = apptButtonItem.text;
12555              apptButtonItem.addEventListener("click", function() {
12556                stanford.analytics.send(stanford.analytics.createComponentClickDirectory(btnText, providerName, "button", "Make An Appointment"));
12557              });
12558            }
12559          }
12560        }
12561      )
12562    }
12563  };
12564  window.addEventListener('load', initializeProfileAppointmentClickEvents);
12565}
12566shcDOMContentLoaded(function () {
12567    if($('.location-page-component').length) {
12568        var locationPage = new SHC.ui.LocationPage();
12569    }
12570
12571    if($('.location-inline-map').length) {
12572        var mapMarker = {
12573            "latitude":  $('#clinicLatitude').text(),
12574            "longitude": $('#clinicLongitude').text()
12575        };
12576        var map = new SHC.ui.Map(mapMarker);
12577    }
12578});
12579shcDOMContentLoaded(function() {
12580    if ($("div.hide-overview").length) {
12581        $("#tab-nav div.panel:first-child").css("display","none");
12582        $("#mobile-tabs div.panel:first-child").css("display","none");
12583    }
12584});
12585
12586// SHC.ui.Hub.Detail
12587//
12588// Flushes top of left column with contacts box on
12589// Life Flight page
12590// -------------------------
12591// [email protected]
12592
12593+function(SHC, $) {
12594    "use strict";
12595
12596    $(function() {
12597        if(document.URL.indexOf('lifeflight.html') !== -1) {
12598            $('.parsysleft h2').first().addClass('lifeflight-section-header');
12599        }
12600    });
12601
12602}(SHC, jQuery);
12603shcDOMContentLoaded(function() {
12604    if (jQuery(".event-event-detail-page").length) {
12605        var Detail = new SHC.ui.Event.Detail(".event-event-detail-page");
12606    }
12607
12608    if($('.mapmodalcontent .map-target').length) {
12609        var officeMarkerPath = $('.mapmodalcontent .map-target').attr('officeMarkerPath');
12610        jQuery('.mapmodalcontent .map-target').load(officeMarkerPath + '.html #map-container', function() {
12611            console.debug("mmc selector");
12612            var locationPage = new SHC.ui.LocationPage();
12613        });
12614    }
12615});
12616 $(function(){
12617    if($('.location-page.campaign-multi-clinic-map').length) {
12618        var map;
12619        var slingResourcePath = $('.location-page.campaign-multi-clinic-map').attr('requestPath');
12620        var splitSlashArray = slingResourcePath.split('/');
12621        var campaignName = splitSlashArray[splitSlashArray.length - 2];
12622        map = new SHC.ui.Map(function() {
12623            map.doCampaignRequest(campaignName);
12624        });
12625    }
12626});
12627
12628shcDOMContentLoaded(function() {
12629	const queryString = window.location.search;
12630	const urlParams = new URLSearchParams(queryString);
12631	const cid = urlParams.get("cid");
12632	if (cid != null && cid != undefined) {
12633    	sessionStorage.setItem("cid", cid);
12634	}
12635	console.log("cid :" + sessionStorage.getItem("cid"));
12636});
12637
12638function initializeMakeAppointmentClickEvents() {
12639    const makeAppointmentModalTileLinks = document.querySelectorAll('.clinic-l2-page .tile-board .tile-box-overlay [data-modalcontainer=".make-an-appt"]');
12640
12641    function initializeLink(appLink, primary) {
12642        if (appLink) {
12643            const btnText = appLink.innerText;
12644            appLink.addEventListener("click", function () {
12645                stanford.analytics.send(stanford.analytics.createComponentClickButton(btnText, primary, 'Make An Appointment'));
12646            });
12647        }
12648    }
12649
12650    if (makeAppointmentModalTileLinks) {
12651        makeAppointmentModalTileLinks.forEach(
12652            function (appTileLink) {
12653                initializeLink(appTileLink, 'tile');
12654            }
12655        );
12656    }
12657}
12658
12659window.addEventListener('load', initializeMakeAppointmentClickEvents);
12660shcDOMContentLoaded(function() {
12661    if ($('meta[name=404]').length) {
12662        if (typeof webData === 'object') {
12663            webData.page404 = "error";
12664        }
12665    }
12666});
12667shcDOMContentLoaded(function() {
12668    if (jQuery(".reveal-box-expert").length) {
12669        var revealBoxesExpert = new SHC.ui.RevealBoxExpert(".reveal-box-expert");
12670        var hashOpen = function () {
12671            var hash = location.hash.replace('#', '');
12672            if (hash && hash.indexOf('&') === -1 && hash.indexOf('=') === -1 ) {
12673                var anchoredBox = $('.reveal-box-expert[name*=' + hash + ']');
12674                if (anchoredBox && anchoredBox.length === 1) {
12675                    // This will be subtracted to the scroll distance in main.js.
12676                    // It only gets set when the hash is the reveal-expert component
12677                    SHC.ui.RevealBoxExpert.hashScroll = 25;
12678                    anchoredBox.addClass('box-active');
12679                    anchoredBox.find(".reveal-arrow-expert").addClass("active");
12680                    anchoredBox.find(".reveal-content-expert").show();
12681                }
12682            }
12683        }
12684        jQuery(window).on('hashchange', hashOpen);
12685        jQuery(window).on('debouncedresize', hashOpen);
12686        jQuery(window).on('anchorclick', hashOpen);
12687    }
12688});
12689shcDOMContentLoaded(function() {
12690    $('.media-resources').each(function(){
12691        var media = new SHC.ui.MediaResources($(this));
12692    });
12693});
12694
12695(function ($, $document) {
12696    "use strict";
12697
12698    $document.on("dialog-ready", function() {
12699        $(".shc-media-contacts-dialog-field").siblings("label.coral-Form-fieldlabel").addClass("shc-media-contacts-dialog-label");
12700    });
12701})($, $(document));
12702shcDOMContentLoaded(function() {
12703    $('.links-bar .carat').click(function(e) {
12704        $(this).closest('.links-bar-root').toggleClass('open', 500);
12705        $(this).closest('.links-bar').find('.carat').toggleClass('show').toggleClass('hide');
12706    });
12707
12708    var linksBarRoot = $('.links-bar-root');
12709    if(linksBarRoot.length) {
12710        var affixLinksBar = function () {
12711            if (linksBarRoot.hasClass('open')) {
12712                linksBarRoot.removeClass('open', 500).promise().done(function() {
12713                    $('.links-bar').find('.carat').toggleClass('show').toggleClass('hide');
12714                });
12715            }
12716
12717            var scrollTop = $(this).scrollTop();
12718            var mastHeadHeight = 65;
12719            if (SHC.ui.screenMode === 'small') {
12720                mastHeadHeight = 0;
12721            }
12722            var topOffset =  $('.links_bar').offset().top;
12723            if ( (topOffset - mastHeadHeight) <= scrollTop ) {
12724                linksBarRoot.addClass('affixed');
12725                linksBarRoot.css('top', mastHeadHeight);
12726            } else {
12727                linksBarRoot.removeClass('affixed');
12728                linksBarRoot.css('top', '');
12729            }
12730        }
12731
12732        $(window).on('scroll', affixLinksBar);
12733        $(window).on('resize', function() {
12734            SHC.ui.detectScreenMode();
12735            affixLinksBar();
12736        });
12737
12738        //init links bar position
12739        affixLinksBar();
12740    }
12741});
12742
12743function initializeLinkClickEvents() {
12744    const makeAppointmentButtonsList = document.querySelectorAll('.link-container a.make-appointment-button');
12745    const linkModalButtonsList = document.querySelectorAll('.link-container a.btn[data-modalcontainer]');
12746    const mapModalButtonLinks = document.querySelectorAll('#cta-map-modal');
12747    const externalLinks = document.querySelectorAll('.link-container [data-modalcontainer="external-link"]');
12748
12749    if (makeAppointmentButtonsList) {
12750        makeAppointmentButtonsList.forEach(
12751            function (makeAppointmentButtonItem) {
12752                if (makeAppointmentButtonItem) {
12753                    let providerName = null;
12754                    let searchTitle = document.querySelector('#marquee-cp16>#shc-search-title');
12755                    if (searchTitle) {
12756                        providerName = searchTitle.innerHTML.trim();
12757                    }
12758                    let btnText = makeAppointmentButtonItem.text !== "" ? makeAppointmentButtonItem.text.trim() : "Make An Appointment";
12759                    makeAppointmentButtonItem.addEventListener("click", function () {
12760                        stanford.analytics.send(stanford.analytics.createComponentClickButton(btnText, "button", "Make An Appointment",null,providerName));
12761                    });
12762                }
12763            }
12764        )
12765    }
12766
12767    if (linkModalButtonsList) {
12768        linkModalButtonsList.forEach((modalButton) => {
12769                if (modalButton.getAttribute('data-modalcontainer') != '.make-an-appt') {
12770                    const btnText = modalButton.innerText;
12771                    modalButton.addEventListener("click", function () {
12772                        stanford.analytics.send(stanford.analytics.createComponentClickButton(btnText, "button", ''));
12773                    });
12774                }
12775            }
12776        );
12777    }
12778
12779    if (mapModalButtonLinks) {
12780        mapModalButtonLinks.forEach((mapLink) => {
12781                const btnText = mapLink.innerText;
12782                mapLink.addEventListener("click", function () {
12783                    stanford.analytics.send(stanford.analytics.createComponentClickButton(btnText, "button", ''));
12784                });
12785            }
12786        );
12787    }
12788
12789    if (externalLinks) {
12790        externalLinks.forEach((externalLink) => {
12791                const text = externalLink.innerText;
12792                externalLink.addEventListener("click", function () {
12793                    stanford.analytics.send(stanford.analytics.createComponentClickButton(text, "text", ''));
12794                });
12795            }
12796        );
12797    }
12798}
12799
12800window.addEventListener('load', initializeLinkClickEvents);
12801function loadLargeImageGallery() {
12802  if ($('.image-gallery-root').length) {
12803    //adjust background image size based on component size
12804    $('.gallery-items .gallery-item').each(function() {
12805      var $this = $(this);
12806
12807      var divHeight = $this.height(),
12808        divWidth = $this.width(),
12809        imgHeight = $this.data('image-height'),
12810        imgWidth = $this.data('image-width');
12811      if (
12812        imgHeight > 0 &&
12813        imgWidth > 0 &&
12814        divHeight > imgHeight &&
12815        divWidth > imgWidth
12816      ) {
12817        $this.addClass('smaller-image');
12818      }
12819    });
12820    //un-hide gallery images
12821    $('.gallery-items .gallery-item').removeClass('hide-on-load');
12822    $('.gallery-items .gallery-item-caption').removeClass('hide-on-load');
12823
12824    // convert to slick slider
12825    $('.gallery-items').slick({
12826      dots: false,
12827      infinite: true,
12828      speed: 300,
12829      slidesToShow: 1,
12830      slidesToScroll: 1,
12831      responsive: [
12832        {
12833          breakpoint: 768,
12834          settings: {
12835            dots: true
12836          }
12837        }
12838      ]
12839    });
12840
12841    //hook custom next/previous buttons to slick next/previous buttons.
12842    $('.custom-slick-next').click(function() {
12843      $(this)
12844        .closest('.image-gallery-wrapper')
12845        .find('.slick-next')
12846        .trigger('click');
12847    });
12848    $('.custom-slick-prev').click(function() {
12849      $(this)
12850        .closest('.image-gallery-wrapper')
12851        .find('.slick-prev')
12852        .trigger('click');
12853    });
12854  }
12855};
12856
12857shcDOMContentLoaded(function () {
12858  loadLargeImageGallery();
12859
12860  // Highlight Reel js
12861  if ($('.hl-root').length) {
12862    $('.hl-root').each(function () {
12863      var slickCarousel = $(this).find('.hl-carousel');
12864      slickCarousel.slick({
12865        slidesToShow: 3,
12866        slidesToScroll: 3,
12867        infinite: false,
12868        draggable: false,
12869        arrows: false,
12870        responsive: [
12871          {
12872            breakpoint: 768,
12873            settings: {
12874              vertical: true,
12875              verticalSwiping: true
12876            }
12877          }
12878        ]
12879      });
12880
12881      var prevArrow = $(this).find('.hl-arrow-prev');
12882      var nextArrow = $(this).find('.hl-arrow-next');
12883      slickCarousel.on('beforeChange', function(event, slick, currentSlide, nextSlide) {
12884        if (nextSlide === 0) {
12885          prevArrow.addClass('hl-hidden');
12886        } else {
12887          prevArrow.removeClass('hl-hidden');
12888        }
12889
12890        if (nextSlide >= slick.slideCount - 3) {
12891          nextArrow.addClass('hl-hidden');
12892        } else {
12893          nextArrow.removeClass('hl-hidden');
12894        }
12895      });
12896
12897      if (!nextArrow.hasClass('hl-hidden')) {
12898        prevArrow.on('click', function() {
12899          slickCarousel.slick('slickPrev');
12900        });
12901
12902        nextArrow.on('click', function() {
12903          slickCarousel.slick('slickNext');
12904        });
12905      }
12906    });
vendor: 8,143 bytes, lines 12907-12911
12907    new SHC.ui.Modal('.hl-article-text.hl-modal');
12908  }
12909});
12910
12911!function(i){"use strict";"function"==typeof define&&define.amd?define(["jquery"],i):"undefined"!=typeof exports?module.exports=i(require("jquery")):i(jQuery)}(function(i){"use strict";var e=window.Slick||{};(e=function(){var e=0;return function(t,o){var s,n=this;n.defaults={accessibility:!0,adaptiveHeight:!1,appendArrows:i(t),appendDots:i(t),arrows:!0,asNavFor:null,prevArrow:'<button class="slick-prev" aria-label="Previous" type="button">Previous</button>',nextArrow:'<button class="slick-next" aria-label="Next" type="button">Next</button>',autoplay:!1,autoplaySpeed:3e3,centerMode:!1,centerPadding:"50px",cssEase:"ease",customPaging:function(e,t){return i('<button type="button" />').text(t+1)},dots:!1,dotsClass:"slick-dots",draggable:!0,easing:"linear",edgeFriction:.35,fade:!1,focusOnSelect:!1,focusOnChange:!1,infinite:!0,initialSlide:0,lazyLoad:"ondemand",mobileFirst:!1,pauseOnHover:!0,pauseOnFocus:!0,pauseOnDotsHover:!1,respondTo:"window",responsive:null,rows:1,rtl:!1,slide:"",slidesPerRow:1,slidesToShow:1,slidesToScroll:1,speed:500,swipe:!0,swipeToSlide:!1,touchMove:!0,touchThreshold:5,useCSS:!0,useTransform:!0,variableWidth:!1,vertical:!1,verticalSwiping:!1,waitForAnimate:!0,zIndex:1e3},n.initials={animating:!1,dragging:!1,autoPlayTimer:null,currentDirection:0,currentLeft:null,currentSlide:0,direction:1,$dots:null,listWidth:null,listHeight:null,loadIndex:0,$nextArrow:null,$prevArrow:null,scrolling:!1,slideCount:null,slideWidth:null,$slideTrack:null,$slides:null,sliding:!1,slideOffset:0,swipeLeft:null,swiping:!1,$list:null,touchObject:{},transformsEnabled:!1,unslicked:!1},i.extend(n,n.initials),n.activeBreakpoint=null,n.animType=null,n.animProp=null,n.breakpoints=[],n.breakpointSettings=[],n.cssTransitions=!1,n.focussed=!1,n.interrupted=!1,n.hidden="hidden",n.paused=!0,n.positionProp=null,n.respondTo=null,n.rowCount=1,n.shouldClick=!0,n.$slider=i(t),n.$slidesCache=null,n.transformType=null,n.transitionType=null,n.visibilityChange="visibilitychange",n.windowWidth=0,n.windowTimer=null,s=i(t).data("slick")||{},n.options=i.extend({},n.defaults,o,s),n.currentSlide=n.options.initialSlide,n.originalSettings=n.options,void 0!==document.mozHidden?(n.hidden="mozHidden",n.visibilityChange="mozvisibilitychange"):void 0!==document.webkitHidden&&(n.hidden="webkitHidden",n.visibilityChange="webkitvisibilitychange"),n.autoPlay=i.proxy(n.autoPlay,n),n.autoPlayClear=i.proxy(n.autoPlayClear,n),n.autoPlayIterator=i.proxy(n.autoPlayIterator,n),n.changeSlide=i.proxy(n.changeSlide,n),n.clickHandler=i.proxy(n.clickHandler,n),n.selectHandler=i.proxy(n.selectHandler,n),n.setPosition=i.proxy(n.setPosition,n),n.swipeHandler=i.proxy(n.swipeHandler,n),n.dragHandler=i.proxy(n.dragHandler,n),n.keyHandler=i.proxy(n.keyHandler,n),n.instanceUid=e++,n.htmlExpr=/^(?:\s*(<[\w\W]+>)[^>]*)$/,n.registerBreakpoints(),n.init(!0)}}()).prototype.activateADA=function(){this.$slideTrack.find(".slick-active").attr({"aria-hidden":"false"}).find("a, input, button, select").attr({tabindex:"0"})},e.prototype.addSlide=e.prototype.slickAdd=function(e,t,o){var s=this;if("boolean"==typeof t)o=t,t=null;else if(t<0||t>=s.slideCount)return!1;s.unload(),"number"==typeof t?0===t&&0===s.$slides.length?i(e).appendTo(s.$slideTrack):o?i(e).insertBefore(s.$slides.eq(t)):i(e).insertAfter(s.$slides.eq(t)):!0===o?i(e).prependTo(s.$slideTrack):i(e).appendTo(s.$slideTrack),s.$slides=s.$slideTrack.children(this.options.slide),s.$slideTrack.children(this.options.slide).detach(),s.$slideTrack.append(s.$slides),s.$slides.each(function(e,t){i(t).attr("data-slick-index",e)}),s.$slidesCache=s.$slides,s.reinit()},e.prototype.animateHeight=function(){var i=this;if(1===i.options.slidesToShow&&!0===i.options.adaptiveHeight&&!1===i.options.vertical){var e=i.$slides.eq(i.currentSlide).outerHeight(!0);i.$list.animate({height:e},i.options.speed)}},e.prototype.animateSlide=function(e,t){var o={},s=this;s.animateHeight(),!0===s.options.rtl&&!1===s.options.vertical&&(e=-e),!1===s.transformsEnabled?!1===s.options.vertical?s.$slideTrack.animate({left:e},s.options.speed,s.options.easing,t):s.$slideTrack.animate({top:e},s.options.speed,s.options.easing,t):!1===s.cssTransitions?(!0===s.options.rtl&&(s.currentLeft=-s.currentLeft),i({animStart:s.currentLeft}).animate({animStart:e},{duration:s.options.speed,easing:s.options.easing,step:function(i){i=Math.ceil(i),!1===s.options.vertical?(o[s.animType]="translate("+i+"px, 0px)",s.$slideTrack.css(o)):(o[s.animType]="translate(0px,"+i+"px)",s.$slideTrack.css(o))},complete:function(){t&&t.call()}})):(s.applyTransition(),e=Math.ceil(e),!1===s.options.vertical?o[s.animType]="translate3d("+e+"px, 0px, 0px)":o[s.animType]="translate3d(0px,"+e+"px, 0px)",s.$slideTrack.css(o),t&&setTimeout(function(){s.disableTransition(),t.call()},s.options.speed))},e.prototype.getNavTarget=function(){var e=this,t=e.options.asNavFor;return t&&null!==t&&(t=i(t).not(e.$slider)),t},e.prototype.asNavFor=function(e){var t=this.getNavTarget();null!==t&&"object"==typeof t&&t.each(function(){var t=i(this).slick("getSlick");t.unslicked||t.slideHandler(e,!0)})},e.prototype.applyTransition=function(i){var e=this,t={};!1===e.options.fade?t[e.transitionType]=e.transformType+" "+e.options.speed+"ms "+e.options.cssEase:t[e.transitionType]="opacity "+e.options.speed+"ms "+e.options.cssEase,!1===e.options.fade?e.$slideTrack.css(t):e.$slides.eq(i).css(t)},e.prototype.autoPlay=function(){var i=this;i.autoPlayClear(),i.slideCount>i.options.slidesToShow&&(i.autoPlayTimer=setInterval(i.autoPlayIterator,i.options.autoplaySpeed))},e.prototype.autoPlayClear=function(){var i=this;i.autoPlayTimer&&clearInterval(i.autoPlayTimer)},e.prototype.autoPlayIterator=function(){var i=this,e=i.currentSlide+i.options.slidesToScroll;i.paused||i.interrupted||i.focussed||(!1===i.options.infinite&&(1===i.direction&&i.currentSlide+1===i.slideCount-1?i.direction=0:0===i.direction&&(e=i.currentSlide-i.options.slidesToScroll,i.currentSlide-1==0&&(i.direction=1))),i.slideHandler(e))},e.prototype.buildArrows=function(){var e=this;!0===e.options.arrows&&(e.$prevArrow=i(e.options.prevArrow).addClass("slick-arrow"),e.$nextArrow=i(e.options.nextArrow).addClass("slick-arrow"),e.slideCount>e.options.slidesToShow?(e.$prevArrow.removeClass("slick-hidden").removeAttr("aria-hidden tabindex"),e.$nextArrow.removeClass("slick-hidden").removeAttr("aria-hidden tabindex"),e.htmlExpr.test(e.options.prevArrow)&&e.$prevArrow.prependTo(e.options.appendArrows),e.htmlExpr.test(e.options.nextArrow)&&e.$nextArrow.appendTo(e.options.appendArrows),!0!==e.options.infinite&&e.$prevArrow.addClass("slick-disabled").attr("aria-disabled","true")):e.$prevArrow.add(e.$nextArrow).addClass("slick-hidden").attr({"aria-disabled":"true",tabindex:"-1"}))},e.prototype.buildDots=function(){var e,t,o=this;if(!0===o.options.dots){for(o.$slider.addClass("slick-dotted"),t=i("<ul />").addClass(o.options.dotsClass),e=0;e<=o.getDotCount();e+=1)t.append(i("<li />").append(o.options.customPaging.call(this,o,e)));o.$dots=t.appendTo(o.options.appendDots),o.$dots.find("li").first().addClass("slick-active")}},e.prototype.buildOut=function(){var e=this;e.$slides=e.$slider.children(e.options.slide+":not(.slick-cloned)").addClass("slick-slide"),e.slideCount=e.$slides.length,e.$slides.each(function(e,t){i(t).attr("data-slick-index",e).data("originalStyling",i(t).attr("style")||"")}),e.$slider.addClass("slick-slider"),e.$slideTrack=0===e.slideCount?i('<div class="slick-track"/>').appendTo(e.$slider):e.$slides.wrapAll('<div class="slick-track"/>').parent(),e.$list=e.$slideTrack.wrap('<div class="slick-list"/>').parent(),e.$slideTrack.css("opacity",0),!0!==e.options.centerMode&&!0!==e.options.swipeToSlide||(e.options.slidesToScroll=1),i("img[data-lazy]",e.$slider).not("[src]").addClass("slick-loading"),e.setupInfinite(),e.buildArrows(),e.buildDots(),e.updateDots(),e.setSlideClasses("number"==typeof e.currentSlide?e.currentSlide:0),!0===e.options.draggable&&e.$list.addClass("draggable")},e.prototype.buildRows=function(){var i,e,t,o,s,n,r,l=this;if(o=document.createDocumentFragment(),n=l.$slider.children(),l.o
vendor: 3,442 bytes, line 12911
12911ptions.rows>1){for(r=l.options.slidesPerRow*l.options.rows,s=Math.ceil(n.length/r),i=0;i<s;i++){var d=document.createElement("div");for(e=0;e<l.options.rows;e++){var a=document.createElement("div");for(t=0;t<l.options.slidesPerRow;t++){var c=i*r+(e*l.options.slidesPerRow+t);n.get(c)&&a.appendChild(n.get(c))}d.appendChild(a)}o.appendChild(d)}l.$slider.empty().append(o),l.$slider.children().children().children().css({width:100/l.options.slidesPerRow+"%",display:"inline-block"})}},e.prototype.checkResponsive=function(e,t){var o,s,n,r=this,l=!1,d=r.$slider.width(),a=window.innerWidth||i(window).width();if("window"===r.respondTo?n=a:"slider"===r.respondTo?n=d:"min"===r.respondTo&&(n=Math.min(a,d)),r.options.responsive&&r.options.responsive.length&&null!==r.options.responsive){s=null;for(o in r.breakpoints)r.breakpoints.hasOwnProperty(o)&&(!1===r.originalSettings.mobileFirst?n<r.breakpoints[o]&&(s=r.breakpoints[o]):n>r.breakpoints[o]&&(s=r.breakpoints[o]));null!==s?null!==r.activeBreakpoint?(s!==r.activeBreakpoint||t)&&(r.activeBreakpoint=s,"unslick"===r.breakpointSettings[s]?r.unslick(s):(r.options=i.extend({},r.originalSettings,r.breakpointSettings[s]),!0===e&&(r.currentSlide=r.options.initialSlide),r.refresh(e)),l=s):(r.activeBreakpoint=s,"unslick"===r.breakpointSettings[s]?r.unslick(s):(r.options=i.extend({},r.originalSettings,r.breakpointSettings[s]),!0===e&&(r.currentSlide=r.options.initialSlide),r.refresh(e)),l=s):null!==r.activeBreakpoint&&(r.activeBreakpoint=null,r.options=r.originalSettings,!0===e&&(r.currentSlide=r.options.initialSlide),r.refresh(e),l=s),e||!1===l||r.$slider.trigger("breakpoint",[r,l])}},e.prototype.changeSlide=function(e,t){var o,s,n,r=this,l=i(e.currentTarget);switch(l.is("a")&&e.preventDefault(),l.is("li")||(l=l.closest("li")),n=r.slideCount%r.options.slidesToScroll!=0,o=n?0:(r.slideCount-r.currentSlide)%r.options.slidesToScroll,e.data.message){case"previous":s=0===o?r.options.slidesToScroll:r.options.slidesToShow-o,r.slideCount>r.options.slidesToShow&&r.slideHandler(r.currentSlide-s,!1,t);break;case"next":s=0===o?r.options.slidesToScroll:o,r.slideCount>r.options.slidesToShow&&r.slideHandler(r.currentSlide+s,!1,t);break;case"index":var d=0===e.data.index?0:e.data.index||l.index()*r.options.slidesToScroll;r.slideHandler(r.checkNavigable(d),!1,t),l.children().trigger("focus");break;default:return}},e.prototype.checkNavigable=function(i){var e,t;if(e=this.getNavigableIndexes(),t=0,i>e[e.length-1])i=e[e.length-1];else for(var o in e){if(i<e[o]){i=t;break}t=e[o]}return i},e.prototype.cleanUpEvents=function(){var e=this;e.options.dots&&null!==e.$dots&&(i("li",e.$dots).off("click.slick",e.changeSlide).off("mouseenter.slick",i.proxy(e.interrupt,e,!0)).off("mouseleave.slick",i.proxy(e.interrupt,e,!1)),!0===e.options.accessibility&&e.$dots.off("keydown.slick",e.keyHandler)),e.$slider.off("focus.slick blur.slick"),!0===e.options.arrows&&e.slideCount>e.options.slidesToShow&&(e.$prevArrow&&e.$prevArrow.off("click.slick",e.changeSlide),e.$nextArrow&&e.$nextArrow.off("click.slick",e.changeSlide),!0===e.options.accessibility&&(e.$prevArrow&&e.$prevArrow.off("keydown.slick",e.keyHandler),e.$nextArrow&&e.$nextArrow.off("keydown.slick",e.keyHandler))),e.$list.off("touchstart.slick mousedown.slick",e.swipeHandler),e.$list.off("touchmove.slick mousemove.slick",e.swipeHandler),e.$list.off("touchend.slick mouseup.slick",e.swipeHandler),e.$list.off("touchcancel.slick mouseleave.
12911slick",e.swipeHandler),e.$list.off("click.slick",e.clickHandler),i(document).off(e.visibilityChange,e.visibility),e.cleanUpSlideEvents(),!0===e.options.accessibility&&e.$list.off("keydown.slick",e.keyHandler),!0===e.options.focusOnSelect&&i(e.$slideTrack).children().off("click.slick",e.selectHandler),i(window).off("orientationchange.slick.slick-"+e.instanceUid,e.orientationChange),i(window).off("resize.slick.slick-"+e.instanceUid,e.resize),i("[draggable!=true]",e.$slideTrack).off("dragstart",e.preventDefault),i(window).off("load.slick.slick-"+e.instanceUid,e.setPosition)},e.prototype.cleanUpSlideEvents=function(){var e=this;e.$list.off("mouseenter.slick",i.proxy(e.interrupt,e,!0)),e.$list.off("mouseleave.slick",i.proxy(e.interrupt,e,!1))},e.prototype.cleanUpRows=function(){var i,e=this;e.options.rows>1&&((i=e.$slides.children().children()).removeAttr("style"),e.$slider.empty().append(i))},e.prototype.clickHandler=function(i){!1===this.shouldClick&&(i.stopImmediatePropagation(),i.stopPropagation(),i.preventDefault())},e.prototype.destroy=function(e){var t=this;t.autoPlayClear(),t.touchObject={},t.cleanUpEvents(),i(".slick-cloned",t.$slider).detach(),t.$dots&&t.$dots.remove(),t.$prevArrow&&t.$prevArrow.length&&(t.$prevArrow.removeClass("slick-disabled slick-arrow slick-hidden").removeAttr("aria-hidden aria-disabled tabindex").css("display",""),t.htmlExpr.test(t.options.prevArrow)&&t.$prevArrow.remove()),t.$nextArrow&&t.$nextArrow.length&&(t.$nextArrow.removeClass("slick-disabled slick-arrow slick-hidden").removeAttr("aria-hidden aria-disabled tabindex").css("display",""),t.htmlExpr.test(t.options.nextArrow)&&t.$nextArrow.remove()),t.$slides&&(t.$slides.removeClass("slick-slide slick-active slick-center slick-visible slick-current").removeAttr("aria-hidden").removeAttr("data-slick-index").each(function(){i(this).attr("style",i(this).data("originalStyling"))}),t.$slideTrack.children(this.options.slide).detach(),t.$slideTrack.detach(),t.$list.detach(),t.$slider.append(t.$slides)),t.cleanUpRows(),t.$slider.removeClass("slick-slider"),t.$slider.removeClass("slick-initialized"),t.$slider.removeClass("slick-dotted"),t.unslicked=!0,e||t.$slider.trigger("destroy",[t])},e.prototype.disableTransition=function(i){var e=this,t={};t[e.transitionType]="",!1===e.options.fade?e.$slideTrack.css(t):e.$slides.eq(i).css(t)},e.prototype.fadeSlide=function(i,e){var t=this;!1===t.cssTransitions?(t.$slides.eq(i).css({zIndex:t.options.zIndex}),t.$slides.eq(i).animate({opacity:1},t.options.speed,t.options.easing,e)):(t.applyTransition(i),t.$slides.eq(i).css({opacity:1,zIndex:t.options.zIndex}),e&&setTimeout(function(){t.disableTransition(i),e.call()},t.options.speed))},e.prototype.fadeSlideOut=function(i){var e=this;!1===e.cssTransitions?e.$slides.eq(i).animate({opacity:0,zIndex:e.options.zIndex-2},e.options.speed,e.options.easing):(e.applyTransition(i),e.$slides.eq(i).css({opacity:0,zIndex:e.options.zIndex-2}))},e.prototype.filterSlides=e.prototype.slickFilter=function(i){var e=this;null!==i&&(e.$slidesCache=e.$slides,e.unload(),e.$slideTrack.children(this.options.slide).detach(),e.$slidesCache.filter(i).appendTo(e.$slideTrack),e.reinit())},e.prototype.focusHandler=function(){var e=this;e.$slider.off("focus.slick blur.slick").on("focus.slick blur.slick","*",function(t){t.stopImmediatePropagation();var o=i(this);setTimeout(function(){e.options.pauseOnFocus&&(e.focussed=o.is(":focus"),e.autoPlay())},0)})},e.prototype.getCurrent=e.prototype.slickCurrentSlide=function(){return this.currentSlide},e.prototype.getDotCount=function(){var i=this,e=0,t=0,o=0;if(!0===i.options.infinite)if(i.slideCount<=i.options.slidesToShow)++o;else for(;e<i.slideCount;)++o,e=t+i.options.slidesToScroll,t+=i.options.slidesToScroll<=i.options.slidesToShow?i.options.slidesToScroll:i.options.slidesToShow;else if(!0===i.options.centerMode)o=i.slideCount;else if(i.options.asNavFor)for(;e<i.slideCount;)++o,e=t+i.options.slidesToScroll,t+=i.options.slidesToScroll<=i.options.slidesToShow?i.options.slidesToScroll:i.options.slidesToShow;else o=1+Math.ceil((i.slideCount-i.options.slidesToShow)/i.options.slidesToScroll);return o-1},e.prototype.getLeft=function(i){var e,t,o,s,n=this,r=0;return n.slideOffset=0,t=n.$slides.first().outerHeight(!0),!0===n.options.infinite?(n.slideCount>n.options.slidesToShow&&(n.slideOffset=n.slideWidth*n.options.slidesToShow*-1,s=-1,!0===n.options.vertical&&!0===n.options.centerMode&&(2===n.options.slidesToShow?s=-1.5:1===n.options.slidesToShow&&(s=-2)),r=t*n.options.slidesToShow*s),n.slideCount%n.options.slidesToScroll!=0&&i+n.options.slidesToScroll>n.slideCount&&n.slideCount>n.options.slidesToShow&&(i>n.slideCount?(n.slideOffset=(n.options.slidesToShow-(i-n.slideCount))*n.slideWidth*-1,r=(n.options.slidesToShow-(i-n.slideCount))*t*-1):(n.slideOffset=n.slideCount%n.options.slidesToScroll*n.slideWidth*-1,r=n.slideCount%n.options.slidesToScroll*t*-1))):i+n.options.slidesToShow>n.slideCount&&(n.slideOffset=(i+n.options.slidesToShow-n.slideCount)*n.slideWidth,r=(i+n.options.slidesToShow-n.slideCount)*t),n.slideCount<=n.options.slidesToShow&&(n.slideOffset=0,r=0),!0===n.options.centerMode&&n.slideCount<=n.options.slidesToShow?n.slideOffset=n.slideWidth*Math.floor(n.options.slidesToShow)/2-n.slideWidth*n.slideCount/2:!0===n.options.centerMode&&!0===n.options.infinite?n.slideOffset+=n.slideWidth*Math.floor(n.options.slidesToShow/2)-n.slideWidth:!0===n.options.centerMode&&(n.slideOffset=0,n.slideOffset+=n.slideWidth*Math.floor(n.options.slidesToShow/2)),e=!1===n.options.vertical?i*n.slideWidth*-1+n.slideOffset:i*t*-1+r,!0===n.options.variableWidth&&(o=n.slideCount<=n.options.slidesToShow||!1===n.options.infinite?n.$slideTrack.children(".slick-slide").eq(i):n.$slideTrack.children(".slick-slide").eq(i+n.options.slidesToShow),e=!0===n.options.rtl?o[0]?-1*(n.$slideTrack.width()-o[0].offsetLeft-o.width()):0:o[0]?-1*o[0].offsetLeft:0,!0===n.options.centerMode&&(o=n.slideCount<=n.options.slidesToShow||!1===n.options.infinite?n.$slideTrack.children(".slick-slide").eq(i):n.$slideTrack.children(".slick-slide").eq(i+n.options.slidesToShow+1),e=!0===n.options.rtl?o[0]?-1*(n.$slideTrack.width()-o[0].offsetLeft-o.width()):0:o[0]?-1*o[0].offsetLeft:0,e+=(n.$list.width()-o.outerWidth())/2)),e},e.prototype.getOption=e.prototype.slickGetOption=function(i){return this.options[i]},e.prototype.getNavigableIndexes=function(){var i,e=this,t=0,o=0,s=[];for(!1===e.options.infinite?i=e.slideCount:(t=-1*e.options.slidesToScroll,o=-1*e.options.slidesToScroll,i=2*e.slideCount);t<i;)s.push(t),t=o+e.options.slidesToScroll,o+=e.options.slidesToScroll<=e.options.slidesToShow?e.options.slidesToScroll:e.options.slidesToShow;return s},e.prototype.getSlick=function(){return this},e.prototype.getSlideCount=function(){var e,t,o=this;return t=!0===o.options.centerMode?o.slideWidth*Math.floor(o.options.slidesToShow/2):0,!0===o.options.swipeToSlide?(o.$slideTrack.find(".slick-slide").each(function(s,n){if(n.offsetLeft-t+i(n).outerWidth()/2>-1*o.swipeLeft)return e=n,!1}),Math.abs(i(e).attr("data-slick-index")-o.currentSlide)||1):o.options.slidesToScroll},e.prototype.goTo=e.prototype.slickGoTo=function(i,e){this.changeSlide({data:{message:"index",index:
12911parseInt(i)}},e)},e.prototype.init=function(e){var t=this;i(t.$slider).hasClass("slick-initialized")||(i(t.$slider).addClass("slick-initialized"),t.buildRows(),t.buildOut(),t.setProps(),t.startLoad(),t.loadSlider(),t.initializeEvents(),t.updateArrows(),t.updateDots(),t.checkResponsive(!0),t.focusHandler()),e&&t.$slider.trigger("init",[t]),!0===t.options.accessibility&&t.initADA(),t.options.autoplay&&(t.paused=!1,t.autoPlay())},e.prototype.initADA=function(){var e=this,t=Math.ceil(e.slideCount/e.options.slidesToShow),o=e.getNavigableIndexes().filter(function(i){return i>=0&&i<e.slideCount});e.$slides.add(e.$slideTrack.find(".slick-cloned")).attr({"aria-hidden":"true",tabindex:"-1"}).find("a, input, button, select").attr({tabindex:"-1"}),null!==e.$dots&&(e.$slides.not(e.$slideTrack.find(".slick-cloned")).each(function(t){var s=o.indexOf(t);i(this).attr({role:"tabpanel",id:"slick-slide"+e.instanceUid+t,tabindex:-1}),-1!==s&&i(this).attr({"aria-describedby":"slick-slide-control"+e.instanceUid+s})}),e.$dots.attr("role","tablist").find("li").each(function(s){var n=o[s];i(this).attr({role:"presentation"}),i(this).find("button").first().attr({role:"tab",id:"slick-slide-control"+e.instanceUid+s,"aria-controls":"slick-slide"+e.instanceUid+n,"aria-label":s+1+" of "+t,"aria-selected":null,tabindex:"-1"})}).eq(e.currentSlide).find("button").attr({"aria-selected":"true",tabindex:"0"}).end());for(var s=e.currentSlide,n=s+e.options.slidesToShow;s<n;s++)e.$slides.eq(s).attr("tabindex",0);e.activateADA()},e.prototype.initArrowEvents=function(){var i=this;!0===i.options.arrows&&i.slideCount>i.options.slidesToShow&&(i.$prevArrow.off("click.slick").on("click.slick",{message:"previous"},i.changeSlide),i.$nextArrow.off("click.slick").on("click.slick",{message:"next"},i.changeSlide),!0===i.options.accessibility&&(i.$prevArrow.on("keydown.slick",i.keyHandler),i.$nextArrow.on("keydown.slick",i.keyHandler)))},e.prototype.initDotEvents=function(){var e=this;!0===e.options.dots&&(i("li",e.$dots).on("click.slick",{message:"index"},e.changeSlide),!0===e.options.accessibility&&e.$dots.on("keydown.slick",e.keyHandler)),!0===e.options.dots&&!0===e.options.pauseOnDotsHover&&i("li",e.$dots).on("mouseenter.slick",i.proxy(e.interrupt,e,!0)).on("mouseleave.slick",i.proxy(e.interrupt,e,!1))},e.prototype.initSlideEvents=function(){var e=this;e.options.pauseOnHover&&(e.$list.on("mouseenter.slick",i.proxy(e.interrupt,e,!0)),e.$list.on("mouseleave.slick",i.proxy(e.interrupt,e,!1)))},e.prototype.initializeEvents=function(){var e=this;e.initArrowEvents(),e.initDotEvents(),e.initSlideEvents(),e.$list.on("touchstart.slick mousedown.slick",{action:"start"},e.swipeHandler),e.$list.on("touchmove.slick mousemove.slick",{action:"move"},e.swipeHandler),e.$list.on("touchend.slick mouseup.slick",{action:"end"}
12911,e.swipeHandler),e.$list.on("touchcancel.slick mouseleave.slick",{action:"end"},e.swipeHandler),e.$list.on("click.slick",e.clickHandler),i(document).on(e.visibilityChange,i.proxy(e.visibility,e)),!0===e.options.accessibility&&e.$list.on("keydown.slick",e.keyHandler),!0===e.options.focusOnSelect&&i(e.$slideTrack).children().on("click.slick",e.selectHandler),i(window).on("orientationchange.slick.slick-"+e.instanceUid,i.proxy(e.orientationChange,e)),i(window).on("resize.slick.slick-"+e.instanceUid,i.proxy(e.resize,e)),i("[draggable!=true]",e.$slideTrack).on("dragstart",e.preventDefault),i(window).on("load.slick.slick-"+e.instanceUid,e.setPosition),i(e.setPosition)},e.prototype.initUI=function(){var i=this;!0===i.options.arrows&&i.slideCount>i.options.slidesToShow&&(i.$prevArrow.show(),i.$nextArrow.show()),!0===i.options.dots&&i.slideCount>i.options.slidesToShow&&i.$dots.show()},e.prototype.keyHandler=function(i){var e=this;i.target.tagName.match("TEXTAREA|INPUT|SELECT")||(37===i.keyCode&&!0===e.options.accessibility?e.changeSlide({data:{message:!0===e.options.rtl?"next":"previous"}}):39===i.keyCode&&!0===e.options.accessibility&&e.changeSlide({data:{message:!0===e.options.rtl?"previous":"next"}}))},e.prototype.lazyLoad=function(){function e(e){i("img[data-lazy]",e).each(function(){var e=i(this),t=i(this).attr("data-lazy"),o=i(this).attr("data-srcset"),s=i(this).attr("data-sizes")||n.$slider.attr("data-sizes"),r=document.createElement("img");r.onload=function(){e.animate({opacity:0}
vendor: 5,619 bytes, line 12911
12911,100,function(){o&&(e.attr("srcset",o),s&&e.attr("sizes",s)),e.attr("src",t).animate({opacity:1},200,function(){e.removeAttr("data-lazy data-srcset data-sizes").removeClass("slick-loading")}),n.$slider.trigger("lazyLoaded",[n,e,t])})},r.onerror=function(){e.removeAttr("data-lazy").removeClass("slick-loading").addClass("slick-lazyload-error"),n.$slider.trigger("lazyLoadError",[n,e,t])},r.src=t})}var t,o,s,n=this;if(!0===n.options.centerMode?!0===n.options.infinite?s=(o=n.currentSlide+(n.options.slidesToShow/2+1))+n.options.slidesToShow+2:(o=Math.max(0,n.currentSlide-(n.options.slidesToShow/2+1)),s=n.options.slidesToShow/2+1+2+n.currentSlide):(o=n.options.infinite?n.options.slidesToShow+n.currentSlide:n.currentSlide,s=Math.ceil(o+n.options.slidesToShow),!0===n.options.fade&&(o>0&&o--,s<=n.slideCount&&s++)),t=n.$slider.find(".slick-slide").slice(o,s),"anticipated"===n.options.lazyLoad)for(var r=o-1,l=s,d=n.$slider.find(".slick-slide"),a=0;a<n.options.slidesToScroll;a++)r<0&&(r=n.slideCount-1),t=(t=t.add(d.eq(r))).add(d.eq(l)),r--,l++;e(t),n.slideCount<=n.options.slidesToShow?e(n.$slider.find(".slick-slide")):n.currentSlide>=n.slideCount-n.options.slidesToShow?e(n.$slider.find(".slick-cloned").slice(0,n.options.slidesToShow)):0===n.currentSlide&&e(n.$slider.find(".slick-cloned").slice(-1*n.options.slidesToShow))},e.prototype.loadSlider=function(){var i=this;i.setPosition(),i.$slideTrack.css({opacity:1}),i.$slider.removeClass("slick-loading"),i.initUI(),"progressive"===i.options.lazyLoad&&i.progressiveLazyLoad()},e.prototype.next=e.prototype.slickNext=function(){this.changeSlide({data:{message:"next"}})},e.prototype.orientationChange=function(){var i=this;i.checkResponsive(),i.setPosition()},e.prototype.pause=e.prototype.slickPause=function(){var i=this;i.autoPlayClear(),i.paused=!0},e.prototype.play=e.prototype.slickPlay=function(){var i=this;i.autoPlay(),i.options.autoplay=!0,i.paused=!1,i.focussed=!1,i.interrupted=!1},e.prototype.postSlide=function(e){var t=this;t.unslicked||(t.$slider.trigger("afterChange",[t,e]),t.animating=!1,t.slideCount>t.options.slidesToShow&&t.setPosition(),t.swipeLeft=null,t.options.autoplay&&t.autoPlay(),!0===t.options.accessibility&&(t.initADA(),t.options.focusOnChange&&i(t.$slides.get(t.currentSlide)).attr("tabindex",0).focus()))},e.prototype.prev=e.prototype.slickPrev=function(){this.changeSlide({data:{message:"previous"}})},e.prototype.preventDefault=function(i){i.preventDefault()},e.prototype.progressiveLazyLoad=function(e){e=e||1;var t,o,s,n,r,l=this,d=i("img[data-lazy]",l.$slider);d.length?(t=d.first(),o=t.attr("data-lazy"),s=t.attr("data-srcset"),n=t.attr("data-sizes")||l.$slider.attr("data-sizes"),(r=document.createElement("img")).onload=function(){s&&(t.attr("srcset",s),n&&t.attr("sizes",n)),t.attr("src",o).removeAttr("data-lazy data-srcset data-sizes").removeClass("slick-loading"),!0===l.options.adaptiveHeight&&l.setPosition(),l.$slider.trigger("lazyLoaded",[l,t,o]),l.progressiveLazyLoad()},r.onerror=function(){e<3?setTimeout(function(){l.progressiveLazyLoad(e+1)},500):(t.removeAttr("data-lazy").removeClass("slick-loading").addClass("slick-lazyload-error"),l.$slider.trigger("lazyLoadError",[l,t,o]),l.progressiveLazyLoad())},r.src=o):l.$slider.trigger("allImagesLoaded",[l])},e.prototype.refresh=function(e){var t,o,s=this;o=s.slideCount-s.options.slidesToShow,!s.options.infinite&&s.currentSlide>o&&(s.currentSlide=o),s.slideCount<=s.options.slidesToShow&&(s.currentSlide=0),t=s.currentSlide,s.destroy(!0),i.extend(s,s.initials,{currentSlide:t}),s.init(),e||s.changeSlide({data:{message:"index",index:t}},!1)},e.prototype.registerBreakpoints=function(){var e,t,o,s=this,n=s.options.responsive||null;if("array"===i.type(n)&&n.length){s.respondTo=s.options.respondTo||"window";for(e in n)if(o=s.breakpoints.length-1,n.hasOwnProperty(e)){for(t=n[e].breakpoint;o>=0;)s.breakpoints[o]&&s.breakpoints[o]===t&&s.breakpoints.splice(o,1),o--;s.breakpoints.push(t),s.breakpointSettings[t]=n[e].settings}s.breakpoints.sort(function(i,e){return s.options.mobileFirst?i-e:e-i})}},e.prototype.reinit=function(){var e=this;e.$slides=e.$slideTrack.children(e.options.slide).addClass("slick-slide"),e.slideCount=e.$slides.length,e.currentSlide>=e.slideCount&&0!==e.currentSlide&&(e.currentSlide=e.currentSlide-e.options.slidesToScroll),e.slideCount<=e.options.slidesToShow&&(e.currentSlide=0),e.registerBreakpoints(),e.setProps(),e.setupInfinite(),e.buildArrows(),e.updateArrows(),e.initArrowEvents(),e.buildDots(),e.updateDots(),e.initDotEvents(),e.cleanUpSlideEvents(),e.initSlideEvents(),e.checkResponsive(!1,!0),!0===e.options.focusOnSelect&&i(e.$slideTrack).children().on("click.slick",e.selectHandler),e.setSlideClasses("number"==typeof e.currentSlide?e.currentSlide:0),e.setPosition(),e.focusHandler(),e.paused=!e.options.autoplay,e.autoPlay(),e.$slider.trigger("reInit",[e])},e.prototype.resize=function(){var e=this;i(window).width()!==e.windowWidth&&(clearTimeout(e.windowDelay),e.windowDelay=window.setTimeout(function(){e.windowWidth=i(window).width(),e.checkResponsive(),e.unslicked||e.setPosition()},50))},e.prototype.removeSlide=e.prototype.slickRemove=function(i,e,t){var o=this;if(i="boolean"==typeof i?!0===(e=i)?0:o.slideCount-1:!0===e?--i:i,o.slideCount<1||i<0||i>o.slideCount-1)return!1;o.unload(),!0===t?o.$slideTrack.children().remove():o.$slideTrack.children(this.options.slide).eq(i).remove(),o.$slides=o.$slideTrack.children(this.options.slide),o.$slideTrack.children(this.options.slide).detach(),o.$slideTrack.append(o.$slides),o.$slidesCache=o.$slides,o.reinit()},e.prototype.setCSS=function(i){var e,t,o=this,s={};
12911!0===o.options.rtl&&(i=-i),e="left"==o.positionProp?Math.ceil(i)+"px":"0px",t="top"==o.positionProp?Math.ceil(i)+"px":"0px",s[o.positionProp]=i,!1===o.transformsEnabled?o.$slideTrack.css(s):(s={},!1===o.cssTransitions?(s[o.animType]="translate("+e+", "+t+")",o.$slideTrack.css(s)):(s[o.animType]="translate3d("+e+", "+t+", 0px)",o.$slideTrack.css(s)))},e.prototype.setDimensions=function(){var i=this;!1===i.options.vertical?!0===i.options.centerMode&&i.$list.css({padding:"0px "+i.options.centerPadding}):(i.$list.height(i.$slides.first().outerHeight(!0)*i.options.slidesToShow),!0===i.options.centerMode&&i.$list.css({padding:i.options.centerPadding+" 0px"})),i.listWidth=i.$list.width(),i.listHeight=i.$list.height(),!1===i.options.vertical&&!1===i.options.variableWidth?(i.slideWidth=Math.ceil(i.listWidth/i.options.slidesToShow),i.$slideTrack.width(Math.ceil(i.slideWidth*i.$slideTrack.children(".slick-slide").length))):!0===i.options.variableWidth?i.$slideTrack.width(5e3*i.slideCount):(i.slideWidth=Math.ceil(i.listWidth),i.$slideTrack.height(Math.ceil(i.$slides.first().outerHeight(!0)*i.$slideTrack.children(".slick-slide").length)));var e=i.$slides.first().outerWidth(!0)-i.$slides.first().width();!1===i.options.variableWidth&&i.$slideTrack.children(".slick-slide").width(i.slideWidth-e)},e.prototype.setFade=function(){var e,t=this;t.$slides.each(function(o,s){e=t.slideWidth*o*-1,!0===t.options.rtl?i(s).css({position:"relative",right:e,top:0,zIndex:t.options.zIndex-2,opacity:0}
12911):i(s).css({position:"relative",left:e,top:0,zIndex:t.options.zIndex-2,opacity:0})}),t.$slides.eq(t.currentSlide).css({zIndex:t.options.zIndex-1,opacity:1})},e.prototype.setHeight=function(){var i=this;if(1===i.options.slidesToShow&&!0===i.options.adaptiveHeight&&!1===i.options.vertical){var e=i.$slides.eq(i.currentSlide).outerHeight(!0);i.$list.css("height",e)}},e.prototype.setOption=e.prototype.slickSetOption=function(){var e,t,o,s,n,r=this,l=!1;if("object"===i.type(arguments[0])?(o=arguments[0],l=arguments[1],n="multiple"):"string"===i.type(arguments[0])&&(o=arguments[0],s=arguments[1],l=arguments[2],"responsive"===arguments[0]&&"array"===i.type(arguments[1])?n="responsive":void 0!==arguments[1]&&(n="single")),"single"===n)r.options[o]=s;else if("multiple"===n)i.each(o,function(i,e){r.options[i]=e});else if("responsive"===n)for(t in s)if("array"!==i.type(r.options.responsive))r.options.responsive=[s[t]];else{for(e=r.options.responsive.length-1;e>=0;)r.options.responsive[e].breakpoint===s[t].breakpoint&&r.options.responsive.splice(e,1),e--;r.options.responsive.push(s[t])}l&&(r.unload(),r.reinit())},e.prototype.setPosition=function(){var i=this;i.setDimensions(),i.setHeight(),!1===i.options.fade?i.setCSS(i.getLeft(i.currentSlide)):i.setFade(),i.$slider.trigger("setPosition",[i])},e.prototype.setProps=function(){var i=this,e=document.body.style;i.positionProp=!0===i.options.vertical?"top":"left","top"===i.positionProp?i.$slider.addClass("slick-vertical"):i.$slider.removeClass("slick-vertical"),void 0===e.WebkitTransition&&void 0===e.MozTransition&&void 0===e.msTransition||!0===i.options.useCSS&&(i.cssTransitions=!0),i.options.fade&&("number"==typeof i.options.zIndex?i.options.zIndex<3&&(i.options.zIndex=3):i.options.zIndex=i.defaults.zIndex),void 0!==e.OTransform&&(i.animType="OTransform",i.transformType="-o-transform",i.transitionType="OTransition",void 0===e.perspectiveProperty&&void 0===e.webkitPerspective&&(i.animType=!1)),void 0!==e.MozTransform&&(i.animType="MozTransform",i.transformType="-moz-transform",i.transitionType="MozTransition",void 0===e.perspectiveProperty&&void 0===e.MozPerspective&&(i.animType=!1)),void 0!==e.webkitTransform&&(i.animType="webkitTransform",i.transformType="-webkit-transform",i.transitionType="webkitTransition",void 0===e.perspectiveProperty&&void 0===e.webkitPerspective&&(i.animType=!1)),void 0!==e.msTransform&&(i.animType="msTransform",i.transformType="-ms-transform",i.transitionType="msTransition",void 0===e.msTransform&&(i.animType=!1)),void 0!==e.transform&&!1!==i.animType&&(i.animType="transform",i.transformType="transform",i.transitionType="transition"),i.transformsEnabled=i.options.useTransform&&null!==i.animType&&!1!==i.animType},e.prototype.setSlideClasses=function(i){var e,t,o,s,n=this;if(t=n.$slider.find(".slick-slide").removeClass("slick-active slick-center slick-current").attr("aria-hidden","true"),n.$slides.eq(i).addClass("slick-current"),!0===n.options.centerMode){var r=n.options.slidesToShow%2==0?1:0;e=Math.floor(n.options.slidesToShow/2),!0===n.options.infinite&&(i>=e&&i<=n.slideCount-1-e?n.$slides.slice(i-e+r,i+e+1).addClass("slick-active").attr("aria-hidden","false"):(o=n.options.slidesToShow+i,t.slice(o-e+1+r,o+e+2).addClass("slick-active").attr("aria-hidden","false")),0===i?t.eq(t.length-1-n.options.slidesToShow).addClass("slick-center"):i===n.slideCount-1&&t.eq(n.options.slidesToShow).addClass("slick-center")),n.$slides.eq(i).addClass("slick-center")}else i>=0&&i<=n.slideCount-n.options.slidesToShow?n.$slides.slice(i,i+n.options.slidesToShow).addClass("slick-active").attr("aria-hidden","false"):t.length<=n.options.slidesToShow?t.addClass("slick-active").attr("aria-hidden","false"):(s=n.slideCount%n.options.slidesToShow,o=!0===n.options.infinite?n.options.slidesToShow+i:i,n.options.slidesToShow==n.options.slidesToScroll&&n.slideCount-i<n.options.slidesToShow?t.slice(o-(n.options.slidesToShow-s),o+s).addClass("slick-active").attr("aria-hidden","false"):t.slice(o,o+n.options.slidesToShow).addClass("slick-active").attr("aria-hidden","false"));"ondemand"!==n.options.lazyLoad&&"anticipated"!==n.options.lazyLoad||n.lazyLoad()},e.prototype.setupInfinite=function(){var e,t,o,s=this;if(!0===s.options.fade&&(s.options.centerMode=!1),!0===s.options.infinite&&!1===s.options.fade&&(t=null,s.slideCount>s.options.slidesToShow)){for(o=!0===s.options.centerMode?s.options.slidesToShow+1:s.options.slidesToShow,e=s.slideCount;e>s.slideCount-o;e-=1)t=e-1,i(s.$slides[t]).clone(!0).attr("id","").attr("data-slick-index",t-s.slideCount).prependTo(s.$slideTrack).addClass("slick-cloned");for(e=0;e<o+s.slideCount;e+=1)t=e,i(s.$slides[t]).clone(!0).attr("id","").attr("data-slick-index",t+s.slideCount).appendTo(s.$slideTrack).addClass("slick-cloned");s.$slideTrack.find(".slick-cloned").find("[id]").each(function(){i(this).attr("id","")})}},e.prototype.interrupt=function(i){var e=this;i||e.autoPlay(),e.interrupted=i},e.prototype.selectHandler=function(e){var t=this,o=i(e.target).is(".slick-slide")?i(e.target):i(e.target).parents(".slick-slide"),s=parseInt(o.attr("data-slick-index"));s||(s=0),t.slideCount<=t.options.slidesToShow?t.slideHandler(s,!1,!0):t.slideHandler(s)},e.prototype.slideHandler=function(i,e,t){var o,s,n,r,l,d=null,a=this;if(e=e||!1,!(!0===a.animating&&!0===a.options.waitForAnimate||!0===a.options.fade&&a.currentSlide===i))if(!1===e&&a.asNavFor(i),o=i,d=a.getLeft(o),r=a.getLeft(a.currentSlide),a.currentLeft=null===a.swipeLeft?r:a.swipeLeft,!1===a.options.infinite&&!1===a.options.centerMode&&(i<0||i>a.getDotCount()*a.options.slidesToScroll))!1===a.options.fade&&(o=a.currentSlide,!0!==t?a.animateSlide(r,function(){a.postSlide(o)}):a.postSlide(o));else if(!1===a.options.infinite&&!0===a.options.centerMode&&(i<0||i>a.slideCount-a.options.slidesToScroll))!1===a.options.fade&&(o=a.currentSlide,!0!==t?a.animateSlide(r,function(){a.postSlide(o)}):a.postSlide(o));else{if(a.options.autoplay&&clearInterval(a.autoPlayTimer),s=o<0?a.slideCount%a.options.slidesToScroll!=0?a.slideCount-a.slideCount%a.options.slidesToScroll:a.slideCount+
12911o:o>=a.slideCount?a.slideCount%a.options.slidesToScroll!=0?0:o-a.slideCount:o,a.animating=!0,a.$slider.trigger("beforeChange",[a,a.currentSlide,s]),n=a.currentSlide,a.currentSlide=s,a.setSlideClasses(a.currentSlide),a.options.asNavFor&&(l=(l=a.getNavTarget()).slick("getSlick")).slideCount<=l.options.slidesToShow&&l.setSlideClasses(a.currentSlide),a.updateDots(),a.updateArrows(),!0===a.options.fade)return!0!==t?(a.fadeSlideOut(n),a.fadeSlide(s,function(){a.postSlide(s)})):a.postSlide(s),void a.animateHeight();!0!==t?a.animateSlide(d,function(){a.postSlide(s)}):a.postSlide(s)}},e.prototype.startLoad=function(){var i=this;!0===i.options.arrows&&i.slideCount>i.options.slidesToShow&&(i.$prevArrow.hide(),i.$nextArrow.hide()),!0===i.options.dots&&i.slideCount>i.options.slidesToShow&&i.$dots.hide(),i.$slider.addClass("slick-loading")},e.prototype.swipeDirection=function(){var i,e,t,o,s=this;return i=s.touchObject.startX-s.touchObject.curX,e=s.touchObject.startY-s.touchObject.curY,t=Math.atan2(e,i),(o=Math.round(180*t/Math.PI))<0&&(o=360-Math.abs(o)),o<=45&&o>=0?!1===s.options.rtl?"left":"right":o<=360&&o>=315?!1===s.options.rtl?"left":"right":o>=135&&o<=225?!1===s.options.rtl?"right":"left":!0===s.options.verticalSwiping?o>=35&&o<=135?"down":"up":"vertical"},e.prototype.swipeEnd=function(i){var e,t,o=this;if(o.dragging=!1,o.swiping=!1,o.scrolling)return o.scrolling=!1,!1;if(o.interrupted=!1,o.shouldClick=!(o.touchObject.swipeLength>10),void 0===o.touchObject.curX)return!1;if(!0===o.touchObject.edgeHit&&o.$slider.trigger("edge",[o,o.swipeDirection()]),o.touchObject.swipeLength>=o.touchObject.minSwipe){switch(t=o.swipeDirection()){case"left":case"down":e=o.options.swipeToSlide?o.checkNavigable(o.currentSlide+o.getSlideCount()):o.currentSlide+o.getSlideCount(),o.currentDirection=0;break;case"right":case"up":e=o.options.swipeToSlide?o.checkNavigable(o.currentSlide-o.getSlideCount()):o.currentSlide-o.getSlideCount(),o.currentDirection=1}"vertical"!=t&&(o.slideHandler(e),o.touchObject={},o.$slider.trigger("swipe",[o,t]))}else o.touchObject.startX!==o.touchObject.curX&&(o.slideHandler(o.currentSlide),o.touchObject={})},e.prototype.swipeHandler=function(i){var e=this;if(!(!1===e.options.swipe||"ontouchend"in document&&!1===e.options.swipe||!1===e.options.draggable&&-1!==i.type.indexOf("mouse")))switch(e.touchObject.fingerCount=i.originalEvent&&void 0!==i.originalEvent.touches?i.originalEvent.touches.length:1,e.touchObject.minSwipe=e.listWidth/e.options.touchThreshold,!0===e.options.verticalSwiping&&(e.touchObject.minSwipe=e.listHeight/e.options.touchThreshold),i.data.action){case"start":e.swipeStart(i);break;case"move":e.swipeMove(i);break;case"end":e.swipeEnd(i)}},e.prototype.swipeMove=function(i){var e,t,o,s,n,r,l=this;return n=void 0!==i.originalEvent?i.originalEvent.touches:null,!(!l.dragging||l.scrolling||n&&1!==n.length)&&(e=l.getLeft(l.currentSlide),l.touchObject.curX=void 0!==n?n[0].pageX:i.clientX,l.touchObject.curY=void 0!==n?n[0].pageY:i.clientY,l.touchObject.swipeLength=Math.round(Math.sqrt(Math.pow(l.touchObject.curX-l.touchObject.startX,2))),r=Math.round(Math.sqrt(Math.pow(l.touchObject.curY-l.touchObject.startY,2))),!l.options.verticalSwiping&&!l.swiping&&r>4?(l.scrolling=!0,!1):(!0===l.options.verticalSwiping&&(l.touchObject.swipeLength=r),t=l.swipeDirection(),void 0!==i.originalEvent&&l.touchObject.swipeLength>4&&(l.swiping=!0,i.preventDefault()),s=(!1===l.options.rtl?1:-1)*(l.touchObject.curX>l.touchObject.startX?1:-1),!0===l.options.verticalSwiping&&(s=l.touchObject.curY>l.touchObject.startY?1:-1),o=l.touchObject.swipeLength,l.touchObject.edgeHit=!1,!1===l.options.infinite&&(0===l.currentSlide&&"right"===t||l.currentSlide>=l.getDotCount()&&"left"===t)&&(o=l.touchObject.swipeLength*l.options.edgeFriction,l.touchObject.edgeHit=!0),!1===l.options.vertical?l.swipeLeft=e+o*s:l.swipeLeft=e+o*(l.$list.height()/l.listWidth)*s,!0===l.options.verticalSwiping&&(l.swipeLeft=e+o*s),!0!==l.options.fade&&!1!==l.options.touchMove&&(!0===l.animating?(l.swipeLeft=null,!1):void l.setCSS(l.swipeLeft))))},e.prototype.swipeStart=function(i){var e,t=this;if(t.interrupted=!0,1!==t.touchObject.fingerCount||t.slideCount<=t.options.slidesToShow)return t.touchObject={},!1;void 0!==i.originalEvent&&void 0!==i.originalEvent.touches&&(e=i.originalEvent.touches[0]),t.touchObject.startX=t.touchObject.curX=void 0!==e?e.pageX:i.clientX,t.touchObject.startY=t.touchObject.curY=void 0!==e?e.pageY:i.clientY,t.dragging=!0},e.prototype.unfilterSlides=e.prototype.slickUnfilter=function(){var i=this;null!==i.$slidesCache&&(i.unload(),i.$slideTrack.children(this.options.slide).detach(),i.$slidesCache.appendTo(i.$slideTrack),i.reinit())},e.prototype.unload=function(){var e=this;i(".slick-cloned",e.$slider).remove(),e.$dots&&e.$dots.remove(),e.$prevArrow&&e.htmlExpr.test(e.options.prevArrow)&&e.$prevArrow.remove(),e.$nextArrow&&e.htmlExpr.test(e.options.nextArrow)&&e.$nextArrow.remove(),e.$slides.removeClass("slick-slide slick-active slick-visible slick-current").attr("aria-hidden","true").css("width","")}
12911,e.prototype.unslick=function(i){var e=this;e.$slider.trigger("unslick",[e,i]),e.destroy()},e.prototype.updateArrows=function(){var i=this;Math.floor(i.options.slidesToShow/2),!0===i.options.arrows&&i.slideCount>i.options.slidesToShow&&!i.options.infinite&&(i.$prevArrow.removeClass("slick-disabled").attr("aria-disabled","false"),i.$nextArrow.removeClass("slick-disabled").attr("aria-disabled","false"),0===i.currentSlide?(i.$prevArrow.addClass("slick-disabled").attr("aria-disabled","true"),i.$nextArrow.removeClass("slick-disabled").attr("aria-disabled","false")):i.currentSlide>=i.slideCount-i.options.slidesToShow&&!1===i.options.centerMode?(i.$nextArrow.addClass("slick-disabled").attr("aria-disabled","true"),i.$prevArrow.removeClass("slick-disabled").attr("aria-disabled","false")):i.currentSlide>=i.slideCount-1&&!0===i.options.centerMode&&(i.$nextArrow.addClass("slick-disabled").attr("aria-disabled","true"),i.$prevArrow.removeClass("slick-disabled").attr("aria-disabled","false")))},e.prototype.updateDots=function(){var i=this;null!==i.$dots&&(i.$dots.find("li").removeClass("slick-active").end(),i.$dots.find("li").eq(Math.floor(i.currentSlide/i.options.slidesToScroll)).addClass("slick-active"))},e.prototype.visibility=function(){var i=this;i.options.autoplay&&(document[i.hidden]?i.interrupted=!0:i.interrupted=!1)},i.fn.slick=function(){var i,t,o=this,s=arguments[0],n=Array.prototype.slice.call(arguments,1),r=o.length;for(i=0;i<r;i++)if("object"==typeof s||void 0===s?o[i].slick=new e(o[i],s):t=o[i].slick[s].apply(o[i].slick,n),void 0!==t)return t;return o}});
12912
12913shcDOMContentLoaded(function() {
12914    if (jQuery(".share-inline").length) {
12915        var share = new SHC.ui.InlineShare(".share-inline");
12916    }
12917});
12918
12919function initializeInlineShareClickEvents() {
12920  const socialIconsList = document.querySelectorAll('.newsroom-share .share-icons a, .share-inline.campaign-share a');
12921  if (socialIconsList) {
12922    socialIconsList.forEach(
12923      function (socialIconItem) {
12924        if(socialIconItem) {
12925          let shareText = socialIconItem.textContent;
12926          if(shareText) {
12927            socialIconItem.addEventListener("click", function () {
12928              stanford.analytics.send(stanford.analytics.createShareEvent(shareText, 'social media'));
12929            });
12930          }
12931        }
12932      }
12933    )
12934  }
12935}
12936
12937window.addEventListener('load', initializeInlineShareClickEvents);
12938shcDOMContentLoaded(function () {
12939    jQuery(".inline-video").each(function (index, item) {
12940        const $item = jQuery(item);
12941        if (!$item.attr("id")) {
12942            $item.attr("id", "inline-video-" + index);
12943        }
12944        const $container = $item.find('.inline-video-container');
12945        let videoId = '62jkZP_Vrwg';
12946        let presentationMode = false;
12947        let editmode = false;
12948        if ($container != null) {
12949            videoId = $container.data('video-id');
12950            presentationMode = $container.data('presentation-mode');
12951            editmode = $container.data('editmode');
12952        }
12953        if (presentationMode == false && editmode == false) {
12954            $item.YTPlayer({
12955                fitToBackground: false,
12956                videoId: videoId,
12957                mute: false,
12958                repeat: false,
12959                playerVars: {
12960                    autoplay: 0,
12961                    controls: 1,
12962                    modestbranding: 1,
12963                    rel: 0,
12964                    showinfo: 0
12965                }
12966            });
12967        }
12968    });
12969});
12970(function ($, $document) {
12971    "use strict";
12972
12973    $document.on("dialog-ready", function() {
12974        $("#shc-form-text-size .js-coral-NumberInput-decrementButton").remove();
12975        $("#shc-form-text-size .js-coral-NumberInput-incrementButton").remove();
12976        $("input[name='./cols']").parent().append('<label class="coral-Form-fieldlabel numberInput-fieldlabel">cols</label>');
12977        $("input[name='./rows']").parent().append('<label class="coral-Form-fieldlabel numberInput-fieldlabel">rows</label>');
12978    });
12979})($, $(document));
12980var formSubmitted = false;
12981var requiredEventAttached = false;
12982var emailEventAttached = false;
12983var nameEventAttached = false;
12984var phoneEventAttached = false;
12985function attachValidation(formElement) {
12986    var form = $(formElement),
12987        formInModal = ($('.shc-form').parents('#modal-content').length>0);
12988    // If a form was dynamically loaded inside modal,
12989    // use that instance specifically.
12990    if (formInModal) {
12991        form = $('#modal-content .shc_form_row').closest('form');
12992        var formFields = form.find('input, textarea, select');
12993        formFields.click(function() {
12994            if(!formStartBool){
12995                addToDataLayer('Form Start');
12996                formStartBool = true;
12997            }
12998        });
12999    }
13000
13001    var emailRegEx = /^[^@]+([@]{1})[0-9a-zA-Z\\._-]+([\\.]{1})[0-9a-zA-Z\\._-]+$/,
13002        nameRegEx = /^[a-zA-Z\s]+$/,
13003        phoneRegEx = /^(\+\d{1,2}\s)?\(?\d{3}\)?[\s.-]?\d{3}[\s.-]?\d{4}$/,
13004        requiredObjects = form.find('.required input, .required textarea, .required select'),
13005        emailConstrainedFields = form.find('.email-constraint'),
13006        nameConstrainedFields = form.find('.name-constraint'),
13007        phoneConstrainedFields = form.find('.phone-constraint'),
13008        inputFields = form.find('input,select'),
13009        constraintMsgSelector = '.form_row_description.constraint_message',
13010        requiredMsgSelector = '.form_row_description.required_message',
13011        submitButton = form.find(".form_button_submit");
13012
13013    function disableSubmit(){
13014        var enable = true;
13015
13016        //test required objects for info
13017        for (var i = 0; i < requiredObjects.length; i++) {
13018            var thing = $(requiredObjects[i]);
13019            if (window.getComputedStyle(requiredObjects[i]).display !== 'none') {
13020                enable = enable && validateRequired(thing);
13021            }
13022        }
13023
13024        //test formatting of text boxes
13025        var constrainedObjects = form.find('.email-constraint, .name-constraint, .phone-constraint');
13026        for (var i = 0; i < constrainedObjects.length; i++) {
13027            var obj = $(constrainedObjects[i]);
13028
13029            var value = obj.val();
13030
13031            if (obj.hasClass("name-constraint")) {
13032                if (value && !nameRegEx.test(value)) {
13033                    enable = false;
13034                }
13035            }
13036            else if (obj.hasClass("email-constraint")){
13037                if (value && !emailRegEx.test(value)) {
13038                    enable = false;
13039                }
13040            }
13041            else if (obj.hasClass("phone-constraint")){
13042                if (value && !phoneRegEx.test(value)) {
13043                    enable = false;
13044                }
13045            }
13046        }
13047
13048        if (enable){
13049            submitButton.removeAttr("disabled");
13050        }
13051        else{
13052            submitButton.attr("disabled", "true");
13053        }
13054    }
13055
13056    function validateRequired($target){
13057        var value = $target.val();
13058
13059        // Take care of radio fields.
13060        // Retrieve value by name attribute and :checked state.
13061        if ($target.attr("type")==="radio") {
13062            var radio_name = $target.attr("name");
13063            value = $("input[name="+radio_name+"]:checked").val();
13064        }
13065        if ($target.attr("type")==="checkbox") {
13066            var checkbox_name = $target.attr("name");
13067            value = null;
13068            $checkedBoxes = $("input[name="+checkbox_name+"]:checked");
13069            $checkedBoxes.each(function(e) {
13070                value += " " + $(this).val();
13071            });
13072        }
13073        if ($target.attr("type")==="dropdown"){
13074            var selected = $($target[0].selectedOptions);
13075            if (selected.hasClass("default-dropdown")){
13076                value = "";
13077            }
13078        }
13079        if (!value || !value.trim()){
13080            return false;
13081        }
13082        else{
13083            return true;
13084        }
13085    }
13086
13087    if(!requiredEventAttached) {
13088        requiredEventAttached = true;
13089        requiredObjects.each(function() {
13090            var obj = $(this);
13091            obj.on("blur", function(e) {
13092                var target = $(e.target),
13093                    section = target.closest(".section"),
13094                    constraintMessage = section.find(constraintMsgSelector),
13095                    requiredMessage = section.find(requiredMsgSelector),
13096                    valid = validateRequired(target);
13097
13098                if (!valid) {
13099                    target.addClass('error');
13100                    constraintMessage.addClass('hidden');
13101                    requiredMessage.removeClass('hidden');
13102                    var errorMessage = $(target).attr('name') + ':' + requiredMessage.text().trim();
13103                    addToDataLayer('Form Error', null, errorMessage);
13104                } else {
13105                    target.removeClass('error');
13106                    requiredMessage.addClass('hidden');
13107                }
13108            });
13109        });
13110    }
13111
13112    requiredObjects.each(function() {
13113        var obj = $(this);
13114        if(obj.is('textarea')){
13115            obj.on('keyup', function(e) {
13116                var target = $(this);
13117                var textValue = target.val();
13118                var section = target.closest(".section");
13119                var constraintMessage = section.find(constraintMsgSelector);
13120
13121                if(textValue && textValue.trim() !== ''){
13122                    disableSubmit();
13123                    target.removeClass('error');
13124                    constraintMessage.addClass('hidden');
13125                }else{
13126                    submitButton.attr("disabled", "true");
13127                    target.addClass('error');
13128                    constraintMessage.removeClass('hidden');
13129                    var errorMessage = $(target).attr('name') + ':' + constraintMessage.text().trim();
13130                    addToDataLayer('Form Error', null, errorMessage);
13131                }
13132            });
13133        }
13134    });
13135
13136    form.addClass('shc-form');
13137    var formError = $('.form_error');
13138    formError.prev('.form_leftcol').remove();
13139
13140    if (!emailEventAttached) {
13141        emailEventAttached = true;
13142        emailConstrainedFields.each(function () {
13143            $(this).blur(function () {
13144                var target = $(this),
13145                    email = target.val(),
13146                    section = target.closest(".section"),
13147                    constraintMessage = section.find(constraintMsgSelector),
13148                    required = (section.find(".required").length > 0);
13149
13150                if (!email && required) {
13151                    constraintMessage.addClass('hidden');
13152                } else if (email && !emailRegEx.test(email)) {
13153                    target.addClass('error');
13154                    constraintMessage.removeClass('hidden');
13155                    var errorMessage = $(target).attr('name') + ':' + constraintMessage.text().trim();
13156                    addToDataLayer('Form Error', null, errorMessage);
13157                } else {
13158                    target.removeClass('error');
13159                    constraintMessage.addClass('hidden');
13160                }
13161            });
13162        });
13163    }
13164
13165
13166    if (!nameEventAttached) {
13167        nameEventAttached = true;
13168        nameConstrainedFields.each(function () {
13169            $(this).blur(function () {
13170                var target = $(this),
13171                    name = target.val(),
13172                    section = target.closest(".section"),
13173                    constraintMessage = section.find(constraintMsgSelector),
13174                    required = (section.find(".required").length > 0);
13175
13176                if (!name && required) {
13177                    constraintMessage.addClass('hidden');
13178                } else if (name && !nameRegEx.test(name)) {
13179                    target.addClass('error');
13180                    constraintMessage.removeClass('hidden');
13181                    var errorMessage = $(target).attr('name') + ':' + constraintMessage.text().trim();
13182                    addToDataLayer('Form Error', null, errorMessage);
13183
13184                } else {
13185                    target.removeClass('error');
13186                    constraintMessage.addClass('hidden');
13187                }
13188            });
13189        });
13190    }
13191
13192    if (!phoneEventAttached) {
13193        phoneEventAttached = true;
13194        phoneConstrainedFields.each(function () {
13195            $(this).blur(function () {
13196                var target = $(this),
13197                    phoneNumber = target.val(),
13198                    section = target.closest(".section"),
13199                    constraintMessage = section.find(constraintMsgSelector),
13200                    required = (section.find(".required").length > 0);
13201
13202                if (!phoneNumber && required) {
13203                    constraintMessage.addClass('hidden');
13204                } else if (phoneNumber && !phoneRegEx.test(phoneNumber)) {
13205                    target.addClass('error');
13206                    constraintMessage.removeClass('hidden');
13207                    var errorMessage = $(target).attr('name') + ':' + constraintMessage.text().trim();
13208                    addToDataLayer('Form Error', null, errorMessage);
13209                } else {
13210                    target.removeClass('error');
13211                    constraintMessage.addClass('hidden');
13212                }
13213            });
13214        });
13215    }
13216
13217    /**
13218     * Show/Hide functionality based on radio button and
13219     * pulldown menu values. Look for DIVs with class="fs"
13220     * and read data-show-when and data-hide-when attributes.
13221     *
13222     * Allow for multiple value triggers. For example:
13223     * "field1=value1,field1=value2,field2=somevalue.
13224     *
13225     */
13226    var sections = [], // formsections
13227        parseTriggers = function(str) {
13228            if (!str) return [];
13229            var triggers = str.split(",");
13230            for (var i=0,n=triggers.length; i<n; i++) {
13231                if (triggers[i]) {
13232                    triggers[i] = triggers[i].replace(new RegExp('\\\s+', 'g'), "").trim();
13233                }
13234            }
13235            return triggers;
13236        },
13237        parseSections = function() {
13238            var fs = form.find(".fs");
13239            fs.each(function(idx, el){
13240                var obj = jQuery(this),
13241                    showAttr = obj.attr("data-show-when"),
13242                    hideAttr = obj.attr("data-hide-when");
13243                obj.data("showTriggers", parseTriggers(showAttr));
13244                obj.data("hideTriggers", parseTriggers(hideAttr));
13245                if (!obj.hasClass("edit-mode")) {
13246                    obj.hide();
13247                }
13248                sections.push(obj);
13249            });
13250        },
13251        resetHiddenFormSections = function() {
13252            inputFields.each(function(){
13253                var field = $(this);
13254                var formsection = field.closest(".fs");
13255                if (formsection.length>0 && !formsection.is(":visible")) {
13256                    // clear error styles and messages
13257                    field.removeClass("error");
13258                    formsection.find(constraintMsgSelector).addClass("hidden");
13259                    formsection.find(requiredMsgSelector).addClass("hidden");
13260                    // uncheck radio buttons and clear text fields
13261                    if (field.attr("type")==="checkbox"||field.attr("type")==="radio") {
13262                        field.prop("checked", false);
13263                    } else if (field.attr("type")==="text") {
13264                        field.val("");
13265                    }
13266                }
13267            });
13268        };
13269
13270    parseSections();
13271
13272    if (requiredObjects.length + nameConstrainedFields.length + phoneConstrainedFields.length + emailConstrainedFields.length > 0) {
13273        disableSubmit();
13274    }
13275
13276    inputFields.each(function(){
13277        jQuery(this).on("change input",function(e){
13278            var obj = jQuery(e.target),
13279                name = e.target.name,
13280                val = obj.val(),
13281                val = val.replace(new RegExp('\\\s+', 'g'), ""),
13282                trigger = name+"="+val;
13283
13284            if (obj.attr("type")==="checkbox") {
13285                var checked = ":unchecked";
13286                if (obj.is(":checked")) {
13287                    checked = ":checked";
13288                }
13289                trigger = trigger+checked;
13290            }
13291
13292            for (var i=0,n=sections.length; i<n; i++) {
13293                var section = sections[i],
13294                    showTriggers = section.data("showTriggers"),
13295                    hideTriggers = section.data("hideTriggers");
13296                if (showTriggers.indexOf(trigger)>-1) {
13297                    section.show();
13298                }
13299                if (hideTriggers.indexOf(trigger)>-1) {
13300                    section.hide();
13301                }
13302            }
13303            //
13304            resetHiddenFormSections();
13305            disableSubmit();
13306        });
13307    });
13308
13309    //need the form to fully reset before trying to disable Submit button.
13310    form.one('click', 'input[type="reset"]', function(e){
13311        e.preventDefault();
13312        $(this).closest('form').get(0).reset();
13313        disableSubmit();
13314    });
13315
13316    form.one('submit', function(e) {
13317        var valid = true,
13318            ecardSelectedURL = $("input[name=\\:ecardSelectedURL]").val(),
13319            ecardSelectedURL = ecardSelectedURL ? ecardSelectedURL : '',
13320            defaultValidator = function() {
13321                var fieldValidated = $(this);
13322                fieldValidated.blur();
13323
13324                // If a field is contained within
13325                // a formsection container,
13326                // validation should only fire when
13327                // it is visible.
13328                var formsection = fieldValidated.closest(".fs");
13329                if (formsection.length>0 && !formsection.is(":visible")) {
13330                    return;
13331                }
13332
13333                if (fieldValidated.hasClass('error')) {
13334                    valid = false;
13335                }
13336            };
13337
13338        // clean up values for hidden Form Sections.
13339        resetHiddenFormSections();
13340
13341        requiredObjects.each(defaultValidator);
13342        emailConstrainedFields.each(defaultValidator);
13343        nameConstrainedFields.each(defaultValidator);
13344        phoneConstrainedFields.each(defaultValidator);
13345
13346        if (valid && !formSubmitted) {
13347          addToDataLayer('Form Submit', ecardSelectedURL);
13348          formSubmitted = true;
13349        }
13350        return valid;
13351    })
13352    .on("reset",function(){
13353        sections = [];
13354        resetHiddenFormSections();
13355        parseSections();
13356    });
13357}
13358
13359$(window).on("debouncedresize load", function () {
13360    // load recaptcha
13361    if($('.form_button_submit.g-recaptcha').length > 0) {
13362        $.getScript("https://www.google.com/recaptcha/enterprise.js?render=6Le3JkAtAAAAAGJJ78Y9PgYBYEJReLxwtoVTUse9");
13363        $('.form_button_submit.g-recaptcha').each((index, element) => {
13364            attachValidation(element.closest('form'));
13365        });
13366        onResizeHandler();
13367        removeCQStyling();
13368    }
13369});
13370
13371$(window).on("resizeEnd", function () {
13372    onResizeHandler();
13373    removeCQStyling();
13374});
13375
13376shcDOMContentLoaded(function(){
13377    if (sessionStorage.getItem("cid")) {
13378        $('<input>').attr({
13379            type: 'hidden',
13380            id: 'cid',
13381            name: 'cid',
13382            value: sessionStorage.getItem("cid")
13383        }).appendTo('form.shc-form');
13384    }
13385    // invoke form plugin
13386    $('form.shc-form').preventDoubleSubmission();
13387});
13388
13389function onResizeHandler() {
13390    $('form').removeClass("large medium small");
13391    $('form').addClass(SHC.ui.screenMode);
13392}
13393
13394/* Brute force to remove CQ styling */
13395function removeCQStyling() {
13396    var small_screen_handler = $('.small').find('.text').find('.form_rightcol.form_error');
13397    var medium_screen_handler = $('.medium').find('.text').find('.form_rightcol.form_error');
13398    if (small_screen_handler) {
13399        $(small_screen_handler).closest('.form_row').find('.form_leftcollabel').css("display", "none");
13400    }
13401    if (medium_screen_handler) {
13402        $(medium_screen_handler).closest('.form_row').find('.form_leftcollabel').css("display", "none");
13403    }
13404}
13405
13406
13407var formStartBool = false;
13408shcDOMContentLoaded(function() {
13409    var form = $('.shc-form');
13410    var formFields = form.find('input, textarea, select');
13411    formFields.click(function() {
13412        if(!formStartBool){
13413            addToDataLayer('Form Start');
13414            formStartBool = true;
13415          }
13416    });
13417});
13418
13419function onSubmit(){
13420    $('.shc-form').find('input.form_button_submit').each((i, el) => {
13421        const disabled = el.getAttribute('disabled');
13422        if (!disabled) {
13423            $(el.closest('form')).submit();
13424            return false;
13425        }
13426    });
13427}
13428
13429function addToDataLayer(eventType, ecardDesignURL, formErrors) {
13430    var url = window.location.pathname;
13431    url = url.substring(0, url.indexOf('.html'));
13432    url = url.substring(1);
13433    var searchTxt = '/';
13434    var regex = new RegExp(searchTxt, 'g');
13435    url = url.replace(regex, "-");
13436    var component = {
13437        info: {
13438            name: url  // String, friendly form name
13439        },
13440        category: {
13441            primary: "form" // String, static value to indicate a form component
13442        }
13443    };
13444    var objective = $("input[name=category]").val();
13445    if (objective !== '' && component.attributes === undefined) {
13446        component.attributes = {
13447            objective: objective
13448        };
13449    } else if (objective !== '' && component.attributes.objective === undefined) {
13450        component.attributes.objective = objective;
13451    }
13452    if (ecardDesignURL || formErrors) {
13453        if (ecardDesignURL) {
13454            component['attributes'] = {selectedDesign: ecardDesignURL};
13455        }
13456        if (formErrors) {
13457            component['info']['error'] = {error: formErrors};
13458        }
13459    }
13460    stanford.analytics.send(stanford.analytics.createFormEvent(eventType, component));
13461}
13462(function ($, $document) {
13463    "use strict";
13464
13465
13466    // NOTE: The majority of this code is based on the following:
13467    // -http://experience-aem.blogspot.com/2015/04/aem-6-sp2-sample-datasource-touch-ui-select-listener.html
13468    // -http://experience-aem.blogspot.com/2015/02/aem-6-sp2-touch-ui-sample-dialog-ready-event-listener.html
13469    $document.on("dialog-ready", function () {
13470        var mail_value = "foundation/components/form/actions/mail",
13471            shc_mail_value = "shc/components/form/actions/shcmail",
13472            shc_formdata_value = "shc/components/form/actions/data_capture",
13473            contact_us_value = "shc/components/form/actions/contact_us_routing",
13474            ecard_value = "shc/components/form/actions/ecard",
13475            mail_id = "#form-start-mail",
13476            shc_mail_id = "#form-start-shc-mail",
13477            shc_formdata_id = "#form-start-shc-formdata",
13478            contact_us_id = "#form-start-contact-us",
13479            ecard_id = "#form-start-shc-ecard",
13480            action_type_id = "#form-start-actiontype";
13481
13482        function hideAll() {
13483            $(mail_id).hide();
13484            $(shc_mail_id).hide();
13485            $(shc_formdata_id).hide();
13486            $(contact_us_id).hide();
13487            $(ecard_id).hide();
13488            $(mail_id + " input[name='./subject']").attr("disabled", "disabled");
13489            $(shc_mail_id + " input[name='./subject']").attr("disabled", "disabled");
13490            $(contact_us_id + " input[name='./subject']").attr("disabled", "disabled");
13491            $("input[name='./mailto']").attr("disabled", "disabled");
13492        }
13493
13494        function showSection(id) {
13495            $(id + " input[name='./subject']").removeAttr("disabled", "disabled");
13496            $(id + " input[name='./mailto']").removeAttr("disabled", "disabled");
13497            $(id).show();
13498        }
13499
13500        function updateFieldsetDisplay(selectedValue) {
13501            hideAll();
13502            if (selectedValue === mail_value) {
13503                showSection(mail_id);
13504            } else if (selectedValue === shc_mail_value) {
13505                showSection(shc_mail_id);
13506            } else if (selectedValue === shc_formdata_value) {
13507                showSection(shc_formdata_id);
13508            } else if (selectedValue === contact_us_value) {
13509                showSection(contact_us_id);
13510            } else if (selectedValue === ecard_value) {
13511                $(ecard_id).show();
13512            }
13513        }
13514
13515        var action_type = new CUI.Select({
13516            element: $(action_type_id + " select").closest(".coral-Select")
13517        });
13518
13519        //workaround to remove the options getting added twice, using CUI.Select()
13520        $(action_type_id + " ul.coral-SelectList").children().each(function () {
13521            $(this).siblings("[data-value='" + $(this).attr("data-value") + "']").remove();
13522        });
13523
13524        action_type._selectList.on('selected.select', function (event) {
13525            updateFieldsetDisplay(event.selectedValue);
13526        });
13527        var currentSelection = $(action_type_id + " option:selected").val();
13528        if (!currentSelection) {
13529            currentSelection = mail_value;
13530        }
13531        updateFieldsetDisplay(currentSelection);
13532    });
13533})($, $(document));
13534shcDOMContentLoaded(function() {
13535    if (jQuery(".open-modal").length) {
13536        SHC.ui.modalInstance = new SHC.ui.Modal(".open-modal");
13537    }
13538});
13539
13540shcDOMContentLoaded(function() {
13541    if (jQuery(".event-collection").length) {
13542        var eventCollection = new SHC.ui.Event.Collection(".event-collection");
13543    }
13544});
13545jQuery(function() {
13546    if (jQuery(".event-course-catalog").length) {
13547        var eventCatalog = new SHC.ui.Event.Catalog(".event-course-catalog");
13548    }
13549});
13550shcDOMContentLoaded(function () {
13551    if (jQuery(".event-carousel").length) {
13552        var eventCarousel = new SHC.ui.EventCarousel(".event-carousel");
13553    }
13554});
13555shcDOMContentLoaded(function() {
13556    if(jQuery.trim(SHC.util.msieVersion()) === 9) {
13557        jQuery('#tab-nav').addClass('IE9');
13558        jQuery('#tab-nav-mobile').addClass('IE9');
13559    }
13560});
13561shcDOMContentLoaded(function() {
13562    if(jQuery("#tab-nav-with-quicknav").length>0) {
13563        var tabNav = new SHC.ui.TabNav('#tab-nav-with-quicknav');
13564    }
13565});
13566
13567shcDOMContentLoaded(function () {
13568    if (jQuery("#tab-nav-no-quicknav").length>0) {
13569        var genericTabNavTabNav = new SHC.ui.GenericTabNavTabNav('#tab-nav-no-quicknav');
13570    }
13571});
13572
13573shcDOMContentLoaded(function() {
13574    var newEmergencyAlert = new SHC.ui.NewEmergencyAlert();
13575});
13576shcDOMContentLoaded(function() {
13577    var ExternalOutageAlert = new SHC.ui.ExternalOutageAlert();
13578});
13579shcDOMContentLoaded(function () {
13580  if ($('.ecard-preview').length) {
13581    $('#modal').addClass('ecard');
13582    var modalContent = $('#modal-content');
13583    $('.preview .ecard-preview a').click(function () {
13584      var formData = $('form').serializeArray();
13585      var formObj = {};
13586      for (var i = 0; i < formData.length; i++) {
13587        formObj[formData[i].name] = formData[i].value;
13588      }
13589
13590      formObj.msgTitle =
13591        formObj.msgTitle === 'Select Option' ? ' ' : formObj.msgTitle;
13592
13593      var previewHTML = function (ecardFormData) {
13594        return (
13595          '<div class="ecard-container"><div class="image-wrapper"><img src="' +
13596          ecardFormData.imgSrc +
13597          '" alt="template image"></div><br><br><div class="ecard-body"><h1>' +
13598          ecardFormData.msgTitle +
13599          '</h1><p>Dear ' +
13600          ecardFormData.ptFirst +
13601          ' ' +
13602          ecardFormData.ptLast +
13603          ',</p><p class="msg-body">' +
13604          ecardFormData.msgBody +
13605          '</p><br><p>' +
13606          ecardFormData.firstName +
13607          ' ' +
13608          ecardFormData.lastName +
13609          '<br>' +
13610          ecardFormData.email +
13611          '</p></div><div class="footer-logo"><img src="/etc/clientlibs/shc/main/svg/shc-logo-combo.svg" alt="footer logo"></div></div>'
13612        );
13613      };
13614      modalContent.empty();
13615      modalContent.append(previewHTML(formObj));
13616      $('#modal-container').addClass('show');
13617    });
13618    $('.ecard .close-modal a').click(function () {
13619      $('#modal-container').removeClass('show');
13620    });
13621  }
13622});
13623
13624shcDOMContentLoaded(function () {
13625    // jQuery(".inline-video").each(function(index, item) {
13626    //     var inlineVideo = new SHC.ui.InlineVideo(item);
13627    // });
13628});
13629shcDOMContentLoaded(function () {
13630  var msgBodyElement = $('.form_field[name="msgBody"]');
13631  var msgBodyMaxCharacterLimit = 900;
13632  var alertMessage = "Maximum allowed character limit reached.";
13633  if (msgBodyElement.length) {
13634    var infoLabel = '<span class="msg-body-info-label">0/' + msgBodyMaxCharacterLimit + '</span><span class="msg-body-alert-message"></span>';
13635    msgBodyElement.closest('.form_row').find('.form_rightcol').append(infoLabel);
13636    msgBodyElement.on('input propertychange', function (event) {
13637      var inputValue = $(event.target).val();
13638      var charCount = inputValue.length;
13639      if (charCount < msgBodyMaxCharacterLimit) {
13640        $('.msg-body-info-label').text(charCount + "/" + msgBodyMaxCharacterLimit);
13641        $('.msg-body-alert-message').text('');
13642      } else {
13643        msgBodyElement.val(inputValue.substr(0, msgBodyMaxCharacterLimit));
13644        $('.msg-body-info-label').text(msgBodyMaxCharacterLimit + "/" + msgBodyMaxCharacterLimit);
13645        $('.msg-body-alert-message').text(alertMessage);
13646      }
13647    })
13648  }
13649});
13650(function ($, $document) {
13651	"use strict";
13652	$document.ready(function() {
13653		const debounce = (func, wait, immediate) => {
13654			var timeout;
13655			return () => {
13656				const context = this, args = arguments;
13657				const later = function() {
13658					timeout = null;
13659					if (!immediate) func.apply(context, args);
13660				};
13661				const callNow = immediate && !timeout;
13662				clearTimeout(timeout);
13663				timeout = setTimeout(later, wait);
13664				if (callNow) func.apply(context, args);
13665			};
13666		};
13667		
13668		function updateAriaHiddenForSR() {
13669			var $dynamicContainers = $(".parbase.dynamic_container .dynamic-container-parsys"),
13670				$mobileContainers = $dynamicContainers.filter(".mobile-size-container"),
13671				$tabletContainers = $dynamicContainers.filter(".tablet-size-container"),
13672				$desktopContainers = $dynamicContainers.filter(".desktop-size-container");
13673			var curWidth = window.innerWidth;
13674			
13675			//containers with none of the 3 sizes (mobile-size-container, tablet-size-container, desktop-size-container) should never be hidden
13676			$dynamicContainers.removeAttr("aria-hidden");
13677			if (curWidth < 768) {
13678				//mobile size
13679				$tabletContainers.attr("aria-hidden", "true");
13680				$desktopContainers.attr("aria-hidden", "true");
13681				$mobileContainers.attr("aria-hidden", "false");
13682			} else if (curWidth < 1024) {
13683				//tablet size
13684				$mobileContainers.attr("aria-hidden", "true");
13685				$desktopContainers.attr("aria-hidden", "true");
13686				$tabletContainers.attr("aria-hidden", "false");
13687			} else {
13688				//desktop size
13689				$mobileContainers.attr("aria-hidden", "true");
13690				$tabletContainers.attr("aria-hidden", "true");
13691				$desktopContainers.attr("aria-hidden", "false");
13692			}
13693		}
13694		
13695		window.addEventListener('resize', debounce(updateAriaHiddenForSR, 200, false), false);
13696		window.addEventListener('orientationchange', debounce(updateAriaHiddenForSR, 200, false), false);
13697		updateAriaHiddenForSR();
13698	});
13699})($, $(document));
13700shcDOMContentLoaded(function() {
13701    if(jQuery(".doctor-story-tile-wrapper").length) {
13702        var drStory = new SHC.ui.DrStory();
13703    }
13704});
13705
13706
13707
13708jQuery(function() {
13709    if ($('.download-asset').length){
13710        initializeDownloadAssetButton();
13711        $.getScript("https://www.google.com/recaptcha/enterprise.js?render=6Le3JkAtAAAAAGJJ78Y9PgYBYEJReLxwtoVTUse9");
13712    }
13713});
13714
13715window.initializeDownloadAssetButton = function () {
13716    var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
13717    var $formtextfield = $('.download-asset .form-text');
13718    var testbutton = function () {
13719        var email = $(this).closest('.download-asset').find('.form-text').val();
13720        if (re.test(email)){
13721            $(this).closest('.download-asset').find('.download-btn').prop('disabled', false);
13722        }else {
13723            $(this).closest('.download-asset').find('.download-btn').prop('disabled', true);
13724        }
13725    };
13726    var download = function($component){
13727        grecaptcha.enterprise.ready(function() {
13728            grecaptcha.enterprise.execute('6Le3JkAtAAAAAGJJ78Y9PgYBYEJReLxwtoVTUse9', {action: 'submit'}).then(function(token) {
13729                // Add the reCAPTCHA token to the form data
13730                $component.find('form').append('<input type="hidden" name="g-recaptcha-response" value="' + token + '">');
13731                // Now serialize the form data
13732                var data = $component.find('form').serialize();
13733                $component.find('.download-popover').hide();
13734                $component.find('.thankyou-popover').show();
13735                $.ajax({
13736                    dataType: "text",
13737                    url: '/bin/api/v1/content/form-email',
13738                    type: 'post',
13739                    data: data,
13740                    success: function (data) {
13741                        var a = $('<a>')
13742                            .attr('href', data)
13743                            .attr('download','')
13744                            .attr('target', '_blank')
13745                            .appendTo('body');
13746                        a[0].click();
13747                        a.remove();
13748                    }
13749                });
13750            })
13751        })
13752    };
13753    $('.download-asset .start-download').on('click', function () {
13754        $(this).closest('.download-asset').find('.popover-content').toggle();
13755    });
13756    $('.download-asset .closeX').on('click', function(){
13757        $(this).closest('.download-asset').find('.popover-content').hide();
13758
13759        $('.download-asset .thankyou-popover').hide();
13760        $('.download-asset .download-popover').show();
13761    });
13762    $formtextfield.blur(function(){
13763        var email = $(this).closest('.download-asset').find('.form-text').val();
13764        if (re.test(email)){
13765            $('.download-asset .email-error').hide();
13766            $(this).closest('.download-asset').find('.form-text').removeClass('error');
13767        } else{
13768            $('.download-asset .email-error').show();
13769            $(this).closest('.download-asset').find('.form-text').addClass('error');
13770
13771        }
13772        testbutton();
13773    });
13774    $formtextfield.on('input', testbutton);
13775    $formtextfield.keydown(function(e){
13776        if (e.keyCode == 13){
13777            testbutton();
13778            if ($(this).siblings("[type='submit']").attr('disabled')){
13779                e.preventDefault();
13780            } else{
13781                e.preventDefault();
13782                var $component = $(this).closest('.download-asset');
13783                download($component);
13784            }
13785        }
13786    });
13787    $('.download-asset .download-btn').on('click', function(e){
13788        e.preventDefault();
13789        var $component = $(this).closest('.download-asset');
13790        download($component);
13791    });
13792}
13793$(document).ready(function() {
13794    var DISCLAIMER_BUTTON = '.disclaimer-button a';
13795    if (jQuery(DISCLAIMER_BUTTON).length) {
13796        var disclaimer = new SHC.ui.Disclaimer_Button(DISCLAIMER_BUTTON);
13797    }
13798});
13799$(document).ready(function () {
13800    $('.videoCarousel iframe[id^="frame"]').each(function () {
13801        var frameId = $(this).attr('id');
13802        setTimeout(() => {
13803            // beat race condition
13804            $(this).removeAttr('style');
13805        }, "3000");
13806        $('#' + frameId).YTPlayer({
13807            fitToBackground: false,
13808            mute: false,
13809            repeat: false,
13810            playerVars: {
13811                autoplay: 1,
13812                controls: 1,
13813                modestbranding: 1,
13814                rel: 0,
13815                showinfo: 0
13816            }
13817        });
13818    });
13819});
13820
13821$(window).resize(function () {
13822    $('.videoCarousel iframe[id^="frame"]').each(function () {
13823        var frameId = $(this).attr('id');
13824        setTimeout(() => {
13825            // beat race condition
13826            $(this).removeAttr('style');
13827        }, "3000");
13828        $('#' + frameId).YTPlayer({
13829            fitToBackground: false,
13830            mute: false,
13831            repeat: false,
13832            playerVars: {
13833                autoplay: 1,
13834                controls: 1,
13835                modestbranding: 1,
13836                rel: 0,
13837                showinfo: 0
13838            }
13839        });
13840    });
13841});
13842shcDOMContentLoaded(function () {
13843    if (jQuery(".isAward").length) {
13844        var awardsTile = new SHC.ui.AwardsTile(".isAward");
13845    }
13846});
13847shcDOMContentLoaded(function () {
13848    var tileTruncation = new  SHC.ui.TileTruncation();
13849});
13850shcDOMContentLoaded(function () {
13851    if (jQuery('.multi-location-tile').length) {
13852        var multiMapTile = new SHC.ui.MultiMapTile();
13853    }
13854});
13855shcDOMContentLoaded(function () {
13856    if($('.location-tile').length) {
13857        $('.location-tile').find('.tile-box-overlay-text.open-modal,  a.open-modal').on('click',function(){
13858            $('body').find('#main').addClass('no-print');
13859        });
13860    }
13861});
13862// [email protected]
13863jQuery(document).on('ready', function() {
13864    var titleDiv = jQuery('.shared-top-content-iparsys .shc-title');
13865    titleDiv.addClass("shc-title-bottom-margin");
13866});
13867function initializeSignInButtonClickEvent() {
13868	const signInForms = document.querySelectorAll('#my-health-login form, #my-health-login-component form');
13869	if(signInForms) {
13870		signInForms.forEach(function(curForm) {
13871			curForm.addEventListener("submit", function () {
13872				stanford.analytics.send(stanford.analytics.createComponentClickButton("sign In", "button", "myhealth log in"));
13873			});
13874		});
13875	}
13876}
13877window.addEventListener('DOMContentLoaded', initializeSignInButtonClickEvent);
13878shcDOMContentLoaded(function() {
13879    if(jQuery('#marquee').length > 0) {
13880        var marquee = new SHC.ui.Marquee("#marquee");
13881    }
13882});
13883
13884shcDOMContentLoaded(function() {
13885    if (jQuery(".info-blocks-container").length) {
13886        var infoblocksContainer = new SHC.ui.InfoblocksContainer(".info-blocks-container");
13887    }
13888});
13889
13890var debounce = function(fn) {
13891  // Setup a timer
13892  var timeout;
13893
13894  // Return a function to run debounced
13895  return function() {
13896    // Setup the arguments
13897    var context = this;
13898    var args = arguments;
13899
13900    // If there's a timer, cancel it
13901    if (timeout) {
13902      cancelAnimationFrame(timeout);
13903    }
13904
13905    // Setup the new requestAnimationFrame()
13906    timeout = requestAnimationFrame(function() {
13907      fn.apply(context, args);
13908    });
13909  };
13910};
13911
13912var isVisible = function(topViewPort, bottomViewPort, topParent, bottomParent) {
13913  var verticalOffset = 250;
13914  return topParent - verticalOffset < bottomViewPort && bottomParent + verticalOffset > topViewPort;
13915};
13916
13917var isNear = function(topViewPort, bottomViewPort, topParent, bottomParent) {
13918  var SCREEN_IMAGE_DISTANCE = 150;
13919  var topDiff = topParent - bottomViewPort;
13920  var bottomDiff = topViewPort - bottomParent;
13921  return (
13922    (topDiff < SCREEN_IMAGE_DISTANCE && topDiff > 0) ||
13923    (bottomDiff < SCREEN_IMAGE_DISTANCE && bottomDiff > 0)
13924  );
13925};
13926
13927var parallaxImage = function(
13928  image,
13929  rand,
13930  direction,
13931  imageRatio,
13932  mobileParallaxOff
13933) {
13934  var scrollNamespace = "scroll." + rand;
13935  var resizeNamespace = "resize." + rand;
13936
13937  var desktopImage = image.data("desktop");
13938  var mobileImage = image.data("mobile");
13939  var imageSource = image.attr("src");
13940
13941  var parent = image.parent();
13942  var childHeight = parseInt(image.css("height"));
13943  var parentHeight = Math.round(childHeight * imageRatio);
13944  var viewPortHeight = $(window).height();
13945  var offset = childHeight - parentHeight;
13946
13947  if (!mobileParallaxOff || SHC.ui.screenMode !== "small") {
13948    onScroll();
13949    loadParallaxImage(true);
13950
13951    //initialize the translation and listeners
13952    $(window).on(scrollNamespace, debounce(onScroll));
13953    $(window).on(resizeNamespace, debounce(onResize));
13954  }
13955
13956  function loadParallaxImage(checkViewport) {
13957    function modifySrc() {
13958      if (!image.attr('src')) {
13959        image.attr('src', image.attr('data-src'));
13960      }
13961      if (image.attr('src')) {
13962        onResize(true);
13963      }
13964    }
13965    if (checkViewport) {
13966      var topViewPort = $(window).scrollTop();
13967      var bottomViewPort = topViewPort + viewPortHeight;
13968      var topParent = parent.offset().top;
13969      var bottomParent = topParent + parentHeight;
13970  
13971      if (isVisible(topViewPort, bottomViewPort, topParent, bottomParent)) {
13972        modifySrc();
13973      } 
13974    } else {
13975      modifySrc();
13976    }
13977  }
13978
13979  function onScroll() {
13980    var topViewPort = $(window).scrollTop();
13981    var bottomViewPort = topViewPort + viewPortHeight;
13982    var topParent = parent.offset().top;
13983    var bottomParent = topParent + parentHeight;
13984
13985    if (isVisible(topViewPort, bottomViewPort, topParent, bottomParent)) {
13986      loadParallaxImage(false);
13987      var percentage;
13988
13989      if (direction === "up") {
13990        percentage =
13991          -(bottomViewPort - topParent) /
13992          ((viewPortHeight + parentHeight) / 100);
13993      } else {
13994        percentage =
13995          (topViewPort - bottomParent) /
13996          ((viewPortHeight + parentHeight) / 100);
13997      }
13998
13999      var translation = Math.round((percentage / 100) * offset);
14000
14001      image.css("transform", "translate3d(0px, " + translation + "px, 0px)");
14002    }
14003  }
14004
14005  function onResize(flag) {
14006    childHeight = parseInt(image.css("height"));
14007    parentHeight = Math.round(childHeight * imageRatio);
14008    parent.css("height", parentHeight + "px");
14009    viewPortHeight = $(window).height();
14010    offset = childHeight - parentHeight;
14011
14012    if (!flag) {
14013      onScroll();
14014    }
14015  }
14016
14017  if (desktopImage || mobileImage) {
14018    image
14019      .on("load", function() {
14020        onResize();
14021      });
14022  }
14023
14024  $(window).on(
14025    "resize",
14026    SHC.util.throttle(function() {
14027      SHC.ui.detectScreenMode();
14028      var currentImage = image.attr("src");
14029      if (SHC.ui.screenMode !== "small") {
14030        if (desktopImage && currentImage !== desktopImage) {
14031          image.attr("src", desktopImage);
14032        } else if (mobileImage && currentImage === mobileImage) {
14033          image.attr("src", imageSource);
14034        }
14035
14036        $(window).on(scrollNamespace, debounce(onScroll));
14037        $(window).on(resizeNamespace, debounce(onResize));
14038        onResize();
14039      } else {
14040        if (desktopImage && currentImage === desktopImage) {
14041          image.attr("src", imageSource);
14042        } else if (mobileImage && currentImage !== mobileImage) {
14043          image.attr("src", mobileImage);
14044        }
14045
14046        if (mobileParallaxOff) {
14047          $(window).off(scrollNamespace);
14048          $(window).off(resizeNamespace);
14049          parent.css("height", "");
14050          image.css("transform", "");
14051        }
14052      }
14053    }, 100)
14054  );
14055};
14056
14057var parallaxInset = function(
14058  image,
14059  rand,
14060  direction,
14061  speed,
14062  mobileParallaxOff,
14063  absoluteLeft
14064) {
14065  var SCALE_START_POINT = 1024;
14066
14067  var scrollNamespace = "scroll." + rand;
14068  var resizeNamespace = "resize." + rand;
14069
14070  var imageHeight = parseInt(image.css("height"));
14071  var viewPortHeight = $(window).height();
14072  var imageDiv = image.closest(".image-with-caption");
14073  var naturalWidth = image[0].naturalWidth;
14074  var maxWidth = (naturalWidth / SCALE_START_POINT) * $(window).width();
14075  maxWidth = maxWidth > naturalWidth ? naturalWidth : maxWidth;
14076
14077  imageDiv.css("max-width", maxWidth);
14078  $(window).on(resizeNamespace, debounce(onInsetResize));
14079
14080  if (!mobileParallaxOff || SHC.ui.screenMode !== "small") {
14081    //initialize the translation and listeners
14082    onInsetScroll();
14083    $(window).on(scrollNamespace, debounce(onInsetScroll));
14084  } else {
14085    imageDiv.css("position", "relative");
14086    image.css("transform", "");
14087    // move image to right side when position relative
14088    if (absoluteLeft === "") {
14089      imageDiv.css("margin-left", "auto");
14090      imageDiv.css("margin-right", "0");
14091    }
14092  }
14093
14094  function onInsetScroll() {
14095    var topViewPort = $(window).scrollTop();
14096    var bottomViewPort = topViewPort + viewPortHeight;
14097    var topImage = image.offset().top;
14098    var bottomImage = topImage + imageHeight;
14099
14100    if (
14101      isVisible(topViewPort, bottomViewPort, topImage, bottomImage) ||
14102      isNear(topViewPort, bottomViewPort, topImage, bottomImage)
14103    ) {
14104      var translation;
14105
14106      if (direction === "up") {
14107        translation =
14108          -(bottomViewPort - topImage) / ((viewPortHeight + imageHeight) / 100);
14109      } else {
14110        translation =
14111          (topViewPort - bottomImage) / ((viewPortHeight + imageHeight) / 100);
14112      }
14113
14114      image.css(
14115        "transform",
14116        "translate3d(0px, " + translation * speed + "px, 0px)"
14117      );
14118    }
14119  }
14120
14121  function onInsetResize() {
14122    imageHeight = parseInt(image.css("height"));
14123    viewPortHeight = $(window).height();
14124    maxWidth = (naturalWidth / SCALE_START_POINT) * $(window).width();
14125    maxWidth = maxWidth > naturalWidth ? naturalWidth : maxWidth;
14126    imageDiv.css("max-width", maxWidth);
14127
14128    if (!mobileParallaxOff || SHC.ui.screenMode !== "small") {
14129      onInsetScroll();
14130    }
14131  }
14132
14133  $(window).on(
14134    "resize",
14135    SHC.util.throttle(function() {
14136      SHC.ui.detectScreenMode();
14137      if (SHC.ui.screenMode !== "small") {
14138        imageDiv.css("position", "");
14139        $(window).on(scrollNamespace, debounce(onInsetScroll));
14140        onInsetResize();
14141      } else {
14142        if (mobileParallaxOff) {
14143          $(window).off(scrollNamespace);
14144          imageDiv.css("position", "relative");
14145          image.css("transform", "");
14146          // move image to right side when position relative
14147          if (absoluteLeft === "") {
14148            imageDiv.css("margin-left", "auto");
14149            imageDiv.css("margin-right", "0");
14150          }
14151        }
14152      }
14153    }, 100)
14154  );
14155};
14156
14157shcDOMContentLoaded(function() {
14158    var HEALTH_CALCULATOR = ".health_calculator";
14159    if($(HEALTH_CALCULATOR).length) {
14160        var display = new SHC.ui.Calculator(HEALTH_CALCULATOR); 
14161    }
14162});
14163
14164$(document).ready(function(){
14165    var isIE = SHC.util.isIE();
14166
14167    if(isIE =="8" || isIE =="9"){
14168        add_placeholder('username', 'IE Placeholder Text');
14169    }
14170    
14171    $('body').on('click', '#insurance-check', function(e) {
14172         $('.make-an-appt-link').toggleClass('disabled');
14173    });
14174});
14175
14176
14177shcDOMContentLoaded(function () {
14178    $('#main').on('click', '.button-container', function () {
14179        var block = $(this).siblings(),
14180            button = $(this).find('.view-more-show-hide-btn'),
14181            closedText = button.data( 'text' ),
14182            openText = button.data( 'open' ),
14183            parent = $(this).parent();
14184
14185        block.slideToggle('fast')
14186            .toggleClass('isOpen');
14187        parent.toggleClass('isOpen');
14188        button.toggleClass('isOpen');
14189
14190        if (!block.hasClass('isOpen')) {
14191            button.text(closedText);
14192        } else {
14193            button.text(openText);
14194        }
14195    });
14196    $(window).on('resizeEnd', function() {
14197        if(SHC.ui.screenMode === 'large') {
14198            if( $('.view-more-container').hasClass('showDesktop')) {
14199                $('.showDesktop > .view-more-block').removeAttr('style');
14200            }
14201        }
14202        if(SHC.ui.screenMode === 'medium'){
14203            if($('.view-more-container').hasClass('showTablet')) {
14204                $('.showTablet > .view-more-block').removeAttr('style');
14205            }
14206        }
14207        if(SHC.ui.screenMode === 'small') {
14208            if($('.view-more-container').hasClass('showMobile')) {
14209                $('.showMobile > .view-more-block').removeAttr('style');
14210            }
14211        }
14212    });
14213});
14214
14215shcDOMContentLoaded(function () {
14216    if ($('.treatment-box-container').length) {
14217        $('.treatment-box-container.bgwhite').each(function (e) {
14218            $(this).closest('.treatment_box_container').addClass('bgwhite');
14219        });
14220
14221        if (screen.width < 747) {
14222            if ($('.treatment-box-container .tab-nav-content').length > 1) {
14223                $('.first-tab').removeClass('active');
14224            } else {
14225                $('.treatment-box-container .double-caret').addClass('hidden');
14226                $('.treatment-box-container .only-tab').css('pointer-events', 'n
14226one');
14227                $('.treatment-box-container .only-tab').css('cursor', 'default');
14228            }
14229        }
14230
14231        SHC.util.clickAnchorTab();
14232
14233        SHC.util.clickInternalAnchorTab();
14234        var firstClick = false;
14235
14236        var doCloneContent = function (that) {
14237            var $that = $(that),
14238                newIndex = $that.data('tab-index'),
14239                content = $that.find(".tab-content"),
14240                container = $that.closest(".treatment-box-container"),
14241                mobile1 = container.find('.tab-area-1-mobile'),
14242                mobile2 = container.find('.tab-area-2-mobile'),
14243                mobile3 = container.find('.tab-area-3-mobile'),
14244                mobile4 = container.find('.tab-area-4-mobile'),
14245                desktopContainer = container.find('.tab-area-desktop');
14246            if (container.hasClass('not-editing')) {
14247                container.attr('data-tab-active', newIndex);
14248                $that.parent().find('.tab-nav-content.active').removeClass('active');
14249                $that.addClass('active');
14250                mobile1.empty();
14251                mobile2.empty();
14252                mobile3.empty();
14253                mobile4.empty();
14254
14255                if (container.hasClass("mobile-tab")) {
14256                    if (newIndex == 0) {
14257                        content.clone().appendTo(mobile1);
14258                        if (container.hasClass("mobile-second")) {
14259                            container.removeClass("mobile-second");
14260                        } else if (container.hasClass("mobile-third")) {
14261                            container.removeClass("mobile-third");
14262                        } else if (container.hasClass("mobile-fourth")) {
14263                            container.removeClass("mobile-fourth");
14264                        }
14265                        container.addClass("mobile-first");
14266
14267                    } else if (newIndex == 1) {
14268                        content.clone().appendTo(mobile2);
14269                        if (container.hasClass("mobile-first")) {
14270                            container.removeClass("mobile-first");
14271                        } else if (container.hasClass("mobile-third")) {
14272                            container.removeClass("mobile-third");
14273                        } else if (container.hasClass("mobile-fourth")) {
14274                            container.removeClass("mobile-fourth");
14275                        }
14276                        container.addClass("mobile-second");
14277
14278                    } else if (newIndex == 2) {
14279                        content.clone().appendTo(mobile3);
14280                        if (container.hasClass("mobile-first")) {
14281                            container.removeClass("mobile-first");
14282                        } else if (container.hasClass("mobile-second")) {
14283                            container.removeClass("mobile-second");
14284                        } else if (container.hasClass("mobile-fourth")) {
14285                            container.removeClass("mobile-fourth");
14286                        }
14287                        container.addClass("mobile-third");
14288
14289                    } else {
14290                        content.clone().appendTo(mobile4);
14291                        if (container.hasClass("mobile-first")) {
14292                            container.removeClass("mobile-first");
14293                        } else if (container.hasClass("mobile-second")) {
14294                            container.removeClass("mobile-second");
14295                        } else if (container.hasClass("mobile-third")) {
14296                            container.removeClass("mobile-third");
14297                        }
14298                        container.addClass("mobile-fourth");
14299                    }
14300                } else {
14301                    if (newIndex == 0 || newIndex == 1) {
14302                        content.clone().appendTo(mobile2);
14303                        if (container.hasClass("mobile-first")) {
14304                            container.removeClass("mobile-first");
14305                        } else if (container.hasClass("mobile-third")) {
14306                            container.removeClass("mobile-third");
14307                        } else if (container.hasClass("mobile-fourth")) {
14308                            container.removeClass("mobile-fourth");
14309                        }
14310                        container.addClass("mobile-second");
14311                    } else {
14312                        content.clone().appendTo(mobile4);
14313                        if (container.hasClass("mobile-first")) {
14314                            container.removeClass("mobile-first");
14315                        } else if (container.hasClass("mobile-second")) {
14316                            container.removeClass("mobile-second");
14317                        } else if (container.hasClass("mobile-third")) {
14318                            container.removeClass("mobile-third");
14319                        }
14320                        container.addClass("mobile-fourth");
14321
14322                    }
14323                }
14324                if (firstClick && SHC.ui.screenMode === "small") {
14325                    var alertMessage = $('#new-emergency-alert');
14326                    var messageOffset = alertMessage.length > 0 ? alertMessage.height() : 0;
14327                    $('html, body').animate({
14328                        scrollTop: $that.offset().top - messageOffset
14329                    }, 500);
14330                }
14331
14332                desktopContainer.empty();
14333                content.clone().appendTo(desktopContainer);
14334
14335                if (content.find('.searchbar-container').length > 0) {
14336                    var event = jQuery.Event('searchbarInTreatmentBox');
14337                    event.desktopContainer = desktopContainer;
14338                    event.mobile1 = mobile1;
14339                    event.mobile2 = mobile2;
14340                    event.mobile3 = mobile3;
14341                    event.mobile4 = mobile4;
14342                    jQuery(window).trigger(event);
14343                }
14344            }
14345        }
14346
14347        $('.not-editing.treatment-box-container .tab-nav-content').on('click', function (event) {//For switching tabs.
14348            var $this = $(this),
14349                target = event.target,
14350                desktop = $this.closest('.treatment-box-container').find('.tab-area-desktop');
14351            if ($(target).closest('.clone-content').length == 0) {//We are checking this to see if the 'click' came from the hidden clone-content node. Don't do following if happened.
14352                desktop.css('display', '');//this will take away the display:none from load.
14353                firstClick = true;
14354                if (!$this.hasClass("active")) {
14355                    doCloneContent(this);
14356                    var tabModalLinks = $this.closest('.treatment-box-container').find('.tab-area-desktop .open-modal, .mobile-tab-details-container .open-modal');
14357                    new SHC.ui.Modal(tabModalLinks);
14358                } else {
14359                    $this.removeClass("active");
14360                    desktop.css('display', 'none');
14361                    var container = $this.closest('.treatment-box-container');
14362                    container.removeClass("mobile-first").removeClass("mobile-second").removeClass("mobile-third").removeClass("mobile-fourth");
14363                }
14364            }
14365            if ($('.ease-of-access').size() > 0) {
14366                new SHC.ui.EaseOfAccess();
14367            }
14368        });
14369
14370        $('.tab-nav-content.active').each(function () {
14371            doCloneContent(this);
14372        });
14373
14374        new SHC.ui.Modal('.treatment-box-container .tab-content .open-modal');
14375    }
14376});
14377
14378shcDOMContentLoaded(function() {
14379  if ($('.process-circles-container').length) {
14380    if (SHC.ui.screenMode === "small") {
14381      $('.process-circles-list li').attr('data-nav-show', 'false');
14382      $('.process-tabs-container-item').attr('data-nav-show', 'false');
14383
14384      $(':not(.mobile-tab).circle_title').each(function() {
14385        var self = jQuery(this);
14386        var appended = self.attr('id') + '-inactive';
14387        self.attr('id', appended);
14388      });
14389
14390      $('.circle_title.mobile-tab').each(function() {
14391        var self = jQuery(this);
14392        var newId = self.attr('id').split('-mobile')[0];
14393        self.attr('id', newId);
14394      });
14395
14396    } else {
14397      $('.mobile-tab.circles').attr('data-nav-show', 'false');
14398      $('.mobile-tab.tabs').attr('data-nav-show', 'false');
14399
14400      $('.process-tabs-container-item').each(function() {
14401        var self = $(this);
14402        if (self.attr('id').indexOf('not-used') > -1) {
14403          var newId = self.attr('id').split('-not-used')[0];
14404          self.attr('id', newId);
14405        }
14406      });
14407    }
14408
14409    SHC.util.clickAnchorTab();
14410
14411    SHC.util.clickInternalAnchorTab();
14412
14413    if ($('div.process-circles-container').length > 0){
14414      var processCircles = new SHC.ui.ProcessCircles('.process-circles-container');
14415    }
14416
14417    // TAB Jquery
14418    var getTabNum = function($tabelem) {
14419      var tabData = jQuery($tabelem).attr('data-attr-tab');
14420      var tabNum = tabData.replace('circle_','');
14421      return tabNum;
14422    };
14423
14424    var setActiveTab = function($tabelem) {
14425      var outerContainer = jQuery($tabelem).closest('.process-circles-container');
14426      var newTab = $($tabelem).attr('data-attr-tab');
14427      jQuery(outerContainer).find('.process-tabs-container h3').each(function() {
14428        jQuery(this).removeClass('active');
14429      });
14430      jQuery(outerContainer).find('.tabs-content-container h3').each(function() {
14431        jQuery(this).removeClass('active');
14432      });
14433      jQuery(outerContainer).find('.tabs-content-container .arrow').removeClass('active');
14434      jQuery(outerContainer).find('.tabs-content-bottom').removeClass('active');
14435      jQuery(outerContainer).find('.tabs-content').each(function() {
14436        jQuery(this).hide();
14437      });
14438
14439      jQuery(outerContainer).find('.'+newTab).show();
14440      $tabelem.addClass('active');
14441      jQuery(outerContainer).find('.'+newTab).parent().find('.arrow').addClass('active');
14442      jQuery(outerContainer).find('.'+newTab).parent().find('.tabs-content-bottom').addClass('active');
14443
14444      //content panel
14445      jQuery(outerContainer).find('.tabs-content-container .tab-content').each(function() {
14446        jQuery(this).removeClass('active');
14447      });
14448
14449      jQuery(outerContainer).find('.tabs-content-container .tab-content.tab_' + getTabNum($tabelem)).addClass('active');
14450
14451      quickNavTextWriter($tabelem);
14452    };
14453
14454    //desktop tabs
14455    jQuery('.process-tabs-container').on('click', 'h3.process-tabs-container-item', function() {
14456      setActiveTab(jQuery(this));
14457    });
14458
14459    jQuery('.process-circles-container').on('click', '.pc-quick-nav-next', function(e) {
14460      e.preventDefault();
14461      quickNavClickHandler(this, true);
14462    });
14463    jQuery('.process-circles-container').on('click', '.pc-quick-nav-prev', function(e) {
14464      e.preventDefault();
14465      quickNavClickHandler(this, false);
14466    });
14467
14468    var quickNavClickHandler = function(element, isNext) {
14469      var $this = $(element),
14470        $pcContainer = $this.closest('.process_circles'),
14471        $activeTab = $pcContainer.find('.active');
14472      if (isNext) {
14473        $activeTab.next().trigger('click');
14474      } else {
14475        $activeTab.prev().trigger('click');
14476      }
14477      $pcContainer[0].scrollIntoView();
14478      window.scrollBy(0,-25);
14479    }
14480
14481    var quickNavTextWriter = function($activeTab) {
14482      var $pcContainer = $activeTab.closest('.process-circles-container'),
14483        $prev = $pcContainer.find('.pc-quick-nav-prev .text'),
14484        $next = $pcContainer.find('.pc-quick-nav-next .text');
14485      $prev.text($activeTab.prev().text());
14486      $next.text($activeTab.next().text());
14487      if (!$prev.html() || $prev.html() === "&nbsp;") {
14488        $prev.parent().addClass('hidden');
14489      } else {
14490        $prev.parent().removeClass('hidden');
14491      }
14492      if (!$next.html() || $next.html() === "&nbsp;") {
14493        $next.parent().addClass('hidden');
14494      } else {
14495        $next.parent().removeClass('hidden');
14496      }
14497    }
14498    $('.process-circles-container .process-tabs-container-item.active, .process-circles-container .circle_title.active').each(function() {
14499        quickNavTextWriter($(this))
14500    }
14501    );
14502
14503    $('.process-circles-list-container li').on('click', function(){
14504      quickNavTextWriter($(this))
14505    });
14506  }
14507});
14508
14509shcDOMContentLoaded(function () {
14510    var searchVer = document.querySelector('meta[name="shc-search-version"]').content || "v1";
14511    var nextStepsContainer = $('#next-steps.container');
14512    if (nextStepsContainer.length > 0) {
14513        var viewAllLocationsLink = nextStepsContainer.find('.view-locations-link a.view-locations');
14514        if(viewAllLocationsLink.length > 0){
14515            viewAllLocationsLink.each(function () {
14516                var anchorLink = $(this);
14517                var clinicTitle = anchorLink.attr('href').split('%5E')[1];
14518                var sp_url = "/bin/api/"+searchVer+"/search.json?do=organic_clinics&x22=sp_clinics&q22=" + clinicTitle;
14519                var totalClinics = 0;
14520                var totalText = "View All # Locations";
14521                jQuery.ajax({
14522                    url: sp_url,
14523                    dataType: "jsonp",
14524                    jsonp: 'callback',
14525                    contentType: "application/json",
14526                    success: function(data) {
14527                        totalClinics = data["general"]["total"];
14528                        totalText = totalText.replace('#', parseInt(totalClinics));
14529                        anchorLink.text(totalText);
14530                    }
14531                });
14532            });
14533        }
14534    }
14535    sendMakeAppointmentButtonClicks();
14536});
14537
14538function sendMakeAppointmentButtonClicks() {
14539    const makeAppointmentButtonsList = document.querySelectorAll('a.primary-clinic.make-appointment-btn'); 
14540    if (makeAppointmentButtonsList) {
14541        makeAppointmentButtonsList.forEach(
14542            function (makeAppointmentButtonItem) {
14543                if (makeAppointmentButtonItem) {
14544                    let btnText = makeAppointmentButtonItem.text !== "" ? makeAppointmentButtonItem.text.trim() : "Make An Appointment";
14545                    let providerNameSpan = document.querySelector(".primary-clinic.clinic-title>a>span");
14546                    let providerName = null;
14547                    if (providerNameSpan) {
14548                        providerName = providerNameSpan.innerHTML;
14549                    }
14550                    makeAppointmentButtonItem.addEventListener("click", function () {
14551                        stanford.analytics.send(stanford.analytics.createComponentClickButton(btnText, "button", "Make An Appointment", null, providerName));
14552                    });
14553                }
14554            }
14555        );
14556    }
14557
14558    const makeAppointmentButtonsList2 = document.querySelectorAll('a.primary-clinic-two.make-appointment-btn'); 
14559    if (makeAppointmentButtonsList2) {
14560        makeAppointmentButtonsList2.forEach(
14561            function (makeAppointmentButtonItem) {
14562                if (makeAppointmentButtonItem) {
14563                    let btnText = makeAppointmentButtonItem.text !== "" ? makeAppointmentButtonItem.text.trim() : "Make An Appointment";
14564                    let providerNameSpan = document.querySelector(".primary-clinic-two.clinic-title>a>span");
14565                    let providerName = null;
14566                    if (providerNameSpan) {
14567                        providerName = providerNameSpan.innerHTML;
14568                    }
14569                    makeAppointmentButtonItem.addEventListener("click", function () {
14570                        stanford.analytics.send(stanford.analytics.createComponentClickButton(btnText, "button", "Make An Appointment", null, providerName));
14571                    });
14572                }
14573            }
14574        );
14575    }
14576    
14577
14578}
14579(function(SHC, jQuery) {
14580    "use strict";
14581    SHC.Namespace(SHC, "SHC.ui.MarqueeVideo");
14582    SHC.ui.MarqueeVideo = new SHC.Class();
14583    SHC.ui.MarqueeVideo.include({
14584        /*
14585         * constructor
14586         */
14587         init: function(parent) {
14588             // set video styles for close button
14589             var $marqueeBlock = jQuery('#marquee-cp16 .marquee-block');
14590             $marqueeBlock.addClass('video');
14591             // Do not fade out '.title' for Presentation Mode.
14592             jQuery("#marquee-cp16 .marquee-video .title").on("click", function(e){
14593                 e.preventDefault();
14594                 if (SHC.ui.screenMode === 'small' || SHC.ui.screenMode === 'medium') {
14595                     var videoScreen = $(e.target).closest(".marquee-video").find("div.video-screen");
14596                     var screenWidth = $(window).width() - 40;
14597                     videoScreen[0].style.height = screenWidth / 16 * 9 + "px";
14598                 }
14599                 var target = jQuery(e.target).closest("div.title");
14600                 if (!target.find("a.presentation").length>0) {
14601                   jQuery("#marquee-cp16 .mobile-image-only img").addClass("hidden");
14602                   jQuery("#marquee-cp16 .video-screen").removeClass("hidden");
14603                   jQuery("#marquee-cp16 .close-button").removeClass("hidden");
14604                   jQuery("#marquee-cp16 .title").fadeOut();
14605                 }
14606             });
14607
14608             jQuery("#marquee-cp16 .close-button").on("click", function(e){
14609                 e.preventDefault();
14610                 // Stop video playback.
14611                 jQuery('.video-screen iframe').each(function(){
14612                     this.contentWindow.postMessage('{"event":"command","func":"' + 'stopVideo' + '","args":""}', '*');
14613                 });
14614                 var target = jQuery(e.target).closest("a");
14615                 if (!target.hasClass("presentation")) {
14616                   jQuery("#marquee-cp16 .video-screen").addClass("hidden");
14617                   jQuery("#marquee-cp16 .close-button").addClass("hidden");
14618                   jQuery("#marquee-cp16 .mobile-image-only img").removeClass("hidden");
14619                   jQuery("#marquee-cp16 .title").fadeIn();
14620                 }
14621             });
14622
14623             // show the gradient if a video element is present
14624             if (jQuery("#marquee-cp16 .marquee-video").length>0) {
14625                 jQuery("#marquee-cp16 .vertical-dark-gradient").removeClass("hidden");
14626             }
14627         }
14628    });
14629}(SHC, jQuery));
14630
14631shcDOMContentLoaded(function() {
14632    var marqueeVideos = new SHC.ui.MarqueeVideo();
14633});
14634
14635shcDOMContentLoaded(function () {
14636    var programMarquees = document.querySelectorAll('.marqueeComponent.programMarqueeComponent');
14637
14638    if (programMarquees.length) {
14639        programMarquees.forEach(function (marq) {
14640            var imgEl = marq.querySelector('img.marquee__image--program');
14641            if (imgEl) {
14642                redefineImageBehavior(imgEl);
14643
14644                var timeout = false,
14645                    delay = 250;
14646                window.addEventListener("resize", function() {
14647                    clearTimeout(timeout);
14648                    timeout = setTimeout(redefineImageBehavior(imgEl), delay)
14649                })
14650            }
14651        })
14652    }
14653})
14654
14655function redefineImageBehavior(imgEl) {
14656    if (imgEl.naturalWidth <= window.innerWidth) {
14657        imgEl.style.width = "100%";
14658    } else if (imgEl.naturalWidth >= imgEl.clientWidth) {
14659        imgEl.style.width = "auto";
14660    }
14661}
14662$(document).ready(function () {
14663  const marqueeList = document.querySelectorAll('.newMarqueeContainer .marquee-youtube-video-container');
14664  var tag = document.createElement('script');
14665  tag.src = "https://www.youtube.com/player_api";
14666  var firstScriptTag = document.getElementsByTagName('script')[0];
14667  firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
14668
14669  let player = {};
14670
14671  if (marqueeList) {
14672
14673    window.onYouTubePlayerAPIReady = function () {
14674      marqueeList.forEach(initiatePlayer);
14675    }
14676
14677    marqueeList.forEach(youtubeClickEvent);
14678  }
14679
14680  function initiatePlayer(videoMarquee) {
14681    const hasImage = videoMarquee.children.length === 2;
14682    const isOnlyVideo = videoMarquee.children.length === 1;
14683
14684    let uniquePlayer;
14685    let videoID;
14686    let iframe;
14687
14688    if (hasImage) {
14689      iframe = videoMarquee.children[1].children[0];
14690      uniquePlayer = iframe.id;
14691      videoID = iframe.dataset.videoId;
14692    }
14693
14694    if (isOnlyVideo) {
14695      iframe = videoMarquee.children[0].children[0];
14696      uniquePlayer = iframe.id;
14697      videoID = iframe.dataset.videoId;
14698    }
14699
14700    if (uniquePlayer != null && videoID != null) {
14701      player[uniquePlayer] = new YT.Player(uniquePlayer, {
14702        height: '100%',
14703        width: '100%',
14704        playerVars: {
14705          'playsinline': 1,
14706          'autoplay': 0
14707        },
14708        videoId: videoID
14709      });
14710    }
14711  }
14712
14713
14714  function youtubeClickEvent(videoMarquee) {
14715    const hasImage = videoMarquee.children.length === 2;
14716    const isOnlyVideo = videoMarquee.children.length === 1;
14717
14718    if (hasImage) {
14719      const imageOverlay = videoMarquee.children[0];
14720      const youtubeVideo = videoMarquee.children[1];
14721      const uniquePlayer = youtubeVideo.children[0].id;
14722
14723      imageOverlay.addEventListener('click', function () {
14724        this.style.display = 'none';
14725        youtubeVideo.style.display = 'block';
14726        player[uniquePlayer].playVideo();
14727      });
14728    }
14729
14730    if (isOnlyVideo) {
14731      const videoPlayer = videoMarquee.children[0];
14732      videoPlayer.style.display = 'block';
14733    }
14734  }
14735});
14736shcDOMContentLoaded(function() {
14737    var getEncodedClinicName = function () {
14738        var nameFromMeta = $('meta[name=sp_displayName]');
14739        var nameFromPage = $('#header h1.shc-page-title');
14740        var nameToUse = "";
14741        if (nameFromMeta.length > 0) {
14742            nameToUse = nameFromMeta.attr('content');
14743        }
14744        else if (nameFromPage.length > 0) {
14745            nameToUse = nameFromPage.text().trim();
14746        }
14747        return encodeURIComponent(nameToUse);
14748    };
14749    var encodedClinicName = getEncodedClinicName();
14750
14751    $('.l3-doctor-list').each(function (i, list) {
14752        var isApp = $(list).find('.isapp').data('is-app');
14753        var init = function () {
14754            var searchVer = document.querySelector('meta[name="shc-search-version"]').content || "v1";
14755            var searchServiceUrl = '/bin/api/'+searchVer+'/search.json';
14756            var doer = '?do=organic_phys';
14757            var x22 = '&x22=sp_clinics';
14758            var q22 = '&q22=' + encodedClinicName;
14759            var x23 = isApp ? '&x23=sp_isapp&q23=true' : '&x23=sp_isapp&q23=false';
14760            var requestUrl = searchServiceUrl + doer + x22 + q22 + x23;
14761            makeAjaxCall(requestUrl, this);
14762        };
14763
14764        var makeAjaxCall = function (requestUrl) {
14765            $.ajax({
14766                url: requestUrl,
14767                dataType: "jsonp",
14768                jsonp: 'callback',
14769                contentType: "application/json",
14770                success: function (data) {
14771                    data.url = requestUrl;
14772                    var handlebarsTemplate = 'handlebars/l3-doctor-profile-template.hbs';
14773                    var finalData = randomizeDoctors(data.results.data);
14774                    $(list).find(".l3-doctor-profile-handlebar-target").append(JST[handlebarsTemplate](finalData));
14775                    SHC.ui.modalInstance = new SHC.ui.Modal('.make-appointment-btn.open-modal', 'doctorMakeApptModalLoaded');
14776                    if (isApp && data.results.data.length === 0) {
14777                        $('.l3-doctor-list.isAppList').hide();
14778                    }
14779                    createAptButtonEvents();
14780                }
14781            });
14782        };
14783        var profileDeck = $('.profiledeck, .l3-doctor-profile');
14784        if (profileDeck.length) {
14785            init();
14786        }
14787    });
14788
14789    var randomizeDoctors = function (dataset) {
14790        for (var i = 0; i < dataset.length - 1; i++) {
14791            var j = i + Math.floor(Math.random() * (dataset.length - i));
14792            var temp = dataset[j];
14793            dataset[j] = dataset[i];
14794            dataset[i] = temp;
14795        }
14796        return dataset;
14797    };
14798
14799  function createAptButtonEvents() {
14800    const apptButtonsList = document.querySelectorAll('.l3-doctor-profile-wrapper a.make-appointment-btn');
14801    if (apptButtonsList) {
14802      apptButtonsList.forEach(
14803        function(apptButtonItem) {
14804          if (apptButtonItem) {
14805            let btnText = apptButtonItem.text;
14806            let providerName = apptButtonItem.closest(".l3-doctor-profile-wrapper").querySelector(".doctor-name").text;
14807            apptButtonItem.removeEventListener("click", sendClick);
14808            apptButtonItem.addEventListener("click", function() {
14809              sendClick(btnText, providerName);
14810            });
14811          }
14812        });
14813    }
14814  }
14815
14816  function sendClick(btnText, providerName) {
14817    stanford.analytics.send(stanford.analytics.createComponentClickDirectory(btnText, providerName, "button", "Make An Appointment"));
14818  }
14819});
14820SHC.Namespace(SHC, "SHC.ui.InlineNav");
14821SHC.ui.InlineNav = new SHC.Class();
14822SHC.ui.InlineNav.include({
14823
14824    init: function() {
14825        this.parent = $(".inline-nav");
14826        // Desktop Elements
14827        this.$icon_open = $(".inline-nav #icon_open");
14828        this.$icon_close = $(".inline-nav #icon_close");
14829        this.$social_icons = $(".inline-nav #social_icons");
14830        this.$icon = $(".inline-nav .icon");
14831        this.$nav_open = $(".inline-nav #nav_open");
14832        this.$nav_close = $(".inline-nav #nav_close");
14833        this.$nav_list = $(".inline-nav #nav_list");
14834        this.$icon_goto = $(".inline-nav #inline-nav-cp16");
14835        this.$icon_chat = $(".inline-nav #cp16Chat");
14836        this.$icon_open.off('click');
14837        this.$icon_close.off('click');
14838        this.$icon.off('click');
14839        this.$nav_open.off('click');
14840        this.$nav_close.off('click');
14841        this.$nav_list.off('click');
14842        this.$icon_chat.off('click');
14843        // Mobile Elements
14844        this.$small_icon_open = $(".inline-nav #small_icon_open");
14845        this.$small_icon_close = $(".inline-nav #small_icon_close");
14846        this.$small_social_icons = $(".inline-nav #small_social_icons");
14847        this.$small_social_actions = $(".inpageNavMobile > #small_social_actions");
14848        this.$small_nav_open = $(".inline-nav #small_nav_open");
14849        this.$small_nav_close = $(".inline-nav #small_nav_close");
14850        this.$small_nav_list = $(".inline-nav #small_nav_list");
14851        this.$small_icon_goto = $(".inline-nav #small_inline_nav");
14852        this.$small_icon_chat = $(".inline-nav #cp16ChatMobile");
14853        this.$small_icon_open.off('click');
14854        this.$small_icon_close.off('click');
14855        this.$small_social_icons.off('click');
14856        this.$small_nav_open.off('click');
14857        this.$small_nav_close.off('click');
14858        this.$small_nav_list.off('click');
14859        this.$small_icon_chat.off('click');
14860        this.cachedFBHref = "";
14861        this.cachedTWHref = "";
14862        this.cachedEmailHref = "";
14863        //do stuff
14864        this.activate();
14865    },
14866    activate: function() {
14867        var that = this,
14868            animationDelay = 100;
14869        // share button to open behavior on a large screen
14870        var openShareComponentLarge = function(e) {
14871            if (e) {
14872                e.preventDefault();
14873            }
14874            that.$icon_open.addClass('hidden');
14875            that.$social_icons.transition({x: 0}, animationDelay);
14876            closeInlineNav();
14877        };
14878        // share button close behavior on a large screen
14879        var closeShareComponentLarge = function(e) {
14880            if (e) {
14881                e.preventDefault();
14882            }
14883            that.$social_icons.transition({x: 300}, animationDelay);
14884            that.$icon_open.removeClass('hidden');
14885        };
14886        var openInlineNav = function(e) {
14887            if (e) {
14888                e.preventDefault();
14889            }
14890            that.$nav_open.addClass('hidden');
14891            that.$nav_list.animate({right: 41}, animationDelay);
14892            closeShareComponentLarge();
14893        };
14894        // share button close behavior on a large screen
14895        var closeInlineNav = function(e) {
14896            if (e) {
14897                e.preventDefault();
14898            }
14899            that.$nav_open.removeClass('hidden');
14900            that.$nav_list.animate({right: -400}, animationDelay);
14901        };
14902        /**
14903         * Mobile Event Handlers.
14904         * ----------------------
14905         */
14906        var openShareComponentMobile = function(e) {
14907            if (e) {
14908                e.preventDefault();
14909            }
14910            that.$small_icon_open.addClass('hidden');
14911            that.$small_icon_close.removeClass('hidden');
14912            $( '#small_social_icons' ).removeClass('hidden');
14913            that.$small_social_icons.transition({y: 0}, animationDelay);
14914            closeInlineNavMobile();
14915        };
14916        var closeShareComponentMobile = function(e) {
14917            if (e) {
14918                e.preventDefault();
14919            }
14920            that.$small_social_icons.transition({y: 300}, animationDelay);
14921            that.$small_icon_open.removeClass('hidden');
14922            that.$small_icon_close.addClass('hidden');
14923            $( '#small_social_icons' ).addClass('hidden');
14924        };
14925        var openInlineNavMobile = function(e) {
14926            if (e) {
14927                e.preventDefault();
14928            }
14929            that.$small_nav_open.addClass('hidden');
14930            that.$small_nav_close.removeClass('hidden');
14931            $( '.isMobile' ).addClass( 'open' );
14932            that.$small_nav_list.transition({y: 0}, animationDelay);
14933            closeShareComponentMobile();
14934        };
14935        var closeInlineNavMobile = function(e) {
14936            if (e) {
14937                e.preventDefault();
14938            }
14939            that.$small_nav_open.removeClass('hidden');
14940            that.$small_nav_close.addClass('hidden');
14941            $( '.isMobile' ).removeClass( 'open' );
14942            that.$small_nav_list.transition({y: 1000}, animationDelay);
14943        };
14944        // prevent default action and wire up socialPopup
14945        var preventPopUp = function(e) {
14946            e.preventDefault();
14947            var iconID = $(this).attr('id');
14948            var iconHref = $(this).find('a').attr('href');
14949            if (iconID && iconHref && iconHref !== "#") {
14950                that.socialPopup(iconID, iconHref);
14951            }
14952        };
14953        if (jQuery(".inline-nav-component").length > 0) {
14954            // share button bindings
14955            that.$icon_open.on('click', openShareComponentLarge);
14956            that.$icon_close.on('click', closeShareComponentLarge);
14957            that.$nav_open.on('click', openInlineNav);
14958            that.$nav_close.on('click', closeInlineNav);
14959            that.$icon.on('click', preventPopUp);
14960            that.$icon_chat.on('click', function(e) {
14961                if (e) {
14962                    e.preventDefault();
14963                }
14964                return false;
14965            });
14966            that.$small_icon_open.on('click', openShareComponentMobile);
14967            that.$small_icon_close.on('click', closeShareComponentMobile);
14968            that.$small_nav_open.on('click', openInlineNavMobile);
14969            that.$small_nav_close.on('click', closeInlineNavMobile);
14970            closeShareComponentLarge();
14971            closeShareComponentMobile();
14972            closeInlineNavMobile();
14973            that.scanNavigation();
14974        }
14975    },
14976    scanNavigation: function() {
14977        var that = this,
14978            navLinks = jQuery("[data-nav-show=true]:not(.mobile-tab-heading-link)"),
14979            largeDiv = jQuery("#nav_list"),
14980            smallDiv = jQuery("#small_nav_list");
14981        largeDiv.empty().append(jQuery("<ul></ul>"));
14982        smallDiv.empty().append(jQuery("<ul></ul>"));
14983
14984        if (navLinks.length > 0) {
14985            var ul1 = largeDiv.find("ul"),
14986                ul2 = smallDiv.find("ul");
14987
14988            navLinks.each(function(idx, el) {
14989                var jq = jQuery(el),
14990                    id = jq.attr("id"),
14991                    text = jq.attr("data-nav"),
14992                    link = "<li><span class='circle'></span><a href='#' data-target-id='" + id + "'>" + text + "</a></li>",
14993                    item1 = jQuery(link),
14994                    item2 = jQuery(link),
14995                    clickHandler = function(e) {
14996                        e.preventDefault();
14997                        var alertMessage = $('#new-emergency-alert');
14998                        var desktopAdjustment = alertMessage.length > 0 ? alertMessage.height() + 95 : 95;
14999                        var mobileAdjustment = alertMessage.length > 0 ? alertMessage.height() + 23 : 23;
15000                        var adjust = (SHC.ui.screenMode === "small") ? mobileAdjustment : desktopAdjustment;
15001                        var $targetElement = jQuery("*[id='" + id + "']");
15002                        if (jq.hasClass('in-page-nav-anchor-tab') && !jq.hasClass('active')) {
15003                            SHC.inPageNavClick = 'true';
15004                            $targetElement.click();
15005                        }
15006                        if (jq[0].hasAttribute('data-in-page-nav-url')) {
15007                            var $tabNav = (SHC.ui.screenMode === "small") ? jQuery("#tab-nav-mobile") : jQuery("#tab-nav");
15008                            jQuery("html,body").animate({ scrollTop: $tabNav.offset().top - adjust }, 300);
15009                            var href = jq[0].getAttribute('data-in-page-nav-url');
15010                            var $childAnchor = (SHC.ui.screenMode === "small") ? $tabNav.find('.mobile-tab-heading a[data-in-page-nav-url="' + href + '"]') : $tabNav.find('.tab-heading a[data-in-page-nav-url="' + href + '"]');
15011                            if ($childAnchor.length > 0) {
15012                                $childAnchor.each(function(id, elem) {
15013                                    var $elem = jQuery(elem);
15014                                    if (SHC.ui.screenMode === "small") {
15015                                        var $mobileTabHeading = $elem.closest('.mobile-tab-heading');
15016                                        if (!$mobileTabHeading.hasClass('active')) {
15017                                            $elem.trigger("click");
15018                                        }
15019                                    }
15020                                    else {
15021                                        if (!$elem.hasClass('active')) {
15022                                            $elem.trigger("click");
15023                                        }
15024                                    }
15025                                });
15026                            }
15027                        }
15028                        else {
15029                            jQuery("html,body").animate({ scrollTop: $targetElement.offset().top - adjust }, 300);
15030                        }
15031                    };
15032                item1.on("click", clickHandler);
15033                item2.on("click", clickHandler);
15034                ul1.append(item1);
15035                ul2.append(item2);
15036            });
15037            var backLink = "<li><span class='caret-up'></span><a href='#'>Back To Top</a></li>",
15038                scrollToTop = function() {
15039                    jQuery("html,body").animate({ scrollTop: 0}, 300);
15040                },
15041                back1 = jQuery(backLink).on("click", scrollToTop),
15042                back2 = jQuery(backLink).on("click", scrollToTop);
15043            // need to append unique objects
15044            ul1.append(back1);
15045            ul2.append(back2);
15046            this.setupHoverEffects();
15047
15048            // when there are no nav items,
15049            // hide the goto buttons.
15050        } else {
15051            this.$icon_goto.hide();
15052            this.$small_icon_goto.hide();
15053            this.$nav_list.hide();
15054            this.$small_nav_list.hide();
15055            this.$small_social_actions.addClass('noNav');
15056        }
15057    },
15058    /**
15059     * Manual vertical offset adjustments by class.
15060     * @param jqObj
15061     */
15062    getScrollAdjustments: function(jq) {
15063        // base adjustments.
15064        // lower values give taller offsets.
15065        var adjust = (SHC.ui.screenMode === "small") ? -13 : -80;
15066        // .. followed by manual override
15067        if (jq.hasClass("treatment-box-container")) {
15068            if (SHC.ui.screenMode === "small") {
15069                adjust += 36;
15070            } else {
15071                adjust += -8;
15072            }
15073        }
15074        return adjust;
15075    },
15076    setupHoverEffects: function() {
15077        var nav_selector = "#nav_list li, #small_nav_list li";
15078        jQuery(nav_selector).hover(
15079            function(e) {
15080                jQuery(e.target).closest("li").addClass("active");
15081            },
15082            function() {
15083                jQuery(nav_selector).removeClass("active");
15084            }
15085        );
15086    },
15087    // Bitly Magic - FB
15088    // TODO: I think the current url needs to be url encoded per bitly requirements doc
15089    getBitlyFB: function() {
15090        let locationHref = window.location.href;
15091        // for local testing
15092        if (locationHref.indexOf("localhost") > -1) {
15093            locationHref = locationHref.replaceAll("http://localhost:4502/","https://stanfordhealthcare.org/");
15094        }
15095        locationHref = this.appendDecodedSocialID(locationHref, "ecid=soc-fb");
15096        let getter = "https://www.facebook.com/sharer/sharer.php?u=" + locationHref;
15097        return getter;
15098    },
15099    // Bitly Magic - Twitter
15100    // TODO: I think the current url needs to be url encoded per bitly requirements doc
15101    getBitlyTW: function() {
15102        let locationHref = window.location.href;
15103        // for local testing
15104        if (locationHref.indexOf("localhost") > -1) {
15105            locationHref = locationHref.replaceAll("http://localhost:4502/","https://stanfordhealthcare.org/");
15106        }
15107        locationHref = this.appendDecodedSocialID(locationHref, "ecid=soc-tw");
15108        let shareTitle = jQuery('meta[name="mail_title"]').attr('content');
15109        if(jQuery('.share-data').length > 0){
15110            shareTitle = jQuery("meta[name='twitter:title']").attr('content');
15111        }
15112        getter = "https://twitter.com/share?text=" + encodeURIComponent(shareTitle) + "&url=" + locationHref + "&via=StanfordHealth";
15113        return getter;
15114    },
15115    // Bitly Magic - Email
15116    // TODO: I think the current url needs to be url encoded per bitly requirements doc
15117    getBitlyEmail: function() {
15118        var locationHref = window.location.href;
15119        // for local testing
15120        if (locationHref.indexOf("localhost") > -1) {
15121            locationHref = locationHref.replaceAll("http://localhost:4502/","https://stanfordhealthcare.org/");
15122        }
15123        locationHref = this.appendDecodedSocialID(locationHref, "ecid=soc-em");
15124        var getter = "mailto:?subject=Stanford Health Care&body=Stanford Health Care " + locationHref;
15125        if(jQuery('.share-data').length > 0){
15126            shareTitle = jQuery(".share-data meta[name='twitter:title']").attr('content');
15127            shareDescription = jQuery('.share-data meta[name="twitter:description"]').attr('content');
15128            getter = "mailto:?subject=" + shareTitle + "&body=" + shareDescription;
15129        }
15130        return getter;
15131    },
15132
15133    appendDecodedSocialID: function(currentURL, socID) {
15134        if (currentURL.indexOf("/presentation-mode") > -1) {
15135            currentURL = this.removeExistingKwcid(currentURL);
15136            var pmodeIdx = currentURL.indexOf("/presentation-mode");
15137            var baseURL = currentURL.substr(0,pmodeIdx);
15138            var pmodeURL = currentURL.substr(pmodeIdx);
15139            if (baseURL.indexOf("?") > -1) {
15140                if (baseURL.indexOf("ecid") > -1) {
15141                    baseURL = this.removeExistingEcid(baseURL);
15142                }
15143                if (baseURL.indexOf("?") === (baseURL.length - 1)) {
15144                    return baseURL + socID + pmodeURL;
15145                } else {
15146                    return baseURL + "&" + socID + pmodeURL;
15147                }
15148            } else {
15149                return baseURL + "?" + socID + pmodeURL;
15150            }
15151        } else {
15152            if (currentURL.indexOf("?") > -1) {
15153                if (currentURL.indexOf("ecid") > -1) {
15154                    currentURL = this.removeExistingEcid(currentURL);
15155                }
15156                currentURL = this.removeExistingKwcid(currentURL);
15157                if (currentURL.indexOf("?") === (currentURL.length - 1)) {
15158                    currentURL + socID;
15159                } else {
15160                    return currentURL + "&" + socID;
15161                }
15162            } else {
15163                return currentURL + "?" + socID;
15164            }
15165        }
15166    },
15167
15168    appendSocialID: function(currentURL, socID) {
15169        if (currentURL.indexOf("/presentation-mode") > -1) {
15170            currentURL = this.removeExistingKwcid(currentURL);
15171            var pmodeIdx = currentURL.indexOf("/presentation-mode");
15172            var baseURL = currentURL.substr(0, pmodeIdx);
15173            var pmodeURL = currentURL.substr(pmodeIdx);
15174            if (baseURL.indexOf("?") > -1) {
15175                if (baseURL.indexOf("ecid") > -1) {
15176                    baseURL = this.removeExistingEcid(baseURL);
15177                }
15178                if (baseURL.indexOf("?") === (baseURL.length - 1)) {
15179                    return encodeURIComponent(baseURL + socID + pmodeURL);
15180                } else {
15181                    return encodeURIComponent(baseURL + "&" + socID + pmodeURL);
15182                }
15183            } else {
15184                return encodeURIComponent(baseURL + "?" + socID + pmodeURL);
15185            }
15186        } else {
15187            if (currentURL.indexOf("?") > -1) {
15188                if (currentURL.indexOf("ecid") > -1) {
15189                    currentURL = this.removeExistingEcid(currentURL);
15190                }
15191                currentURL = this.removeExistingKwcid(currentURL);
15192                if (currentURL.indexOf("?") === (currentURL.length - 1)) {
15193                    return encodeURIComponent(currentURL + socID);
15194                } else {
15195                    return encodeURIComponent(currentURL + "&" + socID);
15196                }
15197            } else {
15198                return encodeURIComponent(currentURL + "?" + socID);
15199            }
15200        }
15201    },
15202    /**
15203     * Strips out all instances of ecid=soc- if it exists. Based off the current ecid=soc-tw with 11 characers
15204     * @param url
15205     * @returns {*}
15206     */
15207    removeExistingEcid: function(url) {
15208        var ecidIndex = url.indexOf('ecid=soc-'),
15209            beforeEcid,
15210            afterEcid;
15211        while (ecidIndex !== -1) {
15212            // cut it out
15213            if (url.charAt(ecidIndex - 1) === "&") {
15214                beforeEcid = url.substr(0, ecidIndex - 1);
15215                afterEcid = url.substr(ecidIndex + 11);
15216            } else {
15217                beforeEcid = url.substr(0, ecidIndex);
15218                afterEcid = url.substr(ecidIndex + 12);
15219            }
15220            url = beforeEcid + afterEcid;
15221            ecidIndex = url.indexOf('ecid=soc-');
15222        }
15223        return url;
15224    },
15225    /**
15226     * Strips out all instances of kwcid parameter if it exists.
15227     * @param url
15228     * @returns {*}
15229     */
15230    removeExistingKwcid: function(url) {
15231        var kwcidIndex = url.indexOf('kwcid=');
15232        var presmode = false;
15233        if (url.indexOf(HOME_PAGE_PATH + ".html/presentation-mode") > -1) {
15234            presmode = true;
15235        }
15236        while (kwcidIndex !== -1) {
15237            // cut it out
15238            var endofparamIndex = url.length;
15239            var i = kwcidIndex;
15240            // can't rely on an exact character count, so we need to detect the end of the parameter
15241            while (i < endofparamIndex) {
15242                if (url.charAt(i) === "&") {
15243                    if (i < endofparamIndex) {
15244                        endofparamIndex = i + 1;
15245                    } else {
15246                        endofparamIndex = i;
15247                    }
15248                    break;
15249                }
15250                //need to account for presentation mode special case on home page
15251                if (presmode) {
15252                    if (url.substr(i, 37) === HOME_PAGE_PATH + ".html/presentation-mode") {
15253                        endofparamIndex = i;
15254                        if (url.charAt(kwcidIndex - 1) === "?") {
15255                            kwcidIndex = kwcidIndex - 1;
15256                        }
15257                        break;
15258                    }
15259                }
15260                i++;
15261                if (i === endofparamIndex) {
15262                    if (url.charAt(kwcidIndex - 1) === "&") {
15263                        kwcidIndex = kwcidIndex - 1;
15264                    }
15265                    endofparamIndex = i;
15266                }
15267            }
15268            var beforeEcid = url.substr(0, kwcidIndex);
15269            var afterEcid = url.substr(endofparamIndex);
15270            url = beforeEcid + afterEcid;
15271            kwcidIndex = url.indexOf('kwcid=');  // detect multiple instances of the parameter
15272        }
15273        return url;
15274    },
15275    socialPopup: function(elementID, url) {
15276        // detect which network we're on
15277        // get bit.ly link
15278        // then open window
15279        var bitLink;
15280        switch (elementID) {
15281            case "icon_facebook":
15282            case "small_icon_facebook":
15283                bitLink = this.getBitlyFB();
15284                window.open(bitLink, 'shcsocial', 'width=400,height=500');
15285                break;
15286            case "icon_twitter":
15287            case "small_icon_twitter":
15288                bitLink = this.getBitlyTW();
15289                window.open(bitLink, 'shcsocial', 'width=400,height=500');
15290                break;
15291            case "icon_email":
15292            case "small_icon_email":
15293                bitLink = this.getBitlyEmail();
15294                document.location.href = bitLink;
15295                break;
15296            default:
15297                document.location.href = url;
15298        }
15299    },
15300    getSelectedText: function() {
15301        var selectedText = jQuery("h1").text();
15302        if (window.getSelection) {
15303            selectedText = window.getSelection();
15304        } else if (document.getSelection) {
15305            selectedText = document.getSelection();
15306        } else if (document.selection) {
15307            selectedText = document.selection.createRange();
15308        }
15309        return selectedText;
15310    },
15311    updateShareHrefs: function(params) {
15312        //update share components - when entering or exiting presentation mode, we need to adjust the href values of the anchor tags for each of the share icons
15313        var enterPresentation = params.enterPresentation || false,
15314            fb = $("#icon_facebook").find("a"),
15315            tw = $("icon_twitter").find("a"),
15316            gp = $("#icon_google_plus").find("a"),
15317            email = $("#icon_email").find("a");
15318        if (enterPresentation) {
15319            var currentPageTitle = document.title,
15320                titleNoSpaces = currentPageTitle.replace(" ", "%20"),
15321                pageDescription = $('meta[property="description"]').attr("content");
15322            // cache out the old hrefs
15323            this.cachedFBHref = fb.attr("href");
15324            this.cachedTWHref = tw.attr("href");
15325            this.cachedEmailHref = email.attr("href");
15326            // set new hrefs
15327            fb.attr("href", "https://www.facebook.com/sharer/sharer.php?u=" + window.location.href);
15328            tw.attr("href", "https://twitter.com/share?text=" + titleNoSpaces + "%20" + window.location.href + "via=StanfordHealth");
15329            email.attr("href", "mailto:?subject=" + currentPageTitle + "&body=" + currentPageTitle + "%0D" + pageDescription + " - " + window.location.href);
15330        } else {
15331            // reset hrefs
15332            fb.attr("href", this.cachedFBHref);
15333            tw.attr("href", this.cachedTWHref);
15334            email.attr("href", this.cachedEmailHref);
15335            // dump cache
15336            this.cachedFBHref = "";
15337            this.cachedTWHref = "";
15338            this.cachedEmailHref = "";
15339        }
15340    }
15341});
15342shcDOMContentLoaded(function() {
15343    if (jQuery(".inline-nav").length > 0) {
15344        var share = new SHC.ui.InlineNav();
15345    }
15346});
15347
15348SHC.Namespace(SHC, "SHC.ui.EaseOfAccess");
15349SHC.ui.EaseOfAccess = new SHC.Class();
15350
15351SHC.ui.EaseOfAccess.include({
15352    /**
15353     * constructor
15354     * @param parent
15355     */
15356    init: function () {
15357        var self = this;
15358        this.categoryViewAll();
15359        this.infoWindowInit = false;
15360        this.placeholderImage = $('.map-placeholder');
15361        this.usingCircleMarkers = $("#colorPin").val() === "true";
15362        this.container = $('.ease-of-access.container');
15363        this.newStyleBool = this.container.hasClass('new-map-styles');
15364
15365        var setUpPlaceholderClickHandlers = function () {
15366            if (self.placeholderImage.size() > 0) {
15367                self.placeholderImage.click(function () {
15368                    self.setUpMap();
15369                    $(this).remove();
15370                });
15371
15372                if ($('.address-listing').size() > 0) {
15373                    $('.address-listing').click(function () {
15374                        if ($('.map-placeholder').size() > 0) {
15375                            self.setUpMap();
15376                            $('.map-placeholder').remove();
15377                            $(this).click();
15378                        }
15379                    });
15380                }
15381            } else {
15382                self.setUpMap();
15383            }
15384        }
15385
15386        var createGoogleMapObject = function () {
15387            self.normalSize = {
15388                size: new google.maps.Size(26.162, 38.236),
15389                labelSize: new google.maps.Point(13, 13),
15390                zIndex: 1
15391            };
15392            self.bigSize = {
15393                size: new google.maps.Size(31.412, 45.912),
15394                labelSize: new google.maps.Point(16, 16),
15395                zIndex: 10
15396            };
15397
15398            setUpPlaceholderClickHandlers();
15399        };
15400
15401        self.relatedClinicsServletPath = "/bin/api/v1/content/relatedclinicsmap.";
15402        if (!(typeof window.google === 'object' && window.google.maps)) {
15403            var scriptLink = "//maps.googleapis.com/maps/api/js?libraries=weather,geometry&sensor=false&key=" + SHC.util.getGoogleAPIKey();
15404            $.getScript(scriptLink).success(function () {
15405                $.getScript("/etc/clientlibs/shc/main/js/vendor/infobubble.min.js").success(function () {
15406                    $.getScript("/etc/clientlibs/shc/main/js/vendor/jquery.mCustomScrollbar.concat.min.js").success(createGoogleMapObject);
15407                });
15408            });
15409        } else if (window.google.maps && !this.infoWindowInit) {
15410            $.getScript("/etc/clientlibs/shc/main/js/vendor/infobubble.min.js").success(function () {
15411                $.getScript("/etc/clientlibs/shc/main/js/vendor/jquery.mCustomScrollbar.concat.min.js").success(createGoogleMapObject);
15412            });
15413        } else {
15414            createGoogleMapObject();
15415        }
15416    },
15417
15418    setUpMap: function () {
15419        var self = this;
15420        var mapData = 'no data';
15421        var map = {};
15422        var $mapContainer = [];
15423        var hasID = [];
15424        var noID = [];
15425        var $eoaContainer = [];
15426        var isAuthorMode = SHC.util.WCM.isAuthorMode();
15427
15428        if (isAuthorMode) {
15429            $eoaContainer = $('.ease-of-access.container');
15430            $mapContainer = self.generateAppropriateDom($eoaContainer, 'desktop');
15431        }
15432        else {
15433            $eoaContainer = $('.ease-of-access.container').not('.clone-content .ease-of-access.container');
15434            //determine appropriate elements based on screen size and render only those, to avoid unnecessary map render
15435            if (SHC.ui.screenMode === 'small') {
15436                $mapContainer = self.generateAppropriateDom($eoaContainer, 'mobile');
15437            } else {
15438                $mapContainer = self.generateAppropriateDom($eoaContainer, 'desktop');
15439            }
15440        }
15441
15442        // set of those that have ID
15443        for (var i = 0; i < $mapContainer.length; i++) {
15444            if ($($mapContainer[i]).data('id') && $($mapContainer[i]).data('id') !== 'no data') {
15445                hasID.push($mapContainer[i]);
15446            }
15447        }
15448
15449        // set of those that do not have ID
15450        for (i = 0; i < $mapContainer.length; i++) {
15451            if ($($mapContainer[i]).data('id') === undefined || $($mapContainer[i]).data('id') === 'no data') {
15452                noID.push($mapContainer[i]);
15453            }
15454        }
15455
15456        //loop through each of hasID elements on the page and render them
15457        for (i = 0; i < hasID.length; i++) {
15458            var mapContainerElem = $(hasID[i]);
15459            mapData = mapContainerElem.data("manual-clinics");
15460            var $mapSelector = mapContainerElem.find('.ease-of-access-map');
15461            map = self.generateMapObj($mapSelector[0]);
15462            self.initMapAndPageProps(map, mapData);
15463        }
15464
15465        //loop through each of noID elements on the page and render them
15466        for (i = 0; i < noID.length; i++) {
15467            mapContainerElem = $(noID[i]);
15468            $mapSelector = mapContainerElem.find('.ease-of-access-map');
15469            mapData = 'no data';
15470            map = self.generateMapObj($mapSelector[0]);
15471            self.initMapAndPageProps(map, mapData);
15472        }
15473    },
15474
15475    generateAppropriateDom: function (container, screen) {
15476        if (screen === 'desktop') {
15477            return container.not('.mobile-tab-details-container .ease-of-access.container').not('.mobile-circle-content .ease-of-access.container').find('.map-container');
15478        }
15479        else if (screen === 'mobile') {
15480            return container.not('.desktop-tab-details-container .ease-of-access.container').not('.desktop-circle-content .ease-of-access.container').find('.map-container');
15481        }
15482    },
15483
15484    generateMapObj: function (elem) {
15485        return new google.maps.Map(elem, {
15486            mapTypeControl: false,
15487            zoomControl: true,
15488		    zoomControlOptions: {
15489		      position: google.maps.ControlPosition.RIGHT_CENTER,
15490		    },
15491            streetViewControl: false
15492        });
15493    },
15494
15495    initMapAndPageProps: function (map, data) {
15496        var self = this;
15497        var pageType = "";
15498        if (window.location.href.indexOf("medical-conditions") > -1) {
15499            pageType = "condition";
15500        } else if (window.location.href.indexOf("medical-clinics") > -1) {
15501            pageType = "clinic";
15502        } else if (window.location.href.indexOf("medical-treatments") > -1) {
15503            pageType = "treatment";
15504        } else if (window.location.href.indexOf("campaigns") > -1) {
15505            pageType = "campaign";
15506        }
15507        var url = window.location.pathname;
15508        var pageName = url.substring(url.lastIndexOf('/') + 1).split('.')[0];
15509
15510        var pageTemplate = jQuery('#shc-search-title').attr("data-page-template");
15511        if (pageTemplate != null) {
15512            if (pageTemplate.indexOf('hubpage') > 0 || pageTemplate.indexOf('hubdetail') > 0) {
15513                var parentPage = $('meta[name=parentPagePath]').attr('content');
15514                if (parentPage.length > 0) {
15515                    pageName = parentPage.substring(parentPage.lastIndexOf('/') + 1);
15516                }
15517            }
15518        } else {
15519            //Since page template is null we don't need it
15520            pageTemplate = pageType;
15521        }
15522
15523        self.addCustomZoomControls(map);
15524        self.buildRelatedClinicsDisplay(pageName, pageType, map, data);
15525    },
15526
15527    setupFilters: function (data, allMarkers, self) {
15528        if (!data) return;
15529        var filtersObj = {};
15530        var clinicAttributeSplit = [];
15531        var clinicAttribute = "";
15532        var title = "";
15533        var filterColors = data.filtersInfo.filterColors.split(', ');
15534        var clinicAttributesToShow = data.filtersInfo.clinicAttributesToShow.split(', ');
15535        for (var i = 0; i < data.maplocations.length; i++) {
15536            for (var k = 0; k < data.maplocations[i].clinics.length; k++) {
15537                if (data.maplocations[i].clinics[k].clinicAttributes) {
15538                    clinicAttributeSplit = data.maplocations[i].clinics[k].clinicAttributes.split(', ');
15539                    for (var j = 0; j < clinicAttributeSplit.length; j++) {
15540                        clinicAttribute = clinicAttributeSplit[j];
15541                        title = data.maplocations[i].clinics[k].title;
15542                        if (filtersObj[clinicAttribute] === undefined) {
15543                            filtersObj[clinicAttribute] = [title];
15544                        } else {
15545                            if (filtersObj[clinicAttribute].indexOf(title) === -1) {
15546                                filtersObj[clinicAttribute].push(title);
15547                            }
15548                        }
15549                    }
15550                }
15551            }
15552        }
15553        var filter = "";
15554        var filterKey = "";
15555        var filterColor = "";
15556        for (var p = 0; p < clinicAttributesToShow.length; p++) {
15557            if (filtersObj[clinicAttributesToShow[p]] !== undefined) {
15558                if (filterColors[p] !== undefined) {
15559                    filterColor = filterColors[p];
15560                } else {
15561                    filterColor = "cardinal-filter-color";
15562                }
15563                filterKey = clinicAttributesToShow[p].split(" ").join("-");
15564                filter = "<div class='clinic-attribute-filter'><span data-clinic-attr='" + clinicAttributesToShow[p] + "' class='filter-checkbox " + filterColor + " " + filterKey + "-filter'></span><label class='" + filterColor + "'>" + clinicAttributesToShow[p] + "</label></div>";
15565                $(".clinic-attribute-filters").append(filter);
15566                $(".filter-checkbox." + filterKey + "-filter").click(function (event) {
15567                    $(event.target).toggleClass("checked");
15568                    var markerTitlesToChange = filtersObj[event.target.getAttribute("data-clinic-attr")];
15569                    if ($(".filter-checkbox.checked").length === 0) {
15570                        for (var k = 0; k < allMarkers.length; k++) {
15571                            allMarkers[k].setVisible(true);
15572                        }
15573                        $(".location-category-list .address-listing").each(function () {
15574                            $(this).css("display", "flex");
15575                        });
15576                        self.categoryViewAll();
15577                    } else if (!$(event.target).hasClass("checked")) {
15578                        $(".filter-checkbox.checked").each(function (index) {
15579                            var clinicAttrData = $(this).attr("data-clinic-attr");
15580                            var titlesToNotRemove = filtersObj[clinicAttrData];
15581                            markerTitlesToChange = markerTitlesToChange.filter(function (item) {
15582                                return !titlesToNotRemove.includes(item);
15583                            });
15584                        });
15585
15586                        for (var i = 0; i < allMarkers.length; i++) {
15587                            if (markerTitlesToChange.includes(allMarkers[i].getTitle())) {
15588                                allMarkers[i].setVisible(false);
15589                            }
15590                        }
15591                        $(".location-category-list .address-listing").each(function () {
15592                            if (markerTitlesToChange.includes($(this).attr("data-marker-title"))) {
15593                                $(this).css("display", "none");
15594                            }
15595                        });
15596                        self.categoryViewAll();
15597                    } else {
15598                        if ($(".filter-checkbox.checked").length === 1) {
15599                            for (var j = 0; j < allMarkers.length; j++) {
15600                                if (!markerTitlesToChange.includes(allMarkers[j].getTitle())) {
15601                                    allMarkers[j].setVisible(false);
15602                                }
15603                            }
15604                            $(".location-category-list .address-listing").each(function () {
15605                                if (!markerTitlesToChange.includes($(this).attr("data-marker-title"))) {
15606                                    $(this).css("display", "none");
15607                                }
15608                            });
15609                        }
15610                        else if ($(".filter-checkbox.checked").length > 1) {
15611                            for (var j = 0; j < allMarkers.length; j++) {
15612                                if (markerTitlesToChange.includes(allMarkers[j].getTitle())) {
15613                                    allMarkers[j].setVisible(true);
15614                                }
15615                            }
15616                            $(".location-category-list .address-listing").each(function () {
15617                                if (markerTitlesToChange.includes($(this).attr("data-marker-title"))) {
15618                                    $(this).css("display", "flex");
15619                                }
15620                            });
15621                        }
15622                        self.categoryViewAll();
15623                    }
15624                });
15625            }
15626        }
15627    },
15628
15629    setupMobileFiltersToggle: function () {
15630        var mobileToggleIcon = $(".clinic-attribute-filters-mobile-toggle-icon");
15631        mobileToggleIcon.click(function () {
15632            if (mobileToggleIcon.hasClass("filters-plus-icon")) {
15633                $(".clinic-attribute-filters").css("display", "block");
15634
15635            } else {
15636                $(".clinic-attribute-filters").css("display", "none");
15637            }
15638            mobileToggleIcon.toggleClass("filters-plus-icon");
15639            mobileToggleIcon.toggleClass("filters-minus-icon");
15640        });
15641    },
15642
15643    buildRelatedClinicsDisplay: function (pagename, pagetype, map, data) {
15644        var self = this;
15645        if (data === "no data") {
15646            var targetUrl = self.relatedClinicsServletPath + pagetype + "." + pagename + ".json";
15647
15648            // hit our servlet to give us our info about related l3 clinics
15649            var request = jQuery.ajax({
15650                url: targetUrl,
15651                async: true,
15652                contentType: "application/json"
15653            }).done(function (data) {
15654                if (data.error != 'No related clinics found') {
15655                    self.loadClinicDirectoryMap(map, data);
15656                }
15657            });
15658        }
15659        else {
15660            self.loadClinicDirectoryMap(map, data);
15661        }
15662    },
15663
15664    addCustomZoomControls: function (map) {
15665        var zoomIn = document.createElement('span');
15666        zoomIn.className = 'gmap-zoom-in';
15667        zoomIn.style.cursor = 'pointer';
15668
15669        var zoomOut = document.createElement('span');
15670        zoomOut.className = 'gmap-zoom-out';
15671        zoomOut.style.cursor = 'pointer';
15672
15673        var zoomContainer = document.createElement('div');
15674        zoomContainer.appendChild(zoomIn);
15675        zoomContainer.appendChild(zoomOut);
15676
15677        google.maps.event.addDomListener(zoomIn, 'click', function () {
15678            map.setZoom(map.getZoom() + 1);
15679        });
15680
15681        google.maps.event.addDomListener(zoomOut, 'click', function () {
15682            map.setZoom(map.getZoom() - 1);
15683        });
15684
15685        map.controls[google.maps.ControlPosition.TOP_RIGHT].push(zoomContainer);
15686    },
15687
15688    loadClinicDirectoryMap: function (map, results) {
15689        var self = this;
15690        var mapIcon = 'https://stanfordhealthcare.org/etc/clientlibs/shc/main/img/SHC_Map_Pin_Active.png';
15691        var bounds = new google.maps.LatLngBounds();
15692        var latitude, longitude, markerSVG, labelText, markerColor, markerTitle, newStyle;
15693        var allMarkers = [];
15694
15695        // iterate over all the clinics and add them to the map
15696        if (!results) return;
15697        for (var i = 0; i < results.maplocations.length; i++) {
15698            latitude = results.maplocations[i].latitude;
15699            longitude = results.maplocations[i].longitude;
15700            newStyle = this.newStyleBool;
15701            labelText = results.maplocations[i].clinics[0].mapMarkerLabel;
15702            markerColor = results.maplocations[i].clinics[0].mapMarkerColor;
15703            markerTitle = results.maplocations[i].clinics[0].title;
15704            
15705            if (this.usingCircleMarkers) {
15706                if (labelText && newStyle) {
15707                    markerSVG = self.getMarkerSVG('circle-ns', markerColor);
15708                } else {
15709                    if (labelText && !newStyle) {
15710                        markerSVG = self.getMarkerSVG('circle', markerColor);
15711                    }
15712                    if (!labelText && newStyle) {
15713                        markerSVG = self.getMarkerSVG('star-circle-ns', markerColor);
15714                    }
15715                    if (!labelText && !newStyle) {
15716                        markerSVG = self.getMarkerSVG('star-circle', markerColor);
15717                    }
15718                }
15719            } else {
15720                if (labelText && newStyle) {
15721                    markerSVG = self.getMarkerSVG('pin-ns', markerColor);
15722                } else {
15723                    if (labelText && !newStyle) {
15724                        markerSVG = self.getMarkerSVG('pin', markerColor);
15725                    }
15726                    if (!labelText && newStyle) {
15727                        markerSVG = self.getMarkerSVG('star-pin-ns', markerColor);
15728                    }
15729                    if (!labelText && !newStyle) {
15730                        markerSVG = self.getMarkerSVG('star-pin', markerColor);
15731                    }
15732                }
15733            }
15734            if (latitude && longitude) {
15735                // create a map marker for this clinic
15736                var markerConfig = {
15737                    position: new google.maps.LatLng(latitude, longitude),
15738                    map: map,
15739                    icon: {
15740                        url: 'data:image/svg+xml;charaset=UTF-8;base64,' + btoa(markerSVG),
15741                        size: this.normalSize.size,
15742                        scaledSize: this.normalSize.size,
15743                        labelOrigin: labelText ? this.normalSize.labelSize : null
15744                    },
15745                    zIndex: this.normalSize.zIndex,
15746                    mapcolor:markerColor,
15747                    title: markerTitle
15748                }
15749                if (labelText) {
15750                    var labelTextColor = "#000000";
15751                    if (!this.newStyleBool) {
15752                        labelTextColor = "#FFFFFF";
15753                    }
15754                    markerConfig.label = {
15755                        text: labelText,
15756                        color: labelTextColor,
15757
15758                        fontSize: labelText.length == 3 ? '10px' : '14px',
15759                        fontFamily: "Source Sans Pro,Helvetica Neue,Helvetica,Arial,sans-serif"
15760                    };
15761                }
15762                var marker = new google.maps.Marker(markerConfig);
15763                allMarkers.push(marker);
15764
15765                self.addClinicClickListeners(results.maplocations[i], marker, map);
15766
15767                //extend the bounds to include each marker's position
15768                bounds.extend(marker.position);
15769            }
15770        }
15771        if ($(".clinic-attribute-filters").length !== 0) {
15772            self.setupFilters(results, allMarkers, self);
15773            self.setupMobileFiltersToggle();
15774        }
15775        // reset the map's bounds so that all the marker's show
15776        if (results.maplocations.length === 1) {
15777            map.fitBounds(bounds);
15778            zoomChangeBoundsListener =
15779                google.maps.event.addListenerOnce(map, 'bounds_changed', function (event) {
15780                    if (this.getZoom()) {
15781                        this.setZoom(16);
15782                    }
15783                });
15784        } else {
15785            map.fitBounds(bounds);
15786        }
15787    },
15788
15789    addClinicClickListeners: function (result, marker, map) {
15790        var that = this;
15791
15792        var infoWindowContent = "",
15793            clinic,
15794            markerLocationInfo,
15795            infoWindowWidth;
15796        // only put in a header if there's more than 1 clinic at this location, otherwise we'll only use the single clinic template
15797        if (result.clinics.length > 1) {
15798            var clinicHeaderInfo = {
15799                numClinics: result.clinics.length,
15800                address: result.clinics[0].address,
15801                city: result.clinics[0].city,
15802                state: result.clinics[0].state
15803            };
15804
15805            infoWindowContent += this.loadTemplate(clinicHeaderInfo, JST["handlebars/info-window-clinic-header.hbs"]);
15806            infoWindowContent += "<div class='info-window-clinic-content-wrapper multi-clinic-content-wrapper'>";
15807        }
15808        else {
15809            infoWindowContent += "<div class='info-window-clinic-content-wrapper single-clinic-content-wrapper'>";
15810        }
15811
15812
15813        for (var i = 0; i < result.clinics.length; i++) {
15814            clinic = result.clinics[i];
15815            clinic.pagePath = clinic.pagePath.indexOf('/content/shc/en') !== -1 ? 'https://stanfordhealthcare.org/' + clinic.pagePath.split('/content/shc/en/')[1] : clinic.pagePath;
15816            markerLocationInfo = {
15817                pagePath: clinic.pagePath,
15818                title: clinic.title,
15819                address: clinic.address,
15820                address2: clinic.address2,
15821                city: clinic.city,
15822                state: clinic.state,
15823                zipcode: clinic.zipcode,
15824                templatePath: clinic.templatePath,
15825                locationDetails: clinic.locationDetails,
15826                isClinic: clinic.isClinic
15827            };
15828            if (result.clinics.length > 1) {
15829                infoWindowWidth = 300;
15830                infoWindowContent += this.loadTemplate(markerLocationInfo, JST["handlebars/info-window-clinics-template.hbs"]);
15831            }
15832            else {
15833                infoWindowWidth = 230;
15834                infoWindowContent += "<span class='hidden single-clinic-address'>" + clinic.address + ", " + clinic.city + ", " + clinic.state + "</span>";
15835                infoWindowContent += this.loadTemplate(markerLocationInfo, JST["handlebars/info-window-clinic-template.hbs"]);
15836            }
15837        }
15838        infoWindowContent += "</div>";
15839
15840        var infoWindow = new InfoBubble({
15841            content: infoWindowContent,
15842            maxWidth: infoWindowWidth,
15843            minWidth: infoWindowWidth,
15844            minHeight: 300,
15845            maxHeight: 200,
15846            shadowStyle: 0,
15847            padding: 16,
15848            borderRadius: 5,
15849            closeSrc: "/etc/clientlibs/shc/main/svg/close-icon-info-bubble.svg"
15850        });
15851        if (infoWindow && !this.infoWindowInit) {
15852            this.infoWindowInit = true;
15853        }
15854
15855        var markerListing = $('.location-listing');
15856
15857        var openMapMarker = function (thisAddressListing) {
15858            if (that.activeMarker) {
15859                that.activeMarker.setIcon(that.closeMarker(that.activeMarker, that.usingCircleMarkers));
15860                that.setMarkerIconSize(that.activeMarker, that.normalSize);
15861            }
15862
15863            // close any active info windows (only want one open at a time)
15864            if (that.openInfoWindow) {
15865                that.openInfoWindow.close();
15866            }
15867            that.activeMarker = marker;
15868            that.openInfoWindow = infoWindow;
15869
15870            that.activeMarker.setIcon(that.openMarker(that.activeMarker));
15871            infoWindow.open(map, marker);
15872
15873            markerListing.find('.address-listing').removeClass('active');
15874            thisAddressListing.addClass('active');
15875
15876            if (thisAddressListing.position()) {
15877                markerListing.animate(
15878                    { scrollTop: thisAddressListing.position().top }, 300
15879                );
15880            }
15881
15882            // fire event for analytics
15883            $(window).trigger("EaseOfAccessMapClick");
15884        };
15885
15886        // listener for when open info window is closed
15887        google.maps.event.addListener(infoWindow, 'closeclick', function () {
15888            // set the active marker's icon back to it's regular size
15889            markerListing.find('.address-listing').removeClass('active');
15890            that.activeMarker.setIcon(that.closeMarker(that.activeMarker, that.usingCircleMarkers));
15891            that.setMarkerIconSize(that.activeMarker, that.normalSize);
15892            that.activeMarker = null;
15893            that.openInfoWindow.close();
15894            $('.clinic-title-tracking').removeClass('clinic-title-tracking');
15895        });
15896        google.maps.event.addListener(infoWindow, 'domready', function () {
15897            if (result.clinics.length > 1) {
15898                $('.info-window-clinic-content-wrapper').mCustomScrollbar({
15899                    theme: "map-view"
15900                });
15901            }
15902            // bind the "Getting Here" links in the info window
15903            new SHC.ui.Modal('.info-window-modal.info-window-location');
15904            $(window).trigger("EaseOfAccessDomReady");
15905        });
15906
15907        // listener for when marker is clicked
15908        google.maps.event.addListener(marker, 'click', function (e) {
15909            var currentAddressListing = $('.address-listing[data-marker-title="' + marker.title + '"]');
15910            openMapMarker(currentAddressListing);
15911        });
15912        // Listeners for when address list item is clicked
15913        result.clinics.forEach(function (clinic) {
15914            var currentAddressListing = $('.address-listing[data-marker-title="' + clinic.title + '"]');
15915            currentAddressListing.on('click', function (e) {
15916                e.stopPropagation();
15917                openMapMarker(currentAddressListing);
15918            });
15919        });
15920    },
15921
15922    loadTemplate: function (incomingData, template) {
15923        return template(incomingData);
15924    },
15925
15926    setMarkerIconSize: function (marker, iconSize) {
15927        if (marker) {
15928            var icon = marker.getIcon();
15929            icon.size = iconSize.size;
15930            icon.scaledSize = iconSize.size;
15931            icon.labelOrigin = iconSize.labelSize;
15932            marker.setIcon(icon);
15933            marker.zIndex = iconSize.zIndex;
15934        }
15935    },
15936
15937    categoryViewAll: function () {
15938        var showMoreCategoriesButtonText = 'View All +';
15939        var showLessCategoriesButtonText = 'View Less -';
15940        var categoryLists = $('.location-category-list');
15941        var numberOfListingsToShow = 3;
15942        var viewAll = $('.view-all-mobile');
15943        viewAll.hide();
15944
15945        var sizeListings = function () {
15946            var isMobile = window.matchMedia('only screen and (max-width: 767px)').matches;
15947
15948            categoryLists.each(function (idx, list) {
15949                var $list = $(list);
15950                var categoryViewAll = $list.next('.view-all-mobile');
15951                var categoryViewAllButton = categoryViewAll.find('button');
15952                categoryViewAll.unbind('click');
15953
15954                if (isMobile) {
15955                    var addressListings = $list.find('.address-listing').filter(':visible');
15956
15957                    if (addressListings.length > numberOfListingsToShow) {
15958                        categoryViewAll.show();
15959                        var heightToShow = 0;
15960
15961                        for (var count = 0; count < numberOfListingsToShow; count++) {
15962                            heightToShow += $(addressListings[count]).outerHeight();
15963                        }
15964                        heightToShow += addressListings.siblings('.location-category-title').height() + 12;
15965
15966                        var hideListings = function () {
15967                            $list.removeClass('open');
15968                            $list.css({
15969                                'height': heightToShow + 'px',
15970                                'overflow': 'hidden'
15971                            });
15972                            categoryViewAllButton.text(showMoreCategoriesButtonText);
15973                        };
15974                        var showAllListings = function () {
15975                            $list.addClass('open');
15976                            $list.css('height', 'auto');
15977                            categoryViewAllButton.text(showLessCategoriesButtonText);
15978                        };
15979                        var toggleHeights = function () {
15980                            if ($list.hasClass('open')) {
15981                                hideListings();
15982                            } else {
15983                                showAllListings();
15984                            }
15985                        };
15986
15987                        hideListings();
15988                        categoryViewAll.on('click', toggleHeights);
15989                    }
15990                    else {
15991                        categoryViewAll.hide();
15992                        $list.css('height', '');
15993                    }
15994                } else {
15995                    categoryViewAll.hide();
15996                    $list.css('height', '');
15997                }
15998            });
15999        }
16000
16001        sizeListings();
16002        $(window).on('resize', sizeListings);
16003    },
16004
16005    closeMarker: function (marker, useCircles) {
16006        var self = this;
16007
16008        if (marker) {
16009            var markerSVG = self.markerToSVG(marker, useCircles);
16010            var newIcon = {
16011                url: 'data:image/svg+xml;charaset=UTF-8;base64,' + btoa(markerSVG)
16012            };
16013
16014            return newIcon;
16015        }
16016
16017        return null;
16018    },
16019
16020    openMarker: function (marker) {
16021        var self = this;
16022
16023        if (marker) {
16024            var markerSVG = self.markerToSVG(marker, false);
16025
16026            var newIcon = {
16027                url: 'data:image/svg+xml;charaset=UTF-8;base64,' + btoa(markerSVG),
16028                scaledSize: self.bigSize.size,
16029                labelOrigin: self.bigSize.labelSize
16030            };
16031
16032            return newIcon;
16033        }
16034
16035        return null;
16036    },
16037
16038    markerToSVG: function (marker, useCircles) {
16039        var self = this;
16040        var label = marker.label;
16041        var labelText = label ? label.text : "";
16042        var newStyle = this.newStyleBool;
16043        var color = marker.mapcolor ? marker.mapcolor : 'red';
16044    
16045        if (useCircles) {
16046            if (labelText && newStyle) {
16047                return self.getMarkerSVG('circle-ns', color);
16048            } else {
16049                if (labelText && !newStyle) {
16050                    return self.getMarkerSVG('circle', color);
16051                }
16052                if (!labelText && newStyle) {
16053                    return self.getMarkerSVG('star-circle-ns', color);
16054                }
16055                if (!labelText && !newStyle) {
16056                    return self.getMarkerSVG('star-circle', color);
16057                }
16058            }
16059        } else {
16060            if (labelText && newStyle) {
16061                return self.getMarkerSVG('pin-ns', color);
16062            } else {
16063                if (labelText && !newStyle) {
16064                    return self.getMarkerSVG('pin', color);
16065                }
16066                if (!labelText && newStyle) {
16067                    return self.getMarkerSVG('star-pin-ns', color);
16068                }
16069                if (!labelText && !newStyle) {
16070                    return self.getMarkerSVG('star-pin', color);
16071                }
16072            }
16073        }
16074    },
16075
16076    getMarkerSVG: function (type, color) {
16077        var svgStyles = '<style>.svg-fill{fill:#8c1515}.svg-fill.withborder{stroke:#8c1515}.svg-fill.withborder.nolabel{fill:#ffffff;}.svg-fill.sandhill{fill:#b3995d}.svg-fill.sandhill.withborder{stroke:#b3995d}.svg-fill.paloAlto{fill:#175e54}.svg-fill.paloAlto.withborder{stroke:#175e54}.svg-fill.teal{fill:#00505c}.svg-fill.teal.withborder{stroke:#00505c}.svg-fill.purple{fill:#53284f}.svg-fill.purple.withborder{stroke:#53284f}.svg-fill.redwood{fill:#8d3c1e}.svg-fill.redwood.withborder{stroke:#8d3c1e}.svg-fill.brown{fill:#5e3032}.svg-fill.brown.withborder{stroke:#5e3032}.svg-fill.sky{fill:#0098db}.svg-fill.sky.withborder{stroke:#0098db}.svg-fill.lagunita{fill:#007c92}
16077.svg-fill.lagunita.withborder{stroke:#007c92}.svg-fill.mint{fill:#009b76}.svg-fill.mint.withborder{stroke:#009b76}.svg-fill.white{fill:#ffffff}.svg-fill.white.withborder{stroke:#ffffff}.svg-fill.spirited{fill:#E04F39}.svg-fill.spirited.withborder{stroke:#E04F39}.svg-fill.sand{fill:#b3995d}.svg-fill.sand.withborder{stroke:#b3995d}.svg-fill.warmgrey{fill:#928b81}.svg-fill.warmgrey.withborder{stroke:#928b81}.svg-fill.lightcardinal{fill:#B83A4B}.svg-fill.lightcardinal.withborder{stroke:#B83A4B}.svg-fill.gold{fill:#b26f16}.svg-fill.gold.withborder{stroke:#b26f16}.svg-fill.poppy{fill:#e98300}.svg-fill.poppy.withborder{stroke:#e98300}.svg-fill.sun{fill:#eaab00}.svg-fill.sun.withborder{stroke:#eaab00}.svg-fill.brick{fill:#651C32}.svg-fill.brick.withborder{stroke:#651C32}</style>';
16078        var xmlDeclaration = '<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" x="0" y="0" viewBox="0 0 34.2 50.1" style="enable-background:new 0 0 34.2 50.1;" xml:space="preserve">';
16079        var markerSVG = xmlDeclaration + svgStyles;
16080        var innerSVG = "";
16081
16082        switch (type) {
16083            case 'circle-ns':
16084                innerSVG = '<circle class="svg-fill withborder ' + color + ' nolabel" cx="17.1" stroke-width="4" cy="17.1" r="13"/>';
16085                break;
16086            case 'star-circle-ns':
16087                innerSVG = '<circle class="svg-fill withborder ' + color + ' nolabel" cx="17.1" stroke-width="4" cy="17.1" r="13"/> '+
16088                    '<g id="map_star_2_">' +
16089                        '<g><polygon fill="#000" points="17.1,8.9 15.5,13.9 10.2,13.9 14.4,17.1 12.8,22.2 17.1,19 21.4,22.2 19.8,17.1 24.1,13.9 18.8,13.9"/></g>' +
16090                    '</g>';
16091                break;
16092            case 'pin-ns':
16093                innerSVG = '<path class="svg-fill ' + color + '" d="M34.2,17.1c0,9.5-17.1,32.9-17.1,32.9S0,26.6,0,17.1S7.7,0,17.1,0S34.2,7.7,34.2,17.1z"/>' +
16094                    '<circle class="svg-fill white" cx="17.1" cy="17.1" r="13"/> ';
16095                break;
16096            case 'star-pin-ns':
16097                innerSVG = '<path class="svg-fill ' + color + '" d="M34.2,17.1c0,9.5-17.1,32.9-17.1,32.9S0,26.6,0,17.1S7.7,0,17.1,0S34.2,7.7,34.2,17.1z"/>' +
16098                    '<circle class="svg-fill withborder white" cx="17.1" cy="17.1" r="13"/> ' +
16099                    '<g id="map_star_2_">' +
16100                    '<g><polygon fill="#000" points="17.1,8.9 15.5,13.9 10.2,13.9 14.4,17.1 12.8,22.2 17.1,19 21.4,22.2 19.8,17.1 24.1,13.9 18.8,13.9"/></g>' +
16101                    '</g>';
16102                break;
16103            case 'circle':
16104                innerSVG = '<circle class="svg-fill withborder ' + color + '" cx="17.1" stroke-width="4" cy="17.1" r="13"/>';
16105                break;
16106            case 'star-circle':
16107                innerSVG = '<circle class="svg-fill withborder ' + color + ' nolabel" cx="17.1" stroke-width="4" cy="17.1" r="13"/> '+
16108                  '<g id="map_star_2_">' +
16109                  '<g><polygon fill="#000" points="17.1,8.9 15.5,13.9 10.2,13.9 14.4,17.1 12.8,22.2 17.1,19 21.4,22.2 19.8,17.1 24.1,13.9 18.8,13.9"/></g>' +
16110                  '</g>';
16111                break;
16112            case 'pin':
16113                innerSVG = '<path class="svg-fill ' + color + '" d="M34.2,17.1c0,9.5-17.1,32.9-17.1,32.9S0,26.6,0,17.1S7.7,0,17.1,0S34.2,7.7,34.2,17.1z"/>' +
16114                  '<circle class="svg-fill ' + color + '" cx="17.1" cy="17.1" r="13"/> ';
16115                break;
16116            case 'star-pin':
16117            default:
16118                innerSVG = '<path class="svg-fill ' + color + '" d="M34.2,17.1c0,9.5-17.1,32.9-17.1,32.9S0,26.6,0,17.1S7.7,0,17.1,0S34.2,7.7,34.2,17.1z"/>' +
16119                  '<circle class="svg-fill withborder white" cx="17.1" cy="17.1" r="13"/> ' +
16120                  '<g id="map_star_2_">' +
16121                  '<g><polygon fill="#000" points="17.1,8.9 15.5,13.9 10.2,13.9 14.4,17.1 12.8,22.2 17.1,19 21.4,22.2 19.8,17.1 24.1,13.9 18.8,13.9"/></g>' +
16122                  '</g>';
16123                break;
16124        }
16125
16126        markerSVG += innerSVG;
16127        markerSVG += "</svg>"
16128
16129        return markerSVG;
16130    }
16131});
16132
16133shcDOMContentLoaded(function () {
16134    if (jQuery('.ease-of-access').size() > 0) {
16135        new SHC.ui.EaseOfAccess();
16136    }
16137    $('.location-category-list').each(function (idx, list) {
16138        var $list = $(list);
16139        if ($list.find('.address-listing').length > 0) {
16140            $list.show();
16141        }
16142    })
16143});
16144
16145function initializeCP16CTAButtonClickEvents() {
16146	const ctaButtons = document.querySelectorAll('a[data-cmp-category-type="find a doctor"],a[data-cmp-category-type="find a clinic"]');
16147	if (ctaButtons) {
16148		ctaButtons.forEach(
16149			function(curButton) {
16150				curButton.addEventListener("click", function(){
16151					let text = curButton.getAttribute("data-cmp-text");
16152					let categoryPrimary = curButton.getAttribute("data-cmp-category-primary");
16153					let categoryType = curButton.getAttribute("data-cmp-category-type");
16154					if (text && categoryPrimary && categoryType) {
16155						stanford.analytics.send(stanford.analytics.createComponentClickButton(text.toLowerCase(), categoryPrimary, categoryType));
16156					}
16157				});
16158		});
16159	}
16160}
16161
16162window.addEventListener('load', initializeCP16CTAButtonClickEvents);
16163shcDOMContentLoaded(function() {
16164
16165    var ConditionSpotlightCP = {
16166        init: function() {
16167            this.that = this;
16168            this.activeClass = "cs-cp-active";
16169            this.positionClassOrder = ["cs-cp-inactive-deepleft", "cs-cp-inactive-left", this.activeClass, "cs-cp-inactive-right", "cs-cp-inactive-deepright"];
16170            this.positionActiveIndex = 2;
16171
16172            this.bindEvents();
16173        },
16174
16175        bindEvents: function() {
16176            var _that = this.that;
16177            $('.condition-spotlight-cp-container:not(.health-wellness-container)').each(function(){
16178                var $this = $(this);
16179                var $controls = $this.find('.cs-cp-pagenav');
16180                var $paddles = $this.find('.cs-cp-paddles');
16181
16182                $controls.on('click', '.cs-cp-pagetoggle', function (e) {
16183                    e.preventDefault();
16184                    var newIndex = $(this).attr('data-id');
16185                    _that.turnPage($this, newIndex);
16186                });
16187            });
16188        },
16189
16190        setControls: function ($container, newIndex) {
16191
16192            var _that = this.that;
16193            var $controls = $container.find('.cs-cp-pagenav');
16194            $controls.find('.cs-cp-pagetoggle').each(function () {
16195                var $this = $(this);
16196                if($this.attr('data-id') === newIndex) {
16197                    $this.addClass(_that.activeClass);
16198                } else if ($this.hasClass(_that.activeClass)) {
16199                    $this.removeClass(_that.activeClass);
16200                }
16201            });
16202        },
16203
16204        turnPage: function ($container, newIndex) {
16205
16206            var _that = this.that;
16207            var $pages = $container.find('.cs-cp-page-container');
16208
16209            $pages.each(function() {
16210                var $this = $(this);
16211                var pageIndex = $this.attr('data-page-index');
16212                _that.positionClassOrder.forEach(function(className) {
16213                    if($this.hasClass(className)) {
16214                        $this.removeClass(className);
16215                    }
16216                });
16217                if(newIndex === pageIndex) {
16218                    $this.find('.cs-cp-whiteoverlay').addClass(_that.activeClass);
16219                } else {
16220                    $this.find('.cs-cp-whiteoverlay').removeClass(_that.activeClass);
16221                }
16222
16223                var positionIndex = 2 - newIndex;
16224                positionIndex = parseInt(positionIndex) + parseInt(pageIndex);
16225                $this.addClass(_that.positionClassOrder[positionIndex]);
16226            });
16227
16228            this.setControls($container, newIndex);
16229
16230
16231        }
16232    }.init();
16233});
16234
16235shcDOMContentLoaded(function() {
16236
16237    var ClinicalTrialsTile = {
16238
16239        init: function () {
16240            var _this = this;
16241            if(jQuery('.clinical-trials-link-container').length) {
16242                var $clinicalTrialsLinks = jQuery('.clinical-trials-link-container');
16243                $clinicalTrialsLinks.each(function() {
16244                    var $element = jQuery(this);
16245                    _this.setSummaryNumbers($element);
16246                });
16247            } 
16248            if (jQuery('.clinical-trials-tile-container').length) {
16249                var $clinicalTrialsTiles = jQuery('.clinical-trials-tile-container');
16250                $clinicalTrialsTiles.each(function() {
16251                    var $element = jQuery(this);
16252                    _this.setSummaryNumbers($element);
16253                });
16254            }
16255        },
16256
16257        setSummaryNumbers: function($element) {
16258            var hubTitle = $element.attr('data-page-title');
16259            var recruitingSum;
16260            var searchVer = document.querySelector('meta[name="shc-search-version"]').content || "v1";
16261            var recruitingSumUrl = "/bin/api/"+searchVer+"/search.json?do=organic_clinical_trials&x27=s
16261p_trialLocks&q27=" + hubTitle + "&x28=sp_status&q28=RECRUITING&general=total";
16262            jQuery.ajax({
16263                url: recruitingSumUrl,
16264                dataType: "jsonp",
16265                jsonp: 'callback',
16266                contentType: "application/json",
16267                success: function(data) {
16268                    recruitingSum = data["general"]["total"];
16269                },
16270                error: function() {
16271                    console.log("Ajax error during setSummaryNumbers");
16272                },
16273                complete: function(data){
16274                    if($element.hasClass('clinical-trials-tile-container')) {
16275                        $element.find('.clinical-trials-tile-open-trials-count').html(recruitingSum);
16276                    }
16277                }
16278            });
16279        }
16280    }.init();
16281});
16282
16283(function (SHC, jQuery) {
16284  'use strict';
16285  SHC.Namespace(SHC, 'SHC.ui.CarouselSlideshow');
16286  SHC.ui.CarouselSlideshow = new SHC.Class();
16287  SHC.ui.CarouselSlideshow.include({
16288    /*
16289     * constructor
16290     */
16291    init: function (parent) {
16292      if (Granite && Granite.author != null) {
16293        console.log('authoring env!');
16294        return;
16295      }
16296
16297      this.originalImagePanels = $('.image-panels').clone();
16298      this.window = $(window);
16299      this.carouselContainer = $('.carousel-container');
16300      this.slideContent = $('.slide-content');
16301      this.clicked = false;
16302      if (this.window.width() < 768) {
16303        this.reorganizeMarkupForMobile();
16304      }
16305      this.slide = $('.imagepanel');
16306      this.regeneratePagination();
16307      this.bindPaginationClicks();
16308      this.bindCarouselClicks();
16309      this.bindCarouselSwipes();
16310      this.setTimers();
16311      if (!jQuery('.editmode').length) {
16312        this.initSlider();
16313      }
16314      this.reorganizeMarkupOnResizeEnd();
16315      $('#main').on('click', '*[data-toggle="lightbox"]', function (e) {
16316        e.preventDefault();
16317        $(this).ekkoLightbox();
16318      });
16319    },
16320    splitImagesIntoSinglePanels: function (slideSelector, slideClass) {
16321      $(slideSelector).each(function () {
16322        var firstImage = $(this)
16323          .parent()
16324          .clone();
16325        $(this)
16326          .children('.second-img')
16327          .remove();
16328        var secondImage = $(this)
16329          .parent()
16330          .after(firstImage);
16331        firstImage.find('a:first-child').remove();
16332        firstImage.find('.slide-show-modal').removeClass('second-img');
16333        secondImage
16334          .children('figure')
16335          .removeClass(slideClass)
16336          .addClass('one-col');
16337        firstImage
16338          .children('figure')
16339          .removeClass(slideClass)
16340          .addClass('one-col');
16341      });
16342    },
16343    reorganizeMarkupForMobile: function () {
16344      // break out 50 50's and 70 30's into their own full squares
16345      this.splitImagesIntoSinglePanels('.two-col-50-50', 'two-col-50-50');
16346      this.splitImagesIntoSinglePanels('.two-col-70-30', 'two-col-70-30');
16347    },
16348    reselectElements: function () {
16349      this.carouselContainer = $('.carousel-container');
16350      this.slideContent = $('.slide-content');
16351      this.clicked = false;
16352      this.slide = $('.imagepanel');
16353    },
16354    regeneratePagination: function () {
16355      var slideLength = this.slide.length;
16356      if (slideLength > 0) {
16357        $('.pagination').remove();
16358        $('.carousel-btn').remove();
16359        var createPagination = '<span />';
16360        if (!$('.editmode').length) {
16361          this.carouselContainer
16362            .append('<nav class="pagination" />')
16363            .append('<span class="carousel-btn prev" />')
16364            .append('<span class="carousel-btn next" />');
16365        }
16366
16367        for (var i = 0; i < slideLength; i++) {
16368          $('.pagination').append(createPagination);
16369        }
16370
16371        $('.pagination')
16372          .find('span')
16373          .first()
16374          .addClass('active');
16375      }
16376    },
16377    bindPaginationClicks: function () {
16378      var that = this;
16379      $('.pagination').on('click', 'span', function () {
16380        var $this = $(this),
16381          isActive = $this.hasClass('active');
16382
16383        if (!isActive) {
16384          that.clicked = true;
16385          that.slideAnimation(false, $this);
16386        }
16387      });
16388    },
16389    bindCarouselClicks: function () {
16390      var that = this;
16391      $('.carousel-btn').on('click', function () {
16392        var $pagination = $('.pagination'),
16393          $activeSlide = $pagination.find('.active'),
16394          slideLength = that.slide.length;
16395        if ($(this).hasClass('prev')) {
16396          if ($activeSlide.index() == 0) {
16397            $pagination
16398              .find('span')
16399              .last()
16400              .trigger('click');
16401          } else {
16402            $activeSlide.prev().trigger('click');
16403          }
16404        } else {
16405          if ($activeSlide.index() == slideLength - 1) {
16406            $pagination
16407              .find('span')
16408              .first()
16409              .trigger('click');
16410          } else {
16411            $activeSlide.next().trigger('click');
16412          }
16413        }
16414      });
16415    },
16416    bindCarouselSwipes: function () {
16417      var that = this;
16418      $('.carousel-container')
16419        .off('swiperight')
16420        .on('swiperight', function () {
16421          var $pagination = $('.pagination'),
16422            $activeSlide = $pagination.find('.active'),
16423            slideLength = that.slide.length;
16424          if ($activeSlide.index() == 0) {
16425            $pagination
16426              .find('span')
16427              .last()
16428              .trigger('click');
16429          } else {
16430            $activeSlide.prev().trigger('click');
16431          }
16432        });
16433      $('.carousel-container')
16434        .off('swipeleft')
16435        .on('swipeleft', function () {
16436          var $pagination = $('.pagination'),
16437            $activeSlide = $pagination.find('.active'),
16438            slideLength = that.slide.length;
16439          if ($activeSlide.index() == slideLength - 1) {
16440            $pagination
16441              .find('span')
16442              .first()
16443              .trigger('click');
16444          } else {
16445            $activeSlide.next().trigger('click');
16446          }
16447        });
16448    },
16449    initSlider: function () {
16450      var isActive = this.carouselContainer.hasClass('active');
16451      if (!isActive) {
16452        this.carouselContainer.addClass('active');
16453      }
16454      this.setPrevNext(0);
16455    },
16456    setPrevNext: function (currentIdx) {
16457      $('.imagepanel')
16458        .removeClass('prev-slide')
16459        .removeClass('next-slide')
16460        .removeClass('current-slide');
16461      var slideSize = this.slide.length;
16462      var prevIdx;
16463      var nextIdx;
16464      if (slideSize == 1) {
16465        return; //this is pointless
16466      } else if (slideSize == 2) {
16467        if (currentIdx == 0) {
16468          prevIdx = 1;
16469          nextIdx = 1;
16470        } else {
16471          prevIdx = 0;
16472          nextIdx = 0;
16473        }
16474      } else {
16475        prevIdx = currentIdx - 1;
16476        nextIdx = currentIdx + 1;
16477        if (prevIdx < 0) {
16478          prevIdx = slideSize - 1;
16479        }
16480        if (nextIdx >= slideSize) {
16481          nextIdx = 0;
16482        }
16483      }
16484      var prevSlide = $(this.slide[prevIdx]);
16485      var nextSlide = $(this.slide[nextIdx]);
16486      var curSlide = $(this.slide[currentIdx]);
16487
16488      if (!$('.editmode').length) {
16489        prevSlide
16490          .show()
16491          .addClass('prev-slide')
16492          .find('a')
16493          .removeClass('open-modal');
16494        nextSlide
16495          .show()
16496          .addClass('next-slide')
16497          .find('a')
16498          .removeClass('open-modal');
16499        curSlide
16500          .addClass('current-slide')
16501          .find('a')
16502          .addClass('open-modal');
16503      }
16504      //new SHC.ui.Modal(".slide .open-modal");
16505    },
16506    slideAnimation: function (timer, obj) {
16507      $('.carouselslideshow .imagepanel').each(function () {
16508        $(this).hide();
16509      });
16510      var $this = obj;
16511      var currentIdx = $this.siblings('.active').index(),
16512        newIdx = $this.index();
16513
16514      if (timer == true) {
16515        $this.trigger('click');
16516        this.clicked = false;
16517      }
16518      if (this.slideContent.length > 1) {
16519        this.carouselContainer.removeClass('active');
16520        $this
16521          .addClass('active')
16522          .siblings('.active')
16523          .removeClass('active');
16524        this.slide.eq(newIdx).show();
16525      }
16526      this.setPrevNext(newIdx);
16527    },
16528    reorganizeMarkupOnResizeEnd: function () {
16529      var that = this;
16530      this.window.on('resizeEnd', function () {
16531        if (that.window.width() > 767) {
16532          // put things back to normal
16533          $('.image-panels').remove();
16534          $('.items').append(that.originalImagePanels);
16535          that.originalImagePanels = $('.image-panels').clone();
16536          // reselect things
16537          that.reselectElements();
16538          that.regeneratePagination();
16539          that.bindPaginationClicks();
16540          that.bindCarouselClicks();
16541          that.bindCarouselSwipes();
16542          that.initSlider();
16543          $('.carousel-btn.next').click();
16544        } else {
16545          // break out 50 50's and 70 30's into their own full squares
16546          that.reorganizeMarkupForMobile();
16547          // reselect things
16548          that.reselectElements();
16549          that.regeneratePagination();
16550          that.bindPaginationClicks();
16551          that.bindCarouselClicks();
16552          that.bindCarouselSwipes();
16553          that.initSlider();
16554          $('.carousel-btn.next').click();
16555        }
16556      });
16557    },
16558    setTimers: function () {
16559      var that = this;
16560      var $timedCarousel = $('.timed-carousel');
16561
16562      if ($timedCarousel.length) {
16563        var setSlideTimer = function () {
16564          var $currentSlide = $timedCarousel.find('.current-slide .slide');
16565          var slideTimer = $currentSlide.attr('data-slide-timer');
16566
16567          setTimeout(
16568            function () {
16569              var $pagination = $('.pagination'),
16570                $activeSlide = $pagination.find('.active'),
16571                slideLength = that.slide.length;
16572              if ($activeSlide.index() == slideLength - 1) {
16573                $pagination
16574                  .find('span')
16575                  .first()
16576                  .trigger('click');
16577              } else {
16578                $activeSlide.next().trigger('click');
16579              }
16580              setSlideTimer();
16581            },
16582            slideTimer ? slideTimer : 6000
16583          );
16584        }
16585        setSlideTimer();
16586      }
16587    }
16588  });
16589})(SHC, jQuery);
16590
16591shcDOMContentLoaded(function () {
16592  new SHC.ui.CarouselSlideshow();
16593});
16594
16595shcDOMContentLoaded(function() {
16596
16597        var searchVer = document.querySelector('meta[name="shc-search-version"]').content || "v1";
16598        var DoctorCount = {
16599            cachedSearchServletUrl: "/bin/api/"+searchVer+"/search.json?do=organic_phys",
16600            primaryCareSpecialties: ["Pediatrics", "Primary%20Care", "Pediatrician", "Primary%20care%20doctor"], //same list as is used for doctor specialty filter
16601
16602            init: function () {
16603
16604                var $that = this;
16605                var $doctorCountContainers = $('.doctor-count-container');
16606                $doctorCountContainers.each( function (element, index) {
16607                    var $this = $(this);
16608                    var $anchor = $this.find('.doctor-count-countanchor');
16609                    $that.getDoctorCount($anchor);
16610
16611                    if (index == $doctorCountContainers.length - 1) {
16612                        $this.find('.doctor-count-horizontal-rule').addClass('hidden');
16613                    }
16614                });
16615
16616                return this;
16617            },
16618
16619            getDoctorCount: function ($that) {
16620
16621                var url = this.cachedSearchServletUrl;
16622                var $componentDiv = $that.closest('.doctor-count-container');
16623                var $doctorLink = $that.closest('.doctor-count-countanchor');
16624                var title = encodeURIComponent($componentDiv.attr("data-page-header"));
16625                var overrideTitle = $doctorLink.attr("data-clinic-override-title");
16626                var specialty = encodeURIComponent($componentDiv.attr("data-specialty"));
16627                var expertise = encodeURIComponent($componentDiv.attr("data-expertise"));
16628                var _this = this;
16629
16630                if (typeof title !== "undefined" || typeof overrideTitle !== "undefined") {
16631                    if(typeof overrideTitle !== "undefined"){
16632                        url += "&x22=sp_clinics&q22=" + overrideTitle;
16633                    }else if(!$componentDiv.hasClass('display-all-doctors')) {
16634                        url += "&x22=sp_clinics&q22=" + title;
16635                    }
16636
16637                    if (specialty !== "undefined") {
16638                        if (specialty !== "Advanced%20Practice%20Provider") {
16639                            url += "&x2=sp_dr_title_groups&q2=" + specialty;
16640                            if (_this.primaryCareSpecialties.indexOf(specialty) > -1) {
16641                                url += "&x1=sp_prim_care_phy&q1=true";
16642                            } else {
16643                                url += "&x1=sp_spec_care_phy&q1=true";
16644                            }
16645                        } else {
16646                            url += "&x2=sp_isapp&q2=true";
16647                        }
16648                        if (expertise !== "undefined") {
16649                            url += "&x3=sp_dr_titles&q3=" + expertise;
16650                        }
16651                        $.ajax({
16652                            dataType: "jsonp",
16653                            url: url,
16654                            async: false,
16655                            success: function (data) {
16656                                _this.setDoctorCount(data, $that);
16657                                _this.setAnchorHref($that);
16658                                if(data.general['total'] == 0) {
16659                                    $doctorLink.addClass('hidden');
16660                                }
16661                            },
16662                            error: function () {
16663                                $componentDiv.addClass('hidden');
16664                            }
16665                        });
16666                    } else {
16667                        $componentDiv.addClass('hidden');
16668                    }
16669                }
16670            },
16671
16672            setDoctorCount: function (data, $that) {
16673
16674                $that.text($that.text().replace(/(\{\{0\}\}|\{0\})/g, data.general['total'])) //TODO update this once it has the correct number
16675            },
16676
16677            setAnchorHref: function ($that) {
16678                var isTrivalley = window.location.pathname.includes('tri-valley') || window.location.pathname.includes('valleycare');
16679                var pagePath = window.location.pathname.replace('/content/shc/en','');
16680                var $componentDiv = $that.closest('.doctor-count-container');
16681                var pageTitle = encodeURIComponent($componentDiv.attr("data-page-header"));
16682                var clinicOverrideTitle = $that.closest('.doctor-count-countanchor').attr("data-clinic-override-title");
16683                var specialty = encodeURIComponent($componentDiv.attr("data-specialty"));
16684                var expertise = encodeURIComponent($componentDiv.attr("data-expertise"));
16685
16686                var url = SHC.ui.Search.DirectoryUtil.guidedDirectoryURL;
16687                if (isTrivalley && url.includes('/content/shc/en')) {
16688                    url = url.replace('/content/shc/en','/tri-valley');
16689                } else if (isTrivalley && !url.includes('/tri-valley')) {
16690                    url = '/tri-valley' + url;
16691                }
16692
16693                //When using the override, the title portion will not correspond to the clinic path being passed, we want to use a clinic to get search results
16694                //but the link should take you originating page and not the clinic used for the search
16695                if(typeof clinicOverrideTitle !=='undefined'){
16696                    pagePath = "/title-override/" + pageTitle  + " AT " + clinicOverrideTitle + /title-override/ + pagePath;
16697                    url += "/&sp_clinics%7C" + pagePath + "%5E" + clinicOverrideTitle;
16698                }else if(!$componentDiv.hasClass('display-all-doctors')) {
16699                    url += "/&sp_clinics%7C" + pagePath + "%5E" + pageTitle;
16700                }
16701
16702                if(this.primaryCareSpecialties.indexOf(specialty) > -1){
16703                    url += "#x1=sp_prim_care_phy&q1=true";
16704                }else{
16705                    url += "#x1=sp_spec_care_phy&q1=true";
16706                }
16707
16708                if (specialty !== "undefined") {
16709                    if (specialty !== "Advanced%20Practice%20Provider") {
16710                        url += "&x2=sp_dr_title_groups&q2=" + specialty;
16711                    } else {
16712                        url += "&sp_x_2=sp_isapp&sp_q_exact_2=true";
16713                    }
16714                    if (expertise !== "undefined") {
16715                        url += "&x3=sp_dr_titles&q3=" + expertise;
16716                    }
16717                }
16718
16719                $that.attr('href', url);
16720                $that.attr('onclick', SHC.util.setCookie("activeView", "list", 1, "/"));
16721            }
16722
16723        }.init();
16724});
16725
16726shcDOMContentLoaded(function () {
16727    if ($('.care-team-tab-container').length) {
16728        SHC.util.clickAnchorTab();
16729
16730        SHC.util.clickInternalAnchorTab();
16731        var firstClick = false;
16732
16733        var doCloneContent = function (that) {
16734            var $that = $(that),
16735                newIndex = $that.data('tab-index'),
16736                content = $that.find(".tab-content"),
16737                container = $that.closest(".care-team-tab-container"),
16738                mobile1 = container.find('.tab-area-1-mobile'),
16739                mobile2 = container.find('.tab-area-2-mobile'),
16740                mobile3 = container.find('.tab-area-3-mobile'),
16741                mobile4 = container.find('.tab-area-4-mobile'),
16742                desktopContainer = container.find('.tab-area-desktop');
16743
16744            container.attr('data-tab-active', newIndex);
16745            $that.parent().find('.tab-nav-content.active').removeClass('active');
16746            $that.addClass('active');
16747            mobile1.empty();
16748            mobile2.empty();
16749            mobile3.empty();
16750            mobile4.empty();
16751
16752            if (container.hasClass("two-tab")) {
16753                if (newIndex == 0) {
16754                    content.clone().appendTo(mobile1);
16755                    if (container.hasClass("mobile-second")) {
16756                        container.removeClass("mobile-second");
16757                    }
16758                    container.addClass("mobile-first");
16759                } else {
16760                    content.clone().appendTo(mobile2);
16761                    if (container.hasClass("mobile-first")) {
16762                        container.removeClass("mobile-first");
16763                    }
16764                    container.addClass("mobile-second");
16765                }
16766            } else if (container.hasClass("three-tab")) {
16767                if (newIndex == 0) {
16768                    content.clone().appendTo(mobile1);
16769                    if (container.hasClass("mobile-second")) {
16770                        container.removeClass("mobile-second");
16771                    } else if (container.hasClass("mobile-third")) {
16772                        container.removeClass("mobile-third");
16773                    }
16774                    container.addClass("mobile-first");
16775
16776                } else if (newIndex == 1) {
16777                    content.clone().appendTo(mobile2);
16778                    if (container.hasClass("mobile-first")) {
16779                        container.removeClass("mobile-first");
16780                    } else if (container.hasClass("mobile-third")) {
16781                        container.removeClass("mobile-third");
16782                    }
16783                    container.addClass("mobile-second");
16784
16785                } else {
16786                    content.clone().appendTo(mobile3);
16787                    if (container.hasClass("mobile-first")) {
16788                        container.removeClass("mobile-first");
16789                    } else if (container.hasClass("mobile-second")) {
16790                        container.removeClass("mobile-second");
16791                    }
16792                    container.addClass("mobile-third");
16793
16794                }
16795            } else {
16796                if (newIndex == 0 || newIndex == 1) {
16797                    content.clone().appendTo(mobile2);
16798                    if (container.hasClass("mobile-first")) {
16799                        container.removeClass("mobile-first");
16800                    } else if (container.hasClass("mobile-third")) {
16801                        container.removeClass("mobile-third");
16802                    } else if (container.hasClass("mobile-fourth")) {
16803                        container.removeClass("mobile-fourth");
16804                    }
16805                    container.addClass("mobile-second");
16806                } else {
16807                    content.clone().appendTo(mobile4);
16808                    if (container.hasClass("mobile-first")) {
16809                        container.removeClass("mobile-first");
16810                    } else if (container.hasClass("mobile-second")) {
16811                        container.removeClass("mobile-second");
16812                    } else if (container.hasClass("mobile-third")) {
16813                        container.removeClass("mobile-third");
16814                    }
16815                    container.addClass("mobile-fourth");
16816
16817                }
16818            }
16819            if (firstClick && SHC.ui.screenMode === "small") {
16820                $('html, body').animate({
16821                    scrollTop: $that.offset().top + ($that.height() / 2)
16822                }, 500);
16823            }
16824
16825            desktopContainer.empty();
16826            content.clone().appendTo(desktopContainer);
16827
16828            if (content.find('.searchbar-container').length > 0) {
16829                var event = jQuery.Event('searchbarInTreatmentBox');
16830                event.desktopContainer = desktopContainer;
16831                event.mobile1 = mobile1;
16832                event.mobile2 = mobile2;
16833                event.mobile3 = mobile3;
16834                event.mobile4 = mobile4;
16835                jQuery(window).trigger(event);
16836            }
16837        }
16838        $('.not-editing.care-team-tab-container .tab-nav-content').on('click', function (event) {//For switching tabs.
16839            var $this = $(this),
16840                target = event.target,
16841                desktop = $this.closest('.care-team-tab-container').find('.tab-area-desktop');
16842            if ($(target).closest('.clone-content').length == 0) {//We are checking this to see if the 'click' came from the hidden clone-content node. Don't do following if happened.
16843                desktop.css('display', '');//this will take away the display:none from load.
16844                firstClick = true;
16845                if (!$this.hasClass("active")) {
16846                    doCloneContent(this);
16847                } else {
16848                    $this.removeClass("active");
16849                    desktop.css('display', 'none');
16850                    var container = $this.closest('.care-team-tab-container');
16851                    container.removeClass("mobile-first").removeClass("mobile-second").removeClass("mobile-third").removeClass("mobile-fourth");
16852                }
16853            }
16854
16855        });
16856
16857        $('.tab-nav-content.active').each(function () {
16858            doCloneContent(this);
16859        });
16860    }
16861});
16862
16863SHC.Namespace(SHC, "SHC.ui.AwardsCarousel");
16864SHC.ui.AwardsCarousel = new SHC.Class();
16865SHC.ui.AwardsCarousel.extend({initialized: false});
16866SHC.ui.AwardsCarousel.include({
16867
16868    init: function (selector) {
16869        this.animationDelay = 1000;
16870        this.rotateInterval = 5000;
16871        this.slideMargin = 10;
16872        this.parent = jQuery(selector);
16873        this.slides = this.parent.find(".logo-image");
16874        this.slideWindow = this.parent.find(".slide-window");
16875        this.slideStrip = this.parent.find(".slide-strip");
16876        this.leftFadeIn = this.parent.find(".slide-window .fade-left");
16877        this.rightFadeIn = this.parent.find(".slide-window .fade-right");
16878        this.slideWidth = 0;
16879        if (!SHC.ui.AwardsCarousel.initalized) {
16880            this.activate();
16881            SHC.ui.AwardsCarousel.initalized = true;
16882        }
16883    },
16884    activate: function() {
16885        var that = this;
16886        this.calculateSlideWidth();
16887        // disable animations when all slides fit on the page
16888        if (this.slideWidth < this.slideWindow.width()) {
16889            this.hideFadeIn();
16890            this.centerSlideStrip();
16891        } else {
16892            this.showFadeIn();
16893            this.startAnimation();
16894        }
16895    },
16896    calculateSlideWidth: function() {
16897        var slideWidth = 0,
16898            slides = this.parent.find(".logo-image");
16899        slides.each(function(idx, el){
16900            var slide = jQuery(el),
16901                findWidth = slide.find("a").width(),
16902                width = findWidth && (findWidth > slide.width()) ?  findWidth : slide.width();
16903            slideWidth = slideWidth + width;
16904        });
16905        this.slideWidth = (slideWidth + 20);
16906    },
16907    centerSlideStrip: function() {
16908        this.slideStrip.width(this.slideWidth);
16909        this.slideStrip.addClass("centered");
16910    },
16911    startAnimation: function() {
16912        var that = this;
16913        // no animations on wcmmode.edit
16914        if (this.parent.hasClass("edit-mode")) {
16915            return;
16916        }
16917        this.intervalHandler = setInterval(function(){
16918            that.nextSlide();
16919        }, this.rotateInterval);
16920    },
16921    stopAnimation: function() {
16922        clearInterval(this.intervalHandler);
16923    },
16924    showFadeIn: function() {
16925        this.leftFadeIn.removeClass("hidden");
16926        this.rightFadeIn.removeClass("hidden");
16927    },
16928    hideFadeIn: function() {
16929        this.leftFadeIn.addClass("hidden");
16930        this.rightFadeIn.addClass("hidden");
16931    },
16932    /**
16933     * Implement infinite loop.
16934     */
16935    fadeInNextSlide: function(){
16936        var that = this,
16937            slides = this.parent.find(".logo-image"),
16938            xPos = -1 * slides.eq(1).position().left;
16939        // detach slide in front at the end of animation
16940        // reset style attribute to prevent oscillation.
16941        this.slideStrip.transition({x: xPos}, this.animationDelay, function(){
16942            var first = slides.first();
16943            first.transition({opacity:0}, 0);
16944            first.detach();
16945            that.slideStrip.removeAttr("style").append(first);
16946            first.transition({opacity:1}, 500);
16947        });
16948    },
16949    nextSlide: function(){
16950        var that = this,
16951            slides = this.parent.find(".logo-image"),
16952            xPos = -1 * slides.eq(1).position().left;
16953        var clone = slides.first().clone();
16954        clone.transition({opacity:0}, 0);
16955        this.slideStrip.append(clone);
16956        clone.transition({opacity:1}, 500);
16957        this.slideStrip.transition({x: xPos}, this.animationDelay, function(){
16958            var first = slides.first();
16959            first.transition({opacity:0}
16959, 0);
16960            first.remove();
16961            that.slideStrip.removeAttr("style");
16962        });
16963    }
16964});
16965/*******************************************************************************
16966 * Copyright 2018 Adobe
16967 *
16968 * Licensed under the Apache License, Version 2.0 (the "License");
16969 * you may not use this file except in compliance with the License.
16970 * You may obtain a copy of the License at
16971 *
16972 *     http://www.apache.org/licenses/LICENSE2.0
16973 *
16974 * Unless required by applicable law or agreed to in writing, software
16975 * distributed under the License is distributed on an "AS IS" BASIS,
16976 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16977 * See the License for the specific language governing permissions and
16978 * limitations under the License.
16979 ******************************************************************************/
16980
16981/**
16982 * Element.matches()
16983 * https://developer.mozilla.org/enUS/docs/Web/API/Element/matches#Polyfill
16984 */
16985if (!Element.prototype.matches) {
16986    Element.prototype.matches = Element.prototype.msMatchesSelector || Element.prototype.webkitMatchesSelector;
16987}
16988
16989// eslint-disable-next-line valid-jsdoc
16990/**
16991 * Element.closest()
16992 * https://developer.mozilla.org/enUS/docs/Web/API/Element/closest#Polyfill
16993 */
16994if (!Element.prototype.closest) {
16995    Element.prototype.closest = function(s) {
16996        "use strict";
16997        var el = this;
16998        if (!document.documentElement.contains(el)) {
16999            return null;
17000        }
17001        do {
17002            if (el.matches(s)) {
17003                return el;
17004            }
17005            el = el.parentElement || el.parentNode;
17006        } while (el !== null && el.nodeType === 1);
17007        return null;
17008    };
17009}
17010
17011/*******************************************************************************
17012 * Copyright 2020 Adobe
17013 *
17014 * Licensed under the Apache License, Version 2.0 (the "License");
17015 * you may not use this file except in compliance with the License.
17016 * You may obtain a copy of the License at
17017 *
17018 *     http://www.apache.org/licenses/LICENSE-2.0
17019 *
17020 * Unless required by applicable law or agreed to in writing, software
17021 * distributed under the License is distributed on an "AS IS" BASIS,
17022 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17023 * See the License for the specific language governing permissions and
17024 * limitations under the License.
17025 ******************************************************************************/
17026(function() {
17027    "use strict";
17028
17029    window.CQ = window.CQ || {};
17030    window.CQ.CoreComponents = window.CQ.CoreComponents || {};
17031    window.CQ.CoreComponents.container = window.CQ.CoreComponents.container || {};
17032    window.CQ.CoreComponents.container.utils = {};
17033
17034    /**
17035     * Utilities for Container Components (accordion, tabs)
17036     *
17037     * @namespace
17038     * @alias CQ.CoreComponents.container.utils
17039     * @type {{}}
17040     */
17041    CQ.CoreComponents.container.utils = {
17042
17043        /**
17044         * Returns index of the container component item (accordion, tabs) that corresponds to the deep link in the URL fragment.
17045         *
17046         * @param {Object} component The Accordion or Tabs component.
17047         * @param {String} itemType The type of the item as defined in the component.
17048         * @returns {Number} the index within the items array if the item exists, -1 otherwise.
17049         */
17050        getDeepLinkItemIdx: function(component, itemType) {
17051            if (window.location.hash) {
17052                var deepLinkId = window.location.hash.substring(1);
17053                if (document.getElementById(deepLinkId) &&
17054                    deepLinkId && component &&
17055                    component._config && component._config.element && component._config.element.id &&
17056                    component._elements && component._elements[itemType] &&
17057                    deepLinkId.indexOf(component._config.element.id + "-item-") === 0) {
17058                    for (var i = 0; i < component._elements[itemType].length; i++) {
17059                        var item = component._elements[itemType][i];
17060                        if (item.id === deepLinkId) {
17061                            return i;
17062                        }
17063                    }
17064                }
17065                return -1;
17066            }
17067        },
17068
17069        /**
17070         * Returns the item of the container component (accordion, tabs) that corresponds to the deep link in the URL fragment.
17071         *
17072         * @param {Object} component The Accordion or Tabs component.
17073         * @param {String} itemType The type of the item as defined in the component.
17074         * @returns {Object} the item if it exists, undefined otherwise.
17075         */
17076        getDeepLinkItem: function(component, itemType) {
17077            var idx = CQ.CoreComponents.container.utils.getDeepLinkItemIdx(component, itemType);
17078            if (component && component._elements && component._elements[itemType]) {
17079                return component._elements[itemType][idx];
17080            }
17081        }
17082
17083    };
17084}());
17085
17086/*******************************************************************************
17087 * Copyright 2018 Adobe
17088 *
17089 * Licensed under the Apache License, Version 2.0 (the "License");
17090 * you may not use this file except in compliance with the License.
17091 * You may obtain a copy of the License at
17092 *
17093 *     http://www.apache.org/licenses/LICENSE-2.0
17094 *
17095 * Unless required by applicable law or agreed to in writing, software
17096 * distributed under the License is distributed on an "AS IS" BASIS,
17097 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17098 * See the License for the specific language governing permissions and
17099 * limitations under the License.
17100 ******************************************************************************/
17101/* global
17102    CQ
17103 */
17104(function ($) {
17105    "use strict";
17106    var containerUtils = window.CQ && window.CQ.CoreComponents && window.CQ.CoreComponents.container && window.CQ.CoreComponents.container.utils ? window.CQ.CoreComponents.container.utils : undefined;
17107    if (!containerUtils) {
17108        // eslint-disable-next-line no-console
17109        console.warn("Tabs: container utilities at window.CQ.CoreComponents.container.utils are not available. This can lead to missing features. Ensure the core.wcm.components.commons.site.container client library is included on the page.");
17110    }
17111
17112    var dataLayerEnabled;
17113    var dataLayer;
17114    var screenMode;
17115    var screenWidth;
17116
17117    var NS = "cmp";
17118    var IS = "tabs";
17119
17120    var keyCodes = {
17121        END: 35,
17122        HOME: 36,
17123        ARROW_LEFT: 37,
17124        ARROW_UP: 38,
17125        ARROW_RIGHT: 39,
17126        ARROW_DOWN: 40
17127    };
17128
17129    var selectors = {
17130        self: "[data-" + NS + '-is="' + IS + '"]',
17131        active: {
17132            tab: "cmp-tabs__tab--active",
17133            tabpanel: "cmp-tabs__tabpanel--active"
17134        }
17135    };
17136    var screenSizes = {
17137        "medium": 768,
17138        "large": 1024
17139    };
17140
17141    function detectScreenMode() {
17142        screenWidth = $(window).width();
17143        if (screenWidth < screenSizes.medium) {
17144            screenMode = "small";
17145        } else if (screenWidth >= screenSizes.medium && screenWidth < screenSizes.large) {
17146            screenMode = "medium";
17147        } else {
17148            screenMode = "large";
17149        }
17150    }
17151
17152    function resetActiveTab(screenMode) {
17153        var screensize = screenMode === "small" ? "mobile" : "desktop";
17154        var $tabList = $('.cmp-tabs__tablist.' + screensize);
17155        $tabList.each(function(i, element){
17156            var $activeTab = $(element).find('.cmp-tabs__tab').first();
17157            $activeTab.trigger('click');
17158            isMobileDropdown(null, $(this));
17159        });
17160    }
17161
17162    function checkHiddenTabs(event) {
17163        var tabsContainer = event.currentTarget.closest('.cmp-tabs');
17164        var fifthTab = tabsContainer.querySelector('.cmp-tabs__tab.fifth-tab');
17165        var isTabsDesign = tabsContainer.classList.contains('tab-design');
17166        var isDropdownTab = event.currentTarget.classList.contains("dropdown-tab");
17167        var isDropdownItem = event.currentTarget.classList.contains("dropdown-item");
17168        var isHiddenTab = event.currentTarget.classList.contains('hidden-dropdown');
17169        var hiddenDropdown = tabsContainer.querySelector('.hidden-dropdown');
17170        var activeDropdown = tabsContainer.querySelector('.active-dropdown');
17171
17172        if (isDropdownItem && !isHiddenTab) {
17173            activeDropdown.dataset['tabIndex'] = event.currentTarget.dataset['tabIndex'];
17174            activeDropdown.innerHTML = event.currentTarget.innerHTML.trim();
17175            activeDropdown.classList.add('active');
17176            fifthTab.classList.add('hidden');
17177            hiddenDropdown.classList.add('active');
17178        } else {
17179            if (!isDropdownTab && isTabsDesign) {
17180                activeDropdown.dataset['tabIndex'] = "0";
17181                activeDropdown.innerHTML = "Hidden Tab";
17182                activeDropdown.classList.remove('active');
17183                fifthTab.classList.remove('hidden');
17184                hiddenDropdown.classList.remove('active');
17185            }
17186        }
17187    }
17188
17189    function activeTabOnload (element) {
17190        var isTabsDesign = $(element).closest('.cmp-tabs').hasClass('tab-design');
17191        if (isTabsDesign) {
17192            var activeTab = $(element).find('.desktop').find('.cmp-tabs__tab--active');
17193            var isDropdownItem = activeTab.hasClass('dropdown-item');
17194            if (activeTab.length > 0 && isDropdownItem ){
17195                var activeDropdown = $(element).find('.active-dropdown');
17196                $(activeDropdown).addClass('active');
17197                $(activeDropdown).data('tab-index', $(activeTab).data('tab-index'));
17198                $(activeDropdown).text($(activeTab)[0].innerHTML.trim());
17199            }
17200        }
17201    }
17202
17203    function isDropdownOpen(event) {
17204        var isTabsDesign = event.currentTarget.closest('.tab-design') !== null;
17205        var isDropdownTab = event.currentTarget.classList.contains("dropdown-tab");
17206        if (isTabsDesign) {
17207            var dropdownTab = event.currentTarget.closest('.tab-design').querySelector('.dropdown-tab');
17208            if (dropdownTab) {
17209                !dropdownTab.classList.contains('open') && isDropdownTab ? dropdownTab.classList.add('open') : dropdownTab.classList.remove('open');
17210            }
17211        }
17212    }
17213
17214    function isMobileDropdown(event, element) {
17215        var $selectContainer;
17216        var screensize = screenMode === "small" ? "mobile" : "desktop";
17217        var isMobileDropdown = event != null ? event.currentTarget.parentElement.classList.contains('dropdown-content'): $(element).closest('.dropdown-content').length > 0;
17218        if (isMobileDropdown && screensize === "mobile") {
17219            if (event != null) {
17220                $selectContainer = event.currentTarget.closest('.cmp-tabs__tablist').querySelector('.select-container');
17221                $selectContainer.children[0].innerHTML = event.currentTarget.innerHTML;
17222                toggleDropdown(event);
17223            } else {
17224               $selectContainer =  $(element).closest('.cmp-tabs__tablist').find('.name');
17225               $selectContainer.html($(element)[0].innerHTML);
17226            }
17227        }
17228    }
17229
17230    function toggleDropdown(e) {
17231        var dropdownContent =$(e.currentTarget).parent().find('.dropdown-content');
17232        var childOfDropdown = $(e.currentTarget).closest('.dropdown-content');
17233        if ($(dropdownContent).length > 0 || childOfDropdown.length > 0) {
17234            var dropdown = $(dropdownContent).length > 0 ? dropdownContent : childOfDropdown;
17235            if ($(dropdown).hasClass('open')) {
17236                $(dropdown).slideUp(300, function () {
17237                    $(dropdown).removeClass('open');
17238                    $(e.currentTarget).removeClass('open');
17239                });
17240            } else {
17241                $(dropdown).slideDown(300, function () {
17242                    $(dropdown).addClass('open');
17243                    $(e.currentTarget).addClass('open');
17244                });
17245            }
17246        }
17247    }
17248
17249    /**
17250     * Tabs Configuration
17251     *
17252     * @typedef {Object} TabsConfig Represents a Tabs configuration
17253     * @property {HTMLElement} element The HTMLElement representing the Tabs
17254     * @property {Object} options The Tabs options
17255     */
17256
17257    /**
17258     * Tabs
17259     *
17260     * @class Tabs
17261     * @classdesc An interactive Tabs component for navigating a list of tabs
17262     * @param {TabsConfig} config The Tabs configuration
17263     */
17264    function Tabs(config) {
17265        var that = this;
17266
17267        if (config && config.element) {
17268            init(config);
17269        }
17270
17271        /**
17272         * Initializes the Tabs
17273         *
17274         * @private
17275         * @param {TabsConfig} config The Tabs configuration
17276         */
17277        function init(config) {
17278            detectScreenMode();
17279            var screensize = screenMode === "small" ? "mobile" : "desktop";
17280            that._config = config;
17281
17282            // prevents multiple initialization
17283            config.element.removeAttribute("data-" + NS + "-is");
17284
17285            cacheElements(config.element);
17286            that._active = getActiveIndex(that._elements["tab-" + screensize]);
17287
17288            if (that._elements.tabpanel) {
17289                refreshActive(config.element);
17290                activeTabOnload(config.element);
17291                bindEvents(config.element);
17292            }
17293
17294            // Show the tab based on deep-link-id if it matches with any existing tab item id
17295            if (containerUtils) {
17296                var deepLinkItemIdx = containerUtils.getDeepLinkItemIdx(that, "tab");
17297                if (deepLinkItemIdx && deepLinkItemIdx !== -1) {
17298                    var deepLinkItem = that._elements["tab"][deepLinkItemIdx];
17299                    if (deepLinkItem && that._elements["tab"][that._active].id !== deepLinkItem.id) {
17300                        navigateAndFocusTab(deepLinkItemIdx);
17301                    }
17302                }
17303            }
17304
17305            if (window.Granite && window.Granite.author && window.Granite.author.MessageChannel) {
17306                /*
17307                 * Editor message handling:
17308                 * - subscribe to "cmp.panelcontainer" message requests sent by the editor frame
17309                 * - check that the message data panel container type is correct and that the id (path) matches this specific Tabs component
17310                 * - if so, route the "navigate" operation to enact a navigation of the Tabs based on index data
17311                 */
17312                CQ.CoreComponents.MESSAGE_CHANNEL = CQ.CoreComponents.MESSAGE_CHANNEL || new window.Granite.author.MessageChannel("cqauthor", window);
17313                CQ.CoreComponents.MESSAGE_CHANNEL.subscribeRequestMessage("cmp.panelcontainer", function (message) {
17314                    if (message.data && message.data.type === "cmp-tabs" && message.data.id === that._elements.self.dataset["cmpPanelcontainerId"]) {
17315                        if (message.data.operation === "navigate") {
17316                            navigate(message.data.index);
17317                        }
17318                    }
17319                });
17320            }
17321        }
17322
17323        /**
17324         * Returns the index of the active tab, if no tab is active returns 0
17325         *
17326         * @param {Array} tabs Tab elements
17327         * @returns {Number} Index of the active tab, 0 if none is active
17328         */
17329        function getActiveIndex(tabs) {
17330            if (tabs) {
17331                for (var i = 0; i < tabs.length; i++) {
17332                    if (tabs[i].classList.contains(selectors.active.tab)) {
17333                        return i;
17334                    }
17335                }
17336            }
17337            return 0;
17338        }
17339
17340        function addClickEvent(tabs) {
17341            if (tabs) {
17342                for (var i = 0; i < tabs.length; i++) {
17343                    (function (index) {
17344                        tabs[i].addEventListener("click", function (event) {
17345                            index = index ? index : event.currentTarget.dataset['tabIndex'];
17346                            event.stopPropagation();
17347                            navigateAndFocusTab(index);
17348                            isMobileDropdown(event);
17349                            isDropdownOpen(event);
17350                            checkHiddenTabs(event);
17351                            quickNavTextWriter(event.currentTarget);
17352                        });
17353                        tabs[i].addEventListener("keydown", function (event) {
17354                            onKeyDown(event);
17355                        });
17356                    })(i);
17357                }
17358            }
17359        }
17360
17361        /**
17362         * Caches the Tabs elements as defined via the {@code data-tabs-hook="ELEMENT_NAME"} markup API
17363         *
17364         * @private
17365         * @param {HTMLElement} wrapper The Tabs wrapper element
17366         */
17367        function cacheElements(wrapper) {
17368            that._elements = {};
17369            that._elements.self = wrapper;
17370            // iterate to separate the two lists into mobile and desktop versions.
17371            var hooks = that._elements.self.querySelectorAll("[data-" + NS + "-hook-" + IS + "]");
17372            for (var i = 0; i < hooks.length; i++) {
17373                var hook = hooks[i];
17374
17375                if (hook.closest("." + NS + "-" + IS) === that._elements.self) { // only process own tab elements
17376                    var capitalized = IS;
17377                    capitalized = capitalized.charAt(0).toUpperCase() + capitalized.slice(1);
17378                    var key = hook.dataset[NS + "Hook" + capitalized];
17379                    if (that._elements[key]) {
17380                        if (!Array.isArray(that._elements[key])) {
17381                            var tmp = that._elements[key];
17382                            that._elements[key] = [tmp];
17383                        }
17384                        that._elements[key].push(hook);
17385                    } else {
17386                        that._elements[key] = hook;
17387                    }
17388                }
17389            }
17390        }
17391
17392        /**
17393         * Binds Tabs event handling
17394         *
17395         * @private
17396         */
17397        function bindEvents(tabElement) {
17398            var that = this;
17399            var tabsMobile = tabElement.querySelector('.cmp-tabs__tablist.mobile').querySelectorAll('.cmp-tabs__tab');
17400            var tabsDesktop = Array.from(tabElement.querySelector('.cmp-tabs__tablist.desktop')
17401                .querySelectorAll('.cmp-tabs__tab'))
17402                .filter(function (item) {
17403                    if (!item.classList.contains("active-dropdown") && !item.classList.contains("hidden-dropdown")) {
17404                        return item;
17405                    }
17406                });
17407            addClickEvent(tabsDesktop);
17408            addClickEvent(tabsMobile);
17409
17410            $('.hidden-dropdown, .active-dropdown').on('click', function (e) {
17411                var index = e.currentTarget.dataset['tabIndex'];
17412                e.stopPropagation();
17413                navigateAndFocusTab(index);
17414                isMobileDropdown(e);
17415                isDropdownOpen(e);
17416                checkHiddenTabs(e);
17417            });
17418        }
17419
17420        /**
17421         * Handles tab keydown events
17422         *
17423         * @private
17424         * @param {Object} event The keydown event
17425         */
17426        function onKeyDown(event) {
17427            var index = that._active;
17428            var lastIndex = that._elements["tab"].length - 1;
17429
17430            switch (event.keyCode) {
17431                case keyCodes.ARROW_LEFT:
17432                case keyCodes.ARROW_UP:
17433                    event.preventDefault();
17434                    if (index > 0) {
17435                        navigateAndFocusTab(index - 1);
17436                    }
17437                    break;
17438                case keyCodes.ARROW_RIGHT:
17439                case keyCodes.ARROW_DOWN:
17440                    event.preventDefault();
17441                    if (index < lastIndex) {
17442                        navigateAndFocusTab(index + 1);
17443                    }
17444                    break;
17445                case keyCodes.HOME:
17446                    event.preventDefault();
17447                    navigateAndFocusTab(0);
17448                    break;
17449                case keyCodes.END:
17450                    event.preventDefault();
17451                    navigateAndFocusTab(lastIndex);
17452                    break;
17453                default:
17454                    return;
17455            }
17456        }
17457
17458        /**
17459         * Refreshes the tab markup based on the current {@code Tabs#_active} index
17460         *
17461         * @private
17462         */
17463        function refreshActive(tabElement) {
17464            var screensize = screenMode === "small" ? "mobile" : "desktop";
17465            var tabpanels = tabElement["tabpanel"];
17466            var tabs = tabElement["tab-" + screensize];
17467
17468            if (tabpanels) {
17469                if (Array.isArray(tabpanels)) {
17470                    for (var i = 0; i < tabpanels.length; i++) {
17471                        if (i === parseInt(that._active)) {
17472                            tabpanels[i].classList.add(selectors.active.tabpanel);
17473                            tabpanels[i].removeAttribute("aria-hidden");
17474                            tabs[i].classList.add(selectors.active.tab);
17475                            tabs[i].setAttribute("aria-selected", true);
17476                            tabs[i].setAttribute("tabindex", "0");
17477                        } else {
17478                            tabpanels[i].classList.remove(selectors.active.tabpanel);
17479                            tabpanels[i].setAttribute("aria-hidden", true);
17480                            tabs[i].classList.remove(selectors.active.tab);
17481                            tabs[i].setAttribute("aria-selected", false);
17482                            tabs[i].setAttribute("tabindex", "-1");
17483                        }
17484                    }
17485                } else {
17486                    // only one tab
17487                    tabpanels.classList.add(selectors.active.tabpanel);
17488                    tabs.classList.add(selectors.active.tab);
17489                }
17490            }
17491        }
17492
17493        /**
17494         * Focuses the element and prevents scrolling the element into view
17495         *
17496         * @param {HTMLElement} element Element to focus
17497         */
17498        function focusWithoutScroll(element) {
17499            var x = window.scrollX || window.pageXOffset;
17500            var y = window.scrollY || window.pageYOffset;
17501            element.focus();
17502            window.scrollTo(x, y);
17503        }
17504
17505        /**
17506         * Navigates to the tab at the provided index
17507         *
17508         * @private
17509         * @param {Number} index The index of the tab to navigate to
17510         */
17511        function navigate(index) {
17512            that._active = index;
17513            refreshActive(that._elements);
17514        }
17515
17516        /**
17517         * Navigates to the item at the provided index and ensures the active tab gains focus
17518         *
17519         * @private
17520         * @param {Number} index The index of the item to navigate to
17521         */
17522        function navigateAndFocusTab(index) {
17523            var screensize = screenMode === "small" ? "mobile" : "desktop";
17524            var exActive = that._active;
17525            navigate(index);
17526            focusWithoutScroll(that._elements["tab-" + screensize][index]);
17527
17528            if (dataLayerEnabled) {
17529
17530                var activeItem = getDataLayerId(that._elements.tabpanel[index]);
17531                var exActiveItem = getDataLayerId(that._elements.tabpanel[exActive]);
17532
17533                dataLayer.push({
17534                    event: "cmp:show",
17535                    eventInfo: {
17536                        path: "component." + activeItem
17537                    }
17538                });
17539
17540                dataLayer.push({
17541                    event: "cmp:hide",
17542                    eventInfo: {
17543                        path: "component." + exActiveItem
17544                    }
17545                });
17546
17547                var tabsId = that._elements.self.id;
17548                var uploadPayload = {component: {}};
17549                uploadPayload.component[tabsId] = {shownItems: [activeItem]};
17550
17551                var removePayload = {component: {}};
17552                removePayload.component[tabsId] = {shownItems: undefined};
17553
17554                dataLayer.push(removePayload);
17555                dataLayer.push(uploadPayload);
17556            }
17557        }
17558    }
17559
17560    /**
17561     * Scrolls the browser when the URI fragment is changed to the item of the container Tab component that corresponds to the deep link in the URI fragment,
17562     and displays its content.
17563     */
17564    function onHashChange() {
17565        if (location.hash && location.hash !== "#") {
17566            var anchorLocation = decodeURIComponent(location.hash);
17567            var anchorElement = document.querySelector(anchorLocation);
17568            if (anchorElement && anchorElement.classList.contains("cmp-tabs__tab") && !anchorElement.classList.contains("cmp-tabs__tab--active")) {
17569                anchorElement.click();
17570            }
17571        }
17572    }
17573
17574    function checkForDropdown($activeTab, isNext) {
17575        if (isNext) {
17576            var isDropdownTab = $activeTab.next().hasClass('dropdown-tab');
17577            return isDropdownTab ? $activeTab.next().find('.hidden-dropdown').next().text() : $activeTab.next().text();
17578        } else {
17579            var isHiddenDropdown = $activeTab.prev().hasClass('hidden-dropdown');
17580            return isHiddenDropdown ? $activeTab.closest('.dropdown-tab').prev().text() : $activeTab.prev().text();
17581        }
17582    }
17583
17584    function quickNavClickHandler(element, isNext) {
17585        var $this = $(element),
17586            screensize = screenMode === "small" ? "mobile" : "desktop",
17587            $tabsContainer = $this.closest('.cmp-tabs'),
17588            $tabList = $tabsContainer.find('.cmp-tabs__tablist.' + screensize),
17589            $activeTab = $tabList.find('.cmp-tabs__tab--active');
17590        if ($activeTab.length < 1) {
17591            $activeTab = $tabList.find('.cmp-tabs__tab').first().addClass('cmp-tabs__tab--active');
17592        }
17593        if (isNext) {
17594            var isDropdownTab = $activeTab.next().hasClass('dropdown-tab');
17595            isDropdownTab ? $activeTab.next().find('.hidden-dropdown').next().trigger('click') : $activeTab.next().trigger('click');
17596        } else {
17597            var isHiddenDropdown = $activeTab.prev().hasClass('hidden-dropdown');
17598            isHiddenDropdown ? $activeTab.prev().closest('.dropdown-tab').prev().trigger('click') : $activeTab.prev().trigger('click');
17599        }
17600        if ($activeTab.closest('.cmp-tabs__tablist').hasClass('mobile')) {
17601            $('.dropdown-content').hide();
17602        }
17603        $tabsContainer[0].scrollIntoView();
17604        window.scrollBy(0, -25);
17605    }
17606
17607    function quickNavTextWriter(activeTab) {
17608        var $tabsContainer = $(activeTab).closest('.cmp-tabs'),
17609            $prev = $tabsContainer.find('.tabs-quick-nav-prev .text'),
17610            $next = $tabsContainer.find('.tabs-quick-nav-next .text');
17611        $prev.text(checkForDropdown($(activeTab), false));
17612        $next.text(checkForDropdown($(activeTab), true));
17613        if (!$prev.html() || $prev.html() === "&nbsp;" || $(activeTab).prev().hasClass('active-dropdown')) {
17614            $prev.parent().addClass('hidden');
17615        } else {
17616            $prev.parent().removeClass('hidden');
17617        }
17618        if (!$next.html() || $next.html() === "&nbsp;") {
17619            $next.parent().addClass('hidden');
17620        } else {
17621            $next.parent().removeClass('hidden');
17622        }
17623    }
17624
17625    function loadQuickNav() {
17626        var screensize = screenMode === "small" ? "mobile" : "desktop";
17627        var isQuickNav = $('.tabs-outer-quick-nav');
17628        var $tabList = $('.cmp-tabs__tablist.' + screensize);
17629        if (isQuickNav) {
17630            $tabList.find('.cmp-tabs__tab.cmp-tabs__tab--active').each(function (i, element) {
17631                quickNavTextWriter($(this))
17632                isMobileDropdown(null, $(this));
17633            });
17634        }
17635    }
17636
17637    /**
17638     * Reads options data from the Tabs wrapper element, defined via {@code data-cmp-*} data attributes
17639     *
17640     * @private
17641     * @param {HTMLElement} element The Tabs element to read options data from
17642     * @returns {Object} The options read from the component data attributes
17643     */
17644    function readData(element) {
17645        var data = element.dataset;
17646        var options = [];
17647        var capitalized = IS;
17648        capitalized = capitalized.charAt(0).toUpperCase() + capitalized.slice(1);
17649        var reserved = ["is", "hook" + capitalized];
17650
17651        for (var key in data) {
17652            if (data.hasOwnProperty(key)) {
17653                var value = data[key];
17654
17655                if (key.indexOf(NS) === 0) {
17656                    key = key.slice(NS.length);
17657                    key = key.charAt(0).toLowerCase() + key.substring(1);
17658
17659                    if (reserved.indexOf(key) === -1) {
17660                        options[key] = value;
17661                    }
17662                }
17663            }
17664        }
17665
17666        return options;
17667    }
17668
17669    /**
17670     * Parses the dataLayer string and returns the ID
17671     *
17672     * @private
17673     * @param {HTMLElement} item the accordion item
17674     * @returns {String} dataLayerId or undefined
17675     */
17676    function getDataLayerId(item) {
17677        if (item && item.dataset.cmpDataLayer) {
17678            return Object.keys(JSON.parse(item.dataset.cmpDataLayer))[0];
17679        } else {
17680            return item.id;
17681        }
17682    }
17683
17684    /**
17685     * Document ready handler and DOM mutation observers. Initializes Tabs components as necessary.
17686     *
17687     * @private
17688     */
17689    function onDocumentReady() {
17690        var dropdownTab = document.querySelectorAll('.dropdown-tab');
17691        if (dropdownTab) {
17692            for (var i = 0;  i < dropdownTab.length; i++) {
17693                dropdownTab[i].addEventListener('click', function (e) {
17694                    e.stopPropagation();
17695                    isDropdownOpen(e);
17696                });
17697            }
17698        }
17699        var selectContainer = $(".mobile .select-container");
17700        selectContainer.on('click', function (e) {
17701            e.preventDefault();
17702            toggleDropdown(e);
17703        });
17704
17705        $('.tabs-quick-nav-next').on('click', function (e) {
17706            e.preventDefault();
17707            quickNavClickHandler(this, true);
17708        });
17709        $('.tabs-quick-nav-prev').on('click', function (e) {
17710            e.preventDefault();
17711            quickNavClickHandler(this, false);
17712        });
17713
17714
17715        dataLayerEnabled = document.body.hasAttribute("data-cmp-data-layer-enabled");
17716        dataLayer = (dataLayerEnabled) ? window.adobeDataLayer = window.adobeDataLayer || [] : undefined;
17717
17718        var elements = document.querySelectorAll(selectors.self);
17719        for (var i = 0; i < elements.length; i++) {
17720            new Tabs({element: elements[i], options: readData(elements[i])});
17721        }
17722
17723        var MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver;
17724        var body = document.querySelector("body");
17725        var observer = new MutationObserver(function (mutations) {
17726            mutations.forEach(function (mutation) {
17727                // needed for IE
17728                var nodesArray = [].slice.call(mutation.addedNodes);
17729                if (nodesArray.length > 0) {
17730                    nodesArray.forEach(function (addedNode) {
17731                        if (addedNode.querySelectorAll) {
17732                            var elementsArray = [].slice.call(addedNode.querySelectorAll(selectors.self));
17733                            elementsArray.forEach(function (element) {
17734                                new Tabs({element: element, options: readData(element)});
17735                            });
17736                        }
17737                    });
17738                }
17739            });
17740        });
17741
17742        observer.observe(body, {
17743            subtree: true,
17744            childList: true,
17745            characterData: true
17746        });
17747    }
17748
17749    $(document).ready(function () {
17750        onDocumentReady();
17751        loadQuickNav();
17752    });
17753
17754
17755    $(document).on('click', function (e) {
17756        var dropdownContent = $('.mobile .dropdown-content');
17757        var selectContainer = $(".mobile .select-container");
17758        if (!selectContainer.has(e.target).length > 0) {
17759            if (dropdownContent.length > 0 && selectContainer.hasClass('open')) {
17760                $(dropdownContent).slideUp(300, function () {
17761                    $(dropdownContent).removeClass('open');
17762                    $(selectContainer).removeClass('open');
17763                });
17764            }
17765        }
17766    })
17767
17768    $(window).resize(function () {
17769        if ($(window).width() !== screenWidth) {
17770            detectScreenMode();
17771            resetActiveTab(screenMode);
17772        }
17773    });
17774
17775    window.addEventListener("load", window.CQ.CoreComponents.container.utils.scrollToAnchor, false);
17776    window.addEventListener("hashchange", onHashChange, false);
17777
17778
17779}(jQuery));
17780function initializePrismButtonClickEvents() {
17781	const prismButtonList = document.querySelectorAll('#prism-box .prism-footer a.btn')
17782	if(prismButtonList) {
17783		prismButtonList.forEach(
17784			function(prismBtnItem){
17785				prismBtnItem.addEventListener("click", function () {
17786	                stanford.analytics.send(stanford.analytics.createComponentClickButton(prismBtnItem.text, "button", "prism login"));
17787	
17788			});
17789		});	
17790	}
17791	const prismLogoButtonList = document.querySelectorAll('#prism-box a.prism-logo')
17792	if(prismLogoButtonList) {
17793		prismLogoButtonList.forEach(
17794			function(prismBtnItem){
17795				prismBtnItem.addEventListener("click", function () {
17796	                stanford.analytics.send(stanford.analytics.createComponentClickButton(prismBtnItem.text, "button", "prism login"));
17797	
17798			});
17799		});	
17800	}
17801}	
17802window.addEventListener('load', initializePrismButtonClickEvents);
17803
17804	
17805shcDOMContentLoaded(function() {
17806    var CLINICAL_TRIALS = '#clinical-trials-component';
17807    if($(CLINICAL_TRIALS).length>0) {
17808        var clinicalTrials = new SHC.ui.ClinicalTrials(".clinical_trials");
17809    }
17810});
17811
17812shcDOMContentLoaded(function () {
17813  if (jQuery('#video').size() > 0) {
17814    var handleAutoPlay = function () {
17815      var player = jQuery('#video').data('ytPlayer').player;
17816      var autoPlay = parseInt(jQuery('#video').attr('data-auto-play'));
17817      // quick hack to stop video from auto playing
17818      if (!autoPlay) {
17819        player.unMute();
17820      }
17821    };
17822    jQuery('#video').YTPlayer({
17823      fitToBackground: false,
17824      height: '450',
17825      width: '690',
17826      videoId: jQuery('#video').attr('data-video-id'),
17827      repeat: jQuery('#video').attr('data-loop') === 'true' ? true : false,
17828      origin: window.location.origin,
17829      playerVars: {
17830        modestbranding: 1,
17831        autoplay: parseInt(jQuery('#video').attr('data-auto-play')),
17832        controls: jQuery('#video.background-only').length ? 0 : 1,
17833        showinfo: 0,
17834        wmode: 'transparent',
17835        branding: 0,
17836        rel: 0,
17837        autohide: 1,
17838      },
17839      callback: handleAutoPlay,
17840    });
17841  }
17842
17843  addLinkClickEventsToDataLayer();
17844});
17845
17846function addLinkClickEventsToDataLayer() {
17847  var allLinks = $(".heromarqueev2 a[data-cmp-location^='marquee']");
17848
17849  if (allLinks && allLinks.size() > 0) {
17850
17851      allLinks.each(function(){
17852
17853        $(this).on("click", function(){
17854
17855          var payload = {
17856            event: "Component Click",
17857            component: {
17858              info: {
17859                location: $(this).data('cmpLocation'),
17860                href: $(this).attr('href')
17861              },
17862              category: {
17863                primary: $(this).data('cmpCategoryPrimary')
17864              }
17865            }
17866          };
17867          
17868          stanford.analytics.send(payload);
17869
17870        });
17871
17872      });
17873  }
17874}
17875jQuery(function () {
17876  if (jQuery('.campaign-hero').length) {
17877    var campaignHero = new SHC.ui.CampaignHero('.campaign-hero');
17878
17879    var parallaxGreyscaleImage = function (image) {
17880      var debounce = function (fn) {
17881        // Setup a timer
17882        var timeout;
17883
17884        // Return a function to run debounced
17885        return function () {
17886          // Setup the arguments
17887          var context = this;
17888          var args = arguments;
17889
17890          // If there's a timer, cancel it
17891          if (timeout) {
17892            cancelAnimationFrame(timeout);
17893          }
17894
17895          // Setup the new requestAnimationFrame()
17896          timeout = requestAnimationFrame(function () {
17897            fn.apply(context, args);
17898          });
17899        };
17900      };
17901
17902      function isVisible(topViewPort, bottomViewPort, topParent, bottomParent) {
17903        return topParent < bottomViewPort && bottomParent > topViewPort;
17904      }
17905
17906      var parent = image.closest('.campaign-hero');
17907      var parentCoverContainer = image.closest('.hero-cover-container, .hero-cover-clone-container');
17908      var whitespace = parentCoverContainer.find('.hero-whitespace');
17909      var childHeight = image.height();
17910      var parentHeight = parent.height();
17911      var whitespaceHeight = whitespace.height();
17912
17913      var headerOffset = 50;
17914
17915      var offset = ((childHeight + whitespaceHeight) - parentHeight);
17916      //initialize the offset
17917      onResize();
17918
17919      function onScroll() {
17920        var topViewPort = $(window).scrollTop();
17921        var viewPortHeight = $(window).height()
17922        var bottomViewPort = topViewPort + viewPortHeight;
17923        var topParent = parent.offset().top;
17924        parentHeight = parent.height();
17925        childHeight = image.height();
17926        whitespaceHeight = whitespace.height();
17927        offset = ((childHeight + whitespaceHeight) - parentHeight);
17928        var bottomParent = topParent + parentHeight;
17929
17930        if (isVisible(topViewPort, bottomViewPort, topParent, bottomParent)) {
17931          var YOffset = window.pageYOffset;
17932          var grayscalePercent =
17933            100 -
17934            ((YOffset - (topParent - headerOffset)) /
17935              (viewPortHeight / 10)) *
17936            100;
17937          if (grayscalePercent < 0) {
17938            grayscalePercent = 0;
17939          } else if (grayscalePercent > 100) {
17940            grayscalePercent = 100;
17941          }
17942          var scaleXY = 1 + (1 - grayscalePercent / 100) * 0.25;
17943
17944          var percentage =
17945            -(bottomViewPort - topParent) /
17946            ((viewPortHeight + parentHeight) / 100);
17947          var translation = Math.round((percentage / 100) * offset);
17948
17949          if (image.hasClass("greyscale-to-color-image")) {
17950            image.css('opacity', 1 - (grayscalePercent / 100));
17951          }
17952          if (image.hasClass("vertical-parallax-and-scale-up-image")) {
17953            image.css(
17954              'transform',
17955              'translate3d(0px, ' +
17956              translation +
17957              'px, 0px)' +
17958              ' ' +
17959              'scale(' +
17960              scaleXY +
17961              ')'
17962            );
17963          } else if (image.hasClass("vertical-parallax-image")) {
17964            image.css(
17965              'transform',
17966              'translate3d(0px, ' + translation + 'px, 0px)'
17967            );
17968          } else if (image.hasClass("scale-up-image")) {
17969            image.css('transform', 'scale(' + scaleXY + ')');
17970          }
17971        }
17972      }
17973
17974      $(window).scroll(debounce(onScroll));
17975
17976      function onResize() {
17977        parentHeight = parent.height();
17978        childHeight = image.height();
17979        whitespaceHeight = whitespace.height();
17980        offset = ((childHeight + whitespaceHeight) - parentHeight);
17981
17982        if (SHC.ui.screenMode === 'large' || SHC.ui.screenMode === 'medium') {
17983          headerOffset = 150;
17984        } else if (SHC.ui.screenMode === 'small') {
17985          headerOffset = 50;
17986        }
17987
17988        onScroll();
17989      }
17990
17991      $(window).resize(debounce(onResize));
17992    };
17993    $(".greyscale-to-color-image, .vertical-parallax-and-scale-up-image, .vertical-parallax-image, .scale-up-image").each(function () {
17994      parallaxGreyscaleImage($(this));
17995    });
17996  }
17997
17998  if (jQuery(".autoplay-video").length) {
17999    // AutoplayVideo class
18000    var AutoplayVideo = function AutoplayVideo(element) {
18001      this.element = element;
18002      this.visible = false;
18003      this.autoplayOff = false;
18004    }
18005
18006    AutoplayVideo.prototype.autoplay = function (visible, loop) {
18007      var video = this.element[0];
18008      if (!this.autoplayOff && (!video.ended || loop)) {
18009        if (this.visible !== visible) {
18010          if (visible) {
18011            video.play();
18012          } else {
18013            video.pause();
18014          }
18015
18016          this.visible = visible;
18017        }
18018      }
18019    };
18020
18021    AutoplayVideo.prototype.handleClick = function () {
18022      var videoObj = this;
18023      var video = videoObj.element[0];
18024      var volume = $(".volume");
18025      var playPause = $(".playPause");
18026
18027      videoObj.element.click(function () {
18028        if (video.paused) {
18029          videoObj.autoplayOff = false;
18030          video.play();
18031        } else {
18032          if (video.muted) {
18033            video.muted = false;
18034          } else {
18035            videoObj.autoplayOff = true;
18036            video.pause();
18037          }
18038        }
18039      });
18040
18041      volume.click(function () {
18042        if (video.muted) {
18043          video.muted = false;
18044        } else if (video.volume === 0) {
18045          video.volume = 1;
18046        } else {
18047          video.volume = 0;
18048        }
18049      });
18050
18051      playPause.click(function () {
18052        if (video.paused) {
18053          videoObj.autoplayOff = false;
18054          video.play();
18055        } else {
18056          videoObj.autoplayOff = true;
18057          video.pause();
18058        }
18059      });
18060    };
18061
18062    AutoplayVideo.prototype.handleHover = function () {
18063      var videoElement = this.element;
18064      var volume = $(".volume");
18065      var playPause = $(".playPause");
18066
18067      videoElement
18068        .add(volume)
18069        .add(playPause)
18070        .hover(
18071          function () {
18072            volume.addClass("show");
18073            playPause.addClass("show");
18074          },
18075          function () {
18076            volume.removeClass("show");
18077            playPause.removeClass("show");
18078          }
18079        );
18080    };
18081
18082    AutoplayVideo.prototype.handleVideoEvents = function (loop) {
18083      var videoObj = this;
18084      var videoElement = this.element;
18085      videoElement.on("play pause", function () {
18086        videoObj.toggleButton($(".playPause"));
18087      });
18088
18089      videoElement.on("volumechange", function () {
18090        videoObj.toggleButton($(".volume"));
18091      });
18092
18093      videoElement.on("ended", function () {
18094        if (loop) {
18095          videoElement[0].play();
18096        }
18097      });
18098    };
18099
18100    AutoplayVideo.prototype.toggleButton = function (element) {
18101      if (element.hasClass("on")) {
18102        element.removeClass("on");
18103        element.addClass("off");
18104      } else {
18105        element.removeClass("off");
18106        element.addClass("on");
18107      }
18108    };
18109
18110    AutoplayVideo.prototype.toggleMute = function () {
18111      this.element[0].muted = !this.element[0].muted;
18112    };
18113
18114    AutoplayVideo.prototype.keepPlaying = function () {
18115      var video = this.element[0];
18116      return !video.paused && !video.muted && (video.volume === 1);
18117    };
18118
18119    AutoplayVideo.prototype.getTop = function () {
18120      return this.element.offset().top;
18121    };
18122
18123    AutoplayVideo.prototype.getBottom = function () {
18124      return this.element.offset().top + this.element.height();
18125    };
18126
18127    var isVisible = function (
18128      topViewPort,
18129      bottomViewPort,
18130      topVideo,
18131      bottomVideo,
18132      triggerPercent
18133    ) {
18134      var visiblePixels = (triggerPercent / 100) * (bottomVideo - topVideo);
18135      var topDiff = bottomViewPort - topVideo;
18136      var bottomDiff = bottomVideo - topViewPort;
18137      return topDiff >= visiblePixels && bottomDiff >= visiblePixels;
18138    };
18139
18140    $(".autoplay-video").each(function () {
18141      var triggerPercent = $(this).data("trigger");
18142      var enableAutoplay = $(this).data("enableautoplay");
18143      var loop = $(this).data("loop");
18144      var autoplayVideo = new AutoplayVideo($(this));
18145
18146      autoplayVideo.handleVideoEvents(loop);
18147      if (
18148        (SHC.util.isAndroid() || SHC.util.isIOS()) &&
18149        SHC.ui.screenMode === "small"
18150      ) {
18151        autoplayVideo.element.attr("controls", "");
18152        autoplayVideo.element.attr("controlsList", "nodownload");
18153        autoplayVideo.toggleMute();
18154        $(this)
18155          .parent()
18156          .children(".autoplay-icon")
18157          .css("display", "none");
18158      } else {
18159        autoplayVideo.handleClick();
18160        autoplayVideo.handleHover();
18161        if (enableAutoplay) {
18162          onVideoScroll();
18163          $(window).scroll(onVideoScroll);
18164        } else {
18165          autoplayVideo.toggleMute();
18166        }
18167      }
18168
18169      function onVideoScroll() {
18170        var topViewPort = $(window).scrollTop();
18171        var bottomViewPort = topViewPort + $(window).height();
18172        var topVideo = autoplayVideo.getTop();
18173        var bottomVideo = autoplayVideo.getBottom();
18174        if (!autoplayVideo.keepPlaying()) {
18175          autoplayVideo.autoplay(
18176            isVisible(
18177              topViewPort,
18178              bottomViewPort,
18179              topVideo,
18180              bottomVideo,
18181              triggerPercent
18182            )
18183          );
18184        }
18185      }
18186    });
18187  }
18188});
18189
18190function initializeButtonClickEvents() {
18191	const myhealth_CAA_buttons = document.querySelectorAll('.generic-button-wrapper a.button-component[href="https://myhealth.stanfordhealthcare.org/#/activate-create"]');
18192	if (myhealth_CAA_buttons) {
18193		myhealth_CAA_buttons.forEach(
18194			function(curButton) {
18195				curButton.addEventListener("click", function(){
18196				stanford.analytics.send(stanford.analytics.createComponentClickButton(curButton.innerText.trim(), "button", "myhealth sign up"));
18197			});
18198		});
18199	}
18200	console.log("tracking generic buttons");
18201	//generic button tracking - RSW-14811
18202    const generic_buttons = document.querySelectorAll('.generic-button-wrapper a.button-component:not([href="https://myhealth.stanfordhealthcare.org/#/activate-create"])');
18203    if (generic_buttons) {
18204        generic_buttons.forEach(
18205            function(curButton) {
18206                curButton.addEventListener("click", function(){
18207                stanford.analytics.send(stanford.analytics.createComponentClickButton(curButton.innerText.trim(), "button", "generic",curButton.getAttribute("href")));
18208            });
18209        });
18210    }
18211}
18212
18213window.addEventListener('DOMContentLoaded', initializeButtonClickEvents);
18214(function(SHC, jQuery) {
18215    "use strict";
18216    SHC.Namespace(SHC, "SHC.ui.BannerDisplay");
18217    SHC.ui.BannerDisplay = new SHC.Class();
18218    SHC.ui.BannerDisplay.include({
18219        /*
18220         * constructor
18221         */
18222        init: function(parent) {
18223            if ($('.banner-display .editmode').length) { console.log("authoring env!"); return; }
18224            var _that = this;
18225            this.window = $(window);
18226            this.bannerDisplayTimes = [];
18227            this.bannerDisplays = $('.banner-display');
18228            if(this.window.width() > 767) {
18229                this.removeLastDuration();
18230                this.addDurationDisplayTimers();
18231                this.reorderPanels();
18232                this.startPanelFade();
18233                this.bannerDisplays.each(function() {
18234                    var $banner = $(this);
18235                    $(window).on('resize', function () {
18236                        _that.adjustBannerHeight($banner.find('.banner-display-image-panels .bannerdisplaypanel:last'));
18237                    });
18238                });
18239            } else {
18240                $('.panel-image.temp-hidden').removeClass('temp-hidden');
18241            }
18242        },
18243        startPanelFade: function() {
18244            var that = this;
18245            that.bannerDisplays.each(function(index, value) {
18246                var $this = $(this);
18247                that.adjustBannerHeight($this.find('.banner-display-image-panels .bannerdisplaypanel:last'));
18248                var fadeLoop = function(i) {
18249                    if (that.bannerDisplayTimes[index][i]) {
18250                        setTimeout(function() {
18251                            var lastIndex = $this.find('.banner-display-image-panels .bannerdisplaypanel').length;
18252                            var $previousPanel = $this.find('.banner-display-image-panels .bannerdisplaypanel:last').prev().find('.panel-image');
18253                            $previousPanel.removeClass('temp-hidden');
18254                            that.adjustBannerHeight($previousPanel);
18255                            $previousPanel.addClass('animated fadeIn').one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function() {
18256                                $(this).off('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend');
18257                            });
18258                            $this.find('.banner-display-image-panels .bannerdisplaypanel:last').addClass('animated fadeOut').one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function() {
18259                                $(this).off('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend');
18260                                $(this).remove();
18261                                that.adjustBannerHeight($previousPanel);
18262                                if (lastIndex !== 1) {
18263                                    fadeLoop(i + 1);
18264                                }
18265                            });
18266                        }, that.bannerDisplayTimes[index][i] * 1000);
18267                    }
18268                };
18269                fadeLoop(0);
18270            });
18271        },
18272        addDurationDisplayTimers: function() {
18273            var that = this;
18274            that.bannerDisplays.each(function(index, value) {
18275                var singleBannerDisplayTimes = [];
18276                $(value).find('.banner-display-image-panels .bannerdisplaypanel img').each(function() {
18277                    var duration = $(this).attr('data-displayduration');
18278                    $(this).closest('.bannerdisplaypanel').attr('data-displayduration', duration);
18279                    singleBannerDisplayTimes.push(duration);
18280                });
18281                that.bannerDisplayTimes.push(singleBannerDisplayTimes);
18282            });
18283        },
18284        reorderPanels: function() {
18285            $('.banner-display-image-panels .bannerdisplaypanel').each(function() {
18286                $(this).prependTo(this.parentNode);
18287            });
18288            $('.banner-display-image-panels').each(function() {
18289                $(this).find('.panel-image.temp-hidden').last().removeClass('temp-hidden');
18290            });
18291        },
18292        removeLastDuration: function() {
18293            $('.banner-display').each(function() {
18294                $(this).find('.banner-display-image-panels .panel-image:last').removeAttr('data-displayduration');
18295            });
18296        },
18297        adjustBannerHeight: function($this) {
18298            var newHeight;
18299            if ($this.height() <= 443) {
18300                newHeight = $this.height();
18301            } else { //image height is greater than 443
18302                newHeight = 443;
18303            }
18304            $this.closest('.banner-display').css('height', newHeight);
18305        }
18306    });
18307}(SHC, jQuery));
18308
18309jQuery(function() {
18310    if ($('.banner-display').length) {
18311        new SHC.ui.BannerDisplay();
18312    }
18313});
18314/*
18315 * debouncedresize: special jQuery event that happens once after a window resize
18316 *
18317 * latest version and complete README available on Github:
18318 * https://github.com/louisremi/jquery-smartresize
18319 *
18320 * Copyright 2012 @louis_remi
18321 * Licensed under the MIT license.
18322 *
18323 * This saved you an hour of work? 
18324 * Send me music http://www.amazon.co.uk/wishlist/HNTU0468LQON
18325 */
18326(function($) {
18327
18328var $event = $.event,
18329	$special,
18330	resizeTimeout;
18331
18332$special = $event.special.debouncedresize = {
18333	setup: function() {
18334		$( this ).on( "resize", $special.handler );
18335	},
18336	teardown: function() {
18337		$( this ).off( "resize", $special.handler );
18338	},
18339	handler: function( event, execAsap ) {
18340		// Save the context
18341		var context = this,
18342			args = arguments,
18343			dispatch = function() {
18344				// set correct event type
18345				event.type = "debouncedresize";
18346				$event.dispatch.apply( context, args );
18347			};
18348
18349		if ( resizeTimeout ) {
18350			clearTimeout( resizeTimeout );
18351		}
18352
18353		execAsap ?
18354			dispatch() :
18355			resizeTimeout = setTimeout( dispatch, $special.threshold );
18356	},
18357	threshold: 150
18358};
18359
18360})($);
18361/*! matchMedia() polyfill - Test a CSS media type/query in JS. Authors & copyright (c) 2012: Scott Jehl, Paul Irish, Nicholas Zakas. Dual MIT/BSD license */
18362
18363window.matchMedia = window.matchMedia || (function( doc, undefined ) {
18364
18365  "use strict";
18366
18367  var bool,
18368      docElem = doc.documentElement,
18369      refNode = docElem.firstElementChild || docElem.firstChild,
18370      // fakeBody required for <FF4 when executed in <head>
18371      fakeBody = doc.createElement( "body" ),
18372      div = doc.createElement( "div" );
18373
18374  div.id = "mq-test-1";
18375  div.style.cssText = "position:absolute;top:-100em";
18376  fakeBody.style.background = "none";
18377  fakeBody.appendChild(div);
18378
18379  return function(q){
18380
18381    div.innerHTML = "&shy;<style media=\"" + q + "\"> #mq-test-1 { width: 42px; }</style>";
18382
18383    docElem.insertBefore( fakeBody, refNode );
18384    bool = div.offsetWidth === 42;
18385    docElem.removeChild( fakeBody );
18386
18387    return {
18388      matches: bool,
18389      media: q
18390    };
18391
18392  };
18393
18394}( document ));
18395/*
18396 * Adobe Systems Incorporated
18397 * Modified: October 30th, 2012
18398 *
18399 * Picturefill - Responsive Images that work today. (and mimic the proposed Picture element with divs).
18400 * Author: Scott Jehl, Filament Group, 2012 | License: MIT/GPLv2
18401 */
18402
18403(function ($, w) {
18404
18405    // Enable strict mode
18406    "use strict";
18407
18408    w.picturefill = function (context) {
18409        var undefined;
18410        if (context === undefined) {
18411            context = $("body");
18412        }
18413
18414        $("div[data-picture]", context).each(function () {
18415            var currentPicture = this;
18416            var matches = [];
18417            $("div[data-media]", currentPicture).each(function () {
18418                var media = $(this).attr("data-media");
18419                if (!media || ( w.matchMedia && w.matchMedia(media).matches )) {
18420                    matches.push(this);
18421                }
18422            });
18423
18424            var $picImg = $("img", currentPicture).first();
18425
18426            if (matches.length) {
18427                if ($picImg.size() === 0) {
18428                    var $currentPicture = $(currentPicture);
18429                    $picImg = $("<img />").attr("alt", $currentPicture.attr("data-alt")).appendTo($currentPicture);
18430                }
18431
18432                var dataDiv = matches.pop();
18433                if (dataDiv.getAttribute("data-mobile")) {
18434                    if (SHC.ui.screenMode === "small") {
18435                        $picImg.attr("data-src", dataDiv.getAttribute("data-mobile") + "/jcr:content/renditions/original");
18436                        $picImg.attr("data-desktop", dataDiv.getAttribute("data-src"));
18437                    } else {
18438                        $picImg.attr("data-src", dataDiv.getAttribute("data-src"));
18439                        $picImg.attr("data-mobile", dataDiv.getAttribute("data-mobile") + "/jcr:content/renditions/original");
18440                    }
18441                } else {
18442                    $picImg.attr("data-src", dataDiv.getAttribute("data-src"));
18443                }
18444                var picImgClass = dataDiv.getAttribute("class") //replace lazyloaded or lazyloading classes with lazyload to trigger lazyloading.
18445                                	.replace("lazyloading", "lazyload")
18446                                	.replace("lazyloaded","lazyload");
18447                $picImg.addClass(picImgClass);
18448            } else {
18449                $picImg.remove();
18450            }
18451        });
18452    };
18453    $(window).on('mobileGenericTabNavLoaded', function(){
18454        w.picturefill();
18455    });
18456
18457    // Run on debounced resize and domready
18458    $(function () {
18459        w.picturefill();
18460    });
18461
18462    $(w).on("debouncedresize", function () {
18463        w.picturefill();
18464    });
18465
18466}($, this));
18467
18468jQuery(function($) {
18469	$(document).trigger('debouncedresize');
18470});
18471
18472/**
18473 * Created by mlivingston on 7/10/17.
18474 */
18475shcDOMContentLoaded(function() {
18476    $('.person-app-container').each(function() {
18477        var $component = $(this);
18478        //assign an index to all person doctors on the page
18479        $.each($component.find('.person-app-doctor'), function(index, item) {
18480            $(item).attr('data-person-index', index);
18481        });
18482
18483        //loop through person doctors and move them into rows
18484        $component.find('.person-app-doctor').each(function() {
18485            var self = $(this);
18486            var selfIndex = parseInt(self.attr('data-person-index'));
18487            var modIndex = selfIndex % 2;
18488            if (modIndex) {
18489                $component.find('.person-app-doctor:eq(' + selfIndex + '), .person-app-doctor:eq('+ (selfIndex - 1) +')').wrapAll('<div class="row" />');
18490            } else if (selfIndex + 1 === $('.line').length) {
18491                $component.find('.person-app-doctor:eq(' + selfIndex + ')').wrap('<div class="row" />');
18492            }
18493        });
18494    });
18495});
18496SHC.Namespace(SHC, "SHC.ui.Masthead");
18497SHC.ui.Masthead = new SHC.Class();
18498// one big onLoad.
18499shcDOMContentLoaded(function () {
18500    if (($('.masthead').length)) {
18501        $('input, textarea').placeholder();
18502        var $slideSpeed = 400;
18503        var wcm = $.trim($('#wcm').text());
18504        var shcLogo = jQuery('.masthead-affixed.affix #shc-logo');
18505        var shcLogoHeader = jQuery('.masthead-affixed.affix #shc-logo-header');
18506        var shcLogoMobile = jQuery('.masthead-affixed.affix #shc-logo-mobile');
18507        var shcLogoHeaderMobile = jQuery('.masthead-affixed.affix #shc-logo-header-mobile');
18508        var advantageLogo = jQuery('.masthead-affixed.affix #shc-logo.shc-advantage');
18509        var advantageLogoMobile = jQuery('.masthead-affixed.affix #shc-log-mobile.shc-advantage');
18510        var shcaNav = jQuery('.masthead-affixed.affix .shca-nav');
18511        var scrollPosition = jQuery(window).scrollTop();
18512        var mastheadContainer = jQuery('.masthead .masthead-affixed.affix');
18513        var advantageMastheadContainer = jQuery('#header.advantage-header .masthead-affixed.affix');
18514        var searchButton = jQuery('.masthead .masthead-affixed.affix .search-button');
18515        var hamburgerButton = jQuery('.masthead .masthead-affixed.affix .hamburger-menu
18515-button');
18516        var homeIconContainer = jQuery('.sidebar-offcanvas .home-icon-container');
18517        var menuHomeLinkSpans = jQuery('.sidebar-offcanvas #menu-home-link span');
18518        $('#header').not('.edit-template-mode').find('#drawers').find('.drawer').hide();
18519        var containerHeight = mastheadContainer.find('.shca-nav') ? '65px' : '50px';
18520        $('#menu-secondary-nav').find('.arrow').addClass('collapsed').parent().parent().parent().find('ul').hide();
18521        SHC.util.clearMapCookiesOnDirectoryClick();
18522
18523        var mastheadResize = function () {
18524            var menu = $('.masthead-affixed .menu-toggle');
18525            if (menu.hasClass('active')) {
18526                mastheadContainer.css({ width: ($(window).width() - 240) + "px" });
18527            }
18528        };
18529
18530        // close menu
18531        var closeMenu = function () {
18532            //$('#menu').hide();
18533            $('#menu-secondary-nav').find('.arrow').addClass('collapsed').parent().parent().parent().find('ul').hide();
18534        };
18535
18536        // open menu
18537        var openMenu = function () {
18538            //$('#menu').show();
18539            $('#menu-secondary-nav').find('.arrow').not($(this)).addClass('collapsed').parent().parent().find('ul').hide();
18540        };
18541
18542        // toggle menu
18543        var toggleMenu = function (menu) {
18544            if (menu.hasClass('active')) {
18545                jQuery('.menu-toggle span.hidden-xs').text('Close');
18546                openMenu(wcm);
18547                jQuery('.menu-toggle span.hidden-xs').parent().attr("data-aa-sidebar-links", "close");
18548                jQuery('.sidebar-offcanvas a').removeAttr('tabindex');
18549            } else {
18550                jQuery('.menu-toggle span.hidden-xs').text('Menu');
18551                closeMenu(wcm);
18552                jQuery('.menu-toggle span.hidden-xs').parent().attr("data-aa-sidebar-links", "menu");
18553                jQuery('.sidebar-offcanvas a').attr('tabindex', '-1');
18554            }
18555        };
18556
18557        // close all drawers
18558        var closeDrawers = function (callback) {
18559            var needToOpenMenu = false;
18560            var callbackInvoked = false;
18561            $('#masthead a').not('.menu-toggle').removeClass('active').parent('li').removeClass('active');
18562            $('#header').not('.edit-template-mode').find('#drawers').find('.drawer').each(function () {
18563                if ($(this).is(':visible')) {
18564                    $(this).slideUp($slideSpeed, callback);
18565                    callbackInvoked = true;
18566                }
18567            });
18568            return callbackInvoked;
18569        };
18570
18571        // set the headline heights for vertical alignment
18572        var updateHeadline = function () {
18573            $('#drawers').find('.standard-drawer').each(function () {
18574                var $headlineTextWrapper = $(this).find('.drawer-headline-content-wrapper');
18575                var $headlineHeight = $headlineTextWrapper.find('.drawer-headline-content').outerHeight();
18576                $headlineTextWrapper.height($headlineHeight);
18577            });
18578        };
18579
18580
18581        /*
18582         * Positioning the Logo when Emergency alert is displayed
18583         * */
18584        var positionLogo = function () {
18585            if ($('#emergencyAlert').length && SHC.ui.screenMode === "small") {
18586                $('.masthead-affixed.mobile').css('position', 'relative');
18587            }
18588        };
18589
18590        var setActivePage = function () {
18591            var path = SHC.util.adjustPath(location.pathname);
18592
18593            $("#masthead-nav>li>a").each(function (i, e) {
18594                var linkLocation = $(e).attr('href');
18595                if (linkLocation) {
18596                    linkLocation = SHC.util.getPathFromUrl(SHC.util.adjustPath(linkLocation));
18597
18598                    //IE is processing linkLocation as blank instead of "/" causing no match in the next if
18599                    if (SHC.util.isIE() && linkLocation === '') {
18600                        if ($(e).attr('href') === '/') {
18601                            linkLocation = $(e).attr('href');
18602                        }
18603                    }
18604
18605                    if ((linkLocation !== "" && linkLocation !== "/" && path.indexOf(linkLocation) > -1)
18606                        || (linkLocation === path)) {
18607                        $(e).addClass("activesection");
18608                        // break the loop
18609                        return false;
18610                    }
18611                }
18612
18613            });
18614        };
18615
18616        updateHeadline();
18617        positionLogo();
18618        setActivePage();
18619
18620        jQuery(window).on('resizeEnd', function () {
18621            updateHeadline();
18622            positionLogo();
18623        });
18624
18625        // TODO
18626        // I think this should only do its thing, if the modal isn't showing???
18627
18628        // logic to transform our shc logo in the header when it hits a certain scrollPosition
18629        var headerLogoAnimation = function () {
18630            var animStart = 35;
18631            var animDuration = 90;
18632            var animEnd = animStart + animDuration;
18633            var bigLogoStartPosition = 8.5;
18634            var smallLogoEndPosition = -24;
18635
18636            // moving/scaling amounts
18637            var scaleAmt = (((animEnd - scrollPosition) * (0.45 / animDuration)) + 0.55);
18638            var moveIconYAmt = (bigLogoStartPosition) - ((scrollPosition - animStart) * 0.45);
18639            var moveHeight = ((animStart - scrollPosition) * (80 / animDuration) + 130);
18640            var moveSearchButtonYAmt = ((animStart - scrollPosition) * (41 / animDuration) + 53);
18641            var moveHamHomeButtonYAmt = ((animStart - scrollPosition) * (41 / animDuration) + 57);
18642
18643            var logoTransform = {};
18644            var advantageLogoTransform = {};
18645            // scrollPosition conditional for logo, masthead size, and fallback conditions
18646            if (!jQuery('#modal-container').is(':visible') && $(window).width() > 767) {
18647                if (scrollPosition >= animStart && scrollPosition < animEnd) {
18648                    mastheadContainer.css({
18649                        'height': moveHeight + 'px',
18650                    }).addClass('shadow');
18651                    homeIconContainer.css({
18652                        'height': moveHeight + 'px'
18653                    });
18654                    menuHomeLinkSpans.css({
18655                        'top': moveHamHomeButtonYAmt + 'px'
18656                    });
18657                    logoTransform = {
18658                        'transform': 'translateY(' + moveIconYAmt + 'px) ' + 'scale(' + scaleAmt + ')'
18659                    };
18660                    shcLogo.css(logoTransform);
18661                    shcLogoHeader.css(logoTransform);
18662                    shcLogoMobile.css(logoTransform);
18663                    shcLogoHeaderMobile.css(logoTransform);
18664                    shcaNav.css({
18665                        'transform': 'translate(0, -20px)'
18666                    });
18667                    searchButton.css({
18668                        'top': moveSearchButtonYAmt + 'px'
18669                    });
18670                    hamburgerButton.css({
18671                        'top': moveSearchButtonYAmt + 'px'
18672                    });
18673                } else if (scrollPosition < animStart) {
18674                    logoTransform = {
18675                        'transform': 'translateY(' + bigLogoStartPosition + 'px)'
18676                    };
18677                    shcLogo.css(logoTransform);
18678                    shcLogoHeader.css(logoTransform);
18679                    shcLogoMobile.css(logoTransform);
18680                    shcLogoHeaderMobile.css(logoTransform);
18681                    shcaNav.css({
18682                        'transform': 'translate(0px, 0px)'
18683                    });
18684                    var mastheadHeight = '130px';
18685                    if (advantageMastheadContainer.length) {
18686                        mastheadHeight = '95px';
18687                    }
18688                    mastheadContainer.css({
18689                        'height': mastheadHeight
18690                    }).removeClass('shadow');
18691                    homeIconContainer.css({
18692                        'height': '130px'
18693                    });
18694                    menuHomeLinkSpans.css({
18695                        'top': '57px'
18696                    });
18697                    searchButton.css({
18698                        'top': '53px'
18699                    });
18700                    hamburgerButton.css({
18701                        'top': '53px'
18702                    });
18703                } else {
18704                    logoTransform = {
18705                        'transform': 'translateY(' + smallLogoEndPosition + 'px) scale(.53)'
18706                    };
18707                    shcLogo.css(logoTransform);
18708                    shcLogoHeader.css(logoTransform);
18709                    shcLogoMobile.css(logoTransform);
18710                    shcLogoHeaderMobile.css(logoTransform);
18711                    advantageLogoTransform = {
18712                        'transform': 'translateY(8px) scale(.53)'
18713                    };
18714                    advantageLogo.css(advantageLogoTransform);
18715                    advantageLogoMobile.css(advantageLogoTransform);
18716                    shcaNav.css({
18717                        'transform': 'translate(0px, 0px)'
18718                    });
18719                    mastheadContainer.css({
18720                        'height': containerHeight
18721                    });
18722                    mastheadContainer.addClass('shadow');
18723                    homeIconContainer.css({
18724                        'height': '50px'
18725                    });
18726                    menuHomeLinkSpans.css({
18727                        'top': '16px'
18728                    });
18729                    searchButton.css({
18730                        'top': '20px'
18731                    });
18732                    hamburgerButton.css({
18733                        'top': '20px'
18734                    });
18735                }
18736            }
18737        };
18738        // reset top and height to natural mobile styles
18739        $(window).on('resizeEnd', function () {
18740            if ($(this).width() < 768) {
18741                homeIconContainer.css('height', '');
18742                menuHomeLinkSpans.css('top', '');
18743            }
18744            else {
18745                //if window's resizeed to larger size after scrolling adjust the size of things
18746                headerLogoAnimation();
18747            }
18748        });
18749
18750        // update scrollPosition on scroll
18751        jQuery(window).scroll(function () {
18752            scrollPosition = $(window).scrollTop();
18753        });
18754
18755        // check to animate shc logo on scroll
18756        jQuery(window).scroll(headerLogoAnimation);
18757
18758        // on masthead anchor click
18759        $('#masthead-nav li.masthead-dropdown a').off('click').on('click', function (e) {
18760            // for stanford lab global navigation menu, only clicking on the carat symbol should trigger dropdown,
18761            // clicking on the text/link would take the user to the linked page.
18762            var isStanfordLabNav = $('.stanford-lab.global-navigation').length ? true : false;
18763            if (!(isStanfordLabNav && $(e.target).is('a'))) {
18764                e.preventDefault();
18765                var link = $(this),
18766                    li = link.parent('li');
18767                $('#masthead').addClass('active');
18768                var menuToggle = $('.masthead-affixed.hidden-xs .menu-toggle');
18769                if (menuToggle.hasClass('active')) {
18770                    menuToggle.trigger("click");
18771                }
18772
18773                // if toggled drawer is already open
18774                if (li.hasClass('active')) {
18775                    // close drawers
18776                    li.removeClass('active');
18777                    closeDrawers(function () {
18778                        $('#masthead').removeClass('active');
18779                    });
18780
18781                } else {
18782                    // close drawers
18783                    closeDrawers();
18784
18785                    li.siblings().removeClass('active');
18786                    li.addClass('active');
18787
18788                    // open toggled drawer
18789                    var toggleId = link.data('toggle');
18790                    $('#drawers').find('.drawer[data-drawer="' + toggleId + '"]').slideDown($slideSpeed, function () {
18791                        //                $('#masthead').removeClass('active');
18792                    });
18793                    updateHeadline();
18794                }
18795                var mobileAppsLinks = $("#my-health-drawer .drawer1-bottom a");
18796                if (mobileAppsLinks && mobileAppsLinks.length === 2) {
18797                    mobileAppsLinks.each(function () {
18798                        var linkText = $(this).text().toLowerCase();
18799                        $(this).attr('data-aa-masthead-links', linkText);
18800                    });
18801                }
18802            }
18803        });
18804
18805        var menuToggleHandler = function (e) {
18806            var that = $(this);
18807            if (e) {
18808                e.preventDefault();
18809            }
18810            $('.menu-toggle').toggleClass('active');
18811            $('#masthead').removeClass("active");
18812            if ($('#header').not('.edit-template-mode').find('#drawers').find('.drawer').is(':visible') && $(this).hasClass('active')) {
18813                closeDrawers(function () {
18814                    toggleMenu(that);
18815                });
18816            } else {
18817                toggleMenu(that);
18818            }
18819        };
18820
18821        // menu-toggle click
18822        $('.menu-toggle').on('click', menuToggleHandler);
18823
18824        // menu close click
18825        $('#menu').find('.close-menu').on('click', function (e) {
18826            e.preventDefault();
18827            $('.menu-toggle').removeClass('active');
18828            closeMenu(wcm);
18829        });
18830
18831        // menu arrow click
18832        $('#menu-secondary-nav').find('.menu-dropdown-toggle').on('click', function (e) {
18833            e.preventDefault();
18834            $('#menu-secondary-nav').find('.menu-dropdown-toggle').not($(this)).find('.arrow').addClass('collapsed').parent().parent().parent().find('ul').slideUp('fast');
18835            $(this).find('.arrow').toggleClass('collapsed').parent().parent().parent().find('ul').slideToggle('fast');
18836        });
18837
18838        $(window).on('resizeEnd', mastheadResize);
18839
18840        // handles hover for menu and search buttons
18841        $('.menu-toggle, .search-toggle').hover(function () {
18842            $(this).addClass('hovering');
18843        }, function () {
18844            $(this).removeClass('hovering');
18845        });
18846
18847        // export when loaded
18848        SHC.ui.Masthead.include({
18849            init: function () {
18850            },
18851            closeMenu: function () {
18852                var menuToggle = $('.masthead-affixed.hidden-xs .menu-toggle');
18853                if (menuToggle.hasClass('active')) {
18854                    menuToggle.trigger("click");
18855                }
18856            },
18857            closeOpenDrawers: function (callback) {
18858                return closeDrawers(callback);
18859            }
18860        });
18861
18862        // Set sidebar-offcanvas links to not be navigable by keyboard on initial page load
18863        jQuery('.sidebar-offcanvas a').attr('tabindex', '-1');
18864
18865        var isStanfordLabNav = $('.stanford-lab.global-navigation').length ? true : false;
18866
18867        if (!isStanfordLabNav) {
18868            const pvLink = document.querySelector('a[data-aa-masthead-links="patients & visitors"]');
18869
18870            const pvDrawer = document.getElementById('pv-drawer');
18871            const firstLinkInPvDrawer = pvDrawer.querySelector('a');
18872            const rightDrawerOfPV = pvDrawer.querySelector('#pv-drawer .drawer2-right.parsys');
18873            const textParbaseSections = rightDrawerOfPV.querySelectorAll('.text.parbase.section');
18874
18875            //Side Menu Navigation Focus Behavior
18876            const sideMenuToggle = document.querySelector('a[data-aa-sidebar-links="menu"]');
18877            const sideNavMenuHomeLink = document.getElementById('menu-home-link');
18878            const lastDiv = $('#menu-secondary-nav .parbase.menu-my-health.masthead_menu_revealbox').last();
18879            if (sideMenuToggle && sideNavMenuHomeLink && lastDiv) {
18880
18881                //Move the focus to home link in sidebar-offcanvas if drawer is open
18882                sideMenuToggle.addEventListener('blur', () => {
18883                if(sideMenuToggle.classList.contains('active'))
18884                    sideNavMenuHomeLink.focus();
18885                });
18886
18887                //Move the focus to sidebar toggle when tabbed from the last item in the sidebar-offcanvas
18888                lastDiv.on('blur', 'a', function () {
18889                    sideMenuToggle.focus();
18890                });
18891            }
18892
18893            var links = [];
18894            textParbaseSections.forEach(section => {
18895                const rteLinks = section.querySelectorAll('.rte-has-anchor-link');
18896                rteLinks.forEach(rteLink => {
18897                    const anchors = rteLink.querySelectorAll('a');
18898                    anchors.forEach(anchor => {
18899                        links.push(anchor);
18900                    });
18901                });
18902            });
18903
18904            //Patients & Visitors Navigation Focus Behavior
18905            if (pvLink && firstLinkInPvDrawer) {
18906
18907                //Move focus to patients and visitors dropdown after clicking on header link
18908                pvLink.addEventListener('blur', function (event) {
18909                    const li = pvLink.parentElement;
18910                    if (li.classList.contains('active')) {
18911                        event.preventDefault();
18912                        firstLinkInPvDrawer.focus();
18913                    }
18914                });
18915
18916                //Move focus back to patients and visitors link after traversing its dropdown
18917                if (links.length > 0) {
18918                    const lastLink = links[links.length - 1];
18919                    lastLink.addEventListener('blur', () => {
18920                        pvLink.focus();
18921                    });
18922                }
18923                else {
18924                    const emailLinkInPv = pvDrawer.querySelector('.masthead-contact-email-text');
18925                    if(emailLinkInPv) {
18926                        emailLinkInPv.addEventListener('blur', () => {
18927                            pvLink.focus();
18928                        });
18929                    }
18930                }
18931            }
18932
18933            //MyHealth Navigation Focus Behavior
18934            const mhLink = document.querySelector('a[data-aa-masthead-links="myhealth"]');
18935            const mhDrawer = document.getElementById('my-health-drawer');
18936            if (mhLink && mhDrawer) {
18937
18938                //Move focus to my health link again after traversing its dropdown
18939                const mhLogin = document.getElementById('my-health-login');
18940                const mhLoginAnchors = mhLogin.querySelectorAll('a');
18941                if (mhLoginAnchors.length > 0) {
18942                    const lastLink = mhLoginAnchors[mhLoginAnchors.length - 1];
18943                    lastLink.addEventListener('blur', () => {
18944                        mhLink.focus();
18945                    });
18946                }
18947
18948                //Move the focus to the first link in my health drawer, if it is open
18949                const mhLeftAnchors = mhDrawer.querySelectorAll('a');
18950                const li = mhLink.parentElement;
18951                if(mhLeftAnchors.length > 0) {
18952                    mhLink.addEventListener('blur', () => {
18953                        if (li.classList.contains('active')) {
18954                            event.preventDefault();
18955                            mhLeftAnchors[0].focus();
18956                        }
18957                    });
18958                }
18959            }
18960        }
18961    }
18962});
18963
18964SHC.Namespace(SHC, "SHC.ui.CampaignHero");
18965SHC.ui.CampaignHero = new SHC.Class();
18966
18967SHC.ui.CampaignHero.include({
18968    /*
18969     * constructor
18970     */
18971    init: function(parent) {
18972        this.parent = parent;
18973        this.activate();
18974    },
18975
18976    activate: function() {
18977        var _this = this;
18978        var syncSize = function() {
18979            jQuery("#heroplayer").height(jQuery(".hero-cover").height());
18980        };
18981        if (jQuery("#heroplayer").length>0) {
18982            syncSize();
18983            jQuery(window).on('resizeEnd', syncSize);
18984            jQuery(_this.parent + " .play-btn").on("click", function(event){
18985                event.preventDefault();
18986                syncSize();
18987                jQuery(_this.parent + " .hero-cover").fadeOut();
18988                jQuery(_this.parent + " .hero-video").fadeIn(1000, function(){
18989                    jQuery(_this.parent + " iframe.hero-youtube").show();
18990                    var ytplayer = _this.getYTplayer();
18991                    if (typeof ytplayer !== "undefined") {
18992                        ytplayer.playVideo();
18993                    }
18994                });
18995            });
18996        }
18997    },
18998
18999    getYTplayer: function() {
19000        var ytIframeID = "heroplayer";
19001        for (var iter = 0; typeof SHC.ytplayers !== "undefined" && SHC.ytplayers != null && iter < SHC.ytplayers.length; iter++) {
19002            if (SHC.ytplayers[iter].f.id === ytIframeID) {
19003                return SHC.ytplayers[iter];
19004            }
19005        }
19006    }
19007});
19008SHC.Namespace(SHC, "SHC.ui.ClinicalTrials");
19009SHC.ui.ClinicalTrials = new SHC.Class();
19010
19011SHC.ui.ClinicalTrials.include({
19012    /*
19013     * constructor
19014     */
19015    init: function(parent) {
19016        var that = this;           
19017        this.parent = parent;
19018        this.nav = $(parent).find(".clinical-trials-tab-nav");
19019        this.sliders = $(parent).find(".clinical-trials-slider");
19020        this.sliderLeftPadding = 20;
19021        this.navMobileDropdownHeight = 88;
19022        this.sliderSpeed = 300;
19023
19024        this.setSummaryNumbers();
19025        this.setupTabs();
19026        this.setupSliders();
19027        
19028
19029        // This is here to make sure google fonts has loaded 
19030        // before finding the initial slider height. There is
19031        // possibly a better way to do this
19032        $(window).on("load", function() {
19033            that.setSliderHeight();
19034        });
19035    },
19036    /*
19037     * sliders setup
19038     */
19039    setupSliders: function() {
19040        var that = this;
19041
19042        var setup = function(index) {
19043            var slider = $(this);
19044            var section = slider.closest(".clinical-trials-cards");
19045            var originalCards = section.find(".clinical-trial-card");
19046            var toggles = section.find(".clinical-trials-slider-toggles");
19047
19048            originalCards.clone().appendTo(slider);
19049
19050            var cards = slider.find(".clinical-trial-card");
19051
19052            // hide toggles if there is only one card
19053            if (cards.length <= 1) {
19054                toggles.hide();
19055            }
19056
19057            // setup slider sizes
19058            that.setCardSizes(cards);
19059            that.setSliderWidth(slider, cards);
19060            that.activateSlider(slider, cards);
19061        };
19062
19063        that.sliders.each(setup);
19064        that.setSliderHeight();
19065        that.setToggleWidth();
19066
19067        var modal = new SHC.ui.Modal(".clinical-trials-slider-container .open-modal");
19068
19069        $('.profile-content-tabs [class*=-tab]').click(function(){
19070            that.setSliderHeight();
19071            that.setToggleWidth();
19072        });
19073    },
19074    setSummaryNumbers: function(){
19075        var hubTitle = $(".clinical-trials-sections").attr("data-hub-title");
19076        var recruitingSum;
19077        var notRecruitingSum;
19078        if(hubTitle){
19079            hubTitle = encodeURIComponent(hubTitle);
19080        }
19081        var searchVer = document.querySelector('meta[name="shc-search-version"]').content || "v1";
19082        var searchUrl = "/bin/api/"+searchVer+"/search.json";
19083        var recruitingSumUrl = searchUrl + "?do=organic_clinical_trials&x27=sp_trialLocks&q27=" + hubTitle + "&x28=sp_status&q28=RECRUITING&general=total";
19084        var notRecruitingSumUrl = searchUrl + "?do=organic_clinical_trials&x27=sp_trialLocks&q27=" + hubTitle + "&x28=sp_status&q28=NOT_RECRUITING&general=total";
19085        var request = jQuery.ajax({
19086            url: recruitingSumUrl,
19087            dataType: "jsonp",
19088            jsonp: 'callback',
19089            contentType: "application/json",
19090            success: function(data) {
19091                recruitingSum = data["general"]["total"];
19092            },
19093            error: function() {
19094                console.log("Ajax error during setSummaryNumbers");
19095            },
19096            complete: function(data){                              
19097                $(".recruiting").find(".summary-count").html(recruitingSum);                        
19098            }
19099        });
19100        request = jQuery.ajax({
19101            url: notRecruitingSumUrl,
19102            dataType: "jsonp",
19103            jsonp: 'callback',
19104            contentType: "application/json",
19105            success: function(data) {
19106                notRecruitingSum = data["general"]["total"];
19107            },
19108            error: function() {
19109                console.log("Ajax error during setSummaryNumbers");
19110            },
19111            complete: function(data){                              
19112                $(".not-recruiting").find(".summary-count").html(notRecruitingSum);                        
19113            }
19114        }); 
19115        
19116    },        
19117            
19118    /*
19119     * set card widths, adjusted manually to try to fit with current design
19120     */
19121    setCardSizes: function(cards) {
19122        var that = this;
19123        var cardWidth = 0;
19124
19125        switch (cards.length) {
19126            case 1:
19127                cardWidth = "82.7%";
19128                break;
19129            case 2:
19130                cardWidth = "41.4%";
19131                break;
19132            case 3:
19133                cardWidth = "27.6%";
19134                break;
19135            case 4:
19136                cardWidth = "20.7%";
19137                break;
19138            case 5:
19139                cardWidth = "16.55%";
19140                break;
19141            case 6:
19142                cardWidth = "13.8%";
19143                break;
19144            default:
19145                break;
19146        }
19147
19148        cards.each(function() {
19149            $(this).css("width", cardWidth);
19150            that.setSliderHeight();
19151        });
19152    },
19153    /*
19154     * Set width of carousel slider
19155     */
19156    setSliderWidth: function(slider, cards) {
19157        slider.css("width", cards.length * 100 + "%");
19158    },
19159    /*
19160     * set height of carousel slider
19161     */
19162    setSliderHeight: function() {
19163        var setHeight = function(index) {
19164            var slider = $(this);
19165            var container = slider.closest(".clinical-trials-slider-container");
19166            container.css("height", slider.height());
19167        };
19168
19169        this.sliders.each(setHeight);
19170    },
19171    /*
19172     * set width of toggle sections
19173     */
19174    setToggleWidth: function() {
19175        var setWidth = function() {
19176            var toggles = $(this);
19177            var cardWidth = toggles.closest(".clinical-trials-cards").find(".clinical-trials-slider").find(".clinical-trial-card").first().find("a").outerWidth();
19178            toggles.css("width", cardWidth);
19179        };
19180        $('.clinical-trials-cards .clinical-trials-slider-toggles-wrapper').each(setWidth);
19181    },
19182    /*
19183     * setup carousel toggles
19184     */
19185    activateSlider: function(slider, cards) {
19186        var that = this;
19187        var container = slider.closest(".clinical-trials-cards").find(".clinical-trials-slider-toggles");
19188
19189        // build toggles
19190        var setup = function(index) {
19191            container.append("<a href=\"#\" class=\"clinical-trials-slider-toggle\" data-card=\"" + index + "\"><span></span></a> ");
19192            container.find(".clinical-trials-slider-toggle").first().addClass("active");
19193        };
19194
19195        // handle toggle clicks
19196        var onToggleClick = function(e) {
19197            console.log("swipeLeft");
19198            e.preventDefault();
19199
19200            var toggle = $(this);
19201            var slider = toggle.closest(".clinical-trials-cards").find(".clinical-trials-slider");
19202            var cardWidth = slider.find(".clinical-trial-card").first().width();
19203            var currentCard = toggle.data("card");
19204
19205            toggle.parent().find("a").removeClass("active");
19206            toggle.addClass("active");
19207            slider.animate({left: (-cardWidth * currentCard) + that.sliderLeftPadding + "px"}, this.sliderSpeed);
19208        };
19209
19210        var onSwipeRight = function(e) {
19211            console.log("swipeRight");
19212            e.preventDefault();
19213
19214            var togglesContainer = $(this).closest(".clinical-trials-cards").find(".clinical-trials-slider-toggles");
19215            var currentId = togglesContainer.find(".active").data("card");
19216
19217            if (currentId > 0) {
19218                var newId = currentId - 1;
19219                togglesContainer.find("a[data-card='" + newId + "']").click();
19220            }
19221        };
19222
19223        var onSwipeLeft = function(e) {
19224            e.preventDefault();
19225
19226            var togglesContainer = $(this).closest(".clinical-trials-cards").find(".clinical-trials-slider-toggles");
19227            var toggles = togglesContainer.find("a");
19228            var currentId = togglesContainer.find(".active").data("card");
19229
19230            if (currentId < toggles.length + 1) {
19231                var newId = currentId + 1;
19232                togglesContainer.find("a[data-card='" + newId + "']").click();
19233            }
19234        };
19235
19236        // refresh the slider to the proper position after window resize
19237        var refreshSlider = function() {
19238            var slider = $(this);
19239            var cardWidth = slider.find(".clinical-trial-card").first().width();
19240            var currentToggles = slider.closest(".clinical-trials-cards").find(".clinical-trials-slider-toggles");
19241            var currentCard = currentToggles.find(".active").data("card");
19242
19243            slider.css("left", (-cardWidth * currentCard) + that.sliderLeftPadding + "px");
19244        };
19245
19246        // handle window resizing (delay 100 to avoid choppiness when resizing)
19247        var onWindowResize = function(e) {
19248            if (this.resizeTO) {
19249                clearTimeout(this.resizeTO);
19250            }
19251            this.resizeTO = setTimeout(function() {
19252                if (SHC.ui.screenMode === 'small') {
19253                    that.sliders.each(refreshSlider);
19254                    that.setToggleWidth();
19255                    that.setSliderHeight();
19256                    that.sliders.css("visibility", "visible").closest(".clinical-trials-sections").find(".clinical-trials-slider-toggles").css("visibility", "visible");
19257                } else {
19258                    that.sliders.css("visibility", "hidden").closest(".clinical-trials-sections").find(".clinical-trials-slider-toggles").css("visibility", "hidden");
19259                }
19260
19261            }, 100);
19262        };
19263
19264        cards.each(setup);
19265        container.find(".clinical-trials-slider-toggle").on("click", onToggleClick);
19266        slider.on("touchmove", function(event) {
19267            event.preventDefault();
19268        });
19269        slider.on("swiperight", onSwipeRight);
19270        slider.on("swipeleft", onSwipeLeft);
19271
19272        $(window).on('resizeEnd', onWindowResize);
19273    },
19274    /*
19275     * tab setup
19276     */
19277    setupTabs: function() {
19278        var that = this;
19279        var nav = that.nav;
19280        var dropdownSpeed = 100;
19281        var hasOpenTrials = nav.find(".currently-recruiting-link").length > 0;
19282        var hasClosedTrials = nav.find(".all-trials-link").length > 0;
19283
19284        var setupDropdown = function(index) {
19285            var activeText = $(this).find(".active").text();
19286            $(this).siblings(".clinical-trials-tab-nav-current").find(".dropdown-text").hide().text(activeText).show();
19287        };
19288
19289        var toggleDropdown = function(e) {
19290            e.preventDefault();
19291            $(this).closest(".clinical-trials-tab-nav-current").siblings(".clinical-trials-tab-nav").slideToggle(dropdownSpeed);
19292            $(this).closest(".clinical-trials-tab-nav-current").find(".dropdown-arrow").toggleClass("open");
19293        };
19294
19295        var onNavClick = function(e) {
19296            e.preventDefault();
19297
19298            var item = $(this);
19299            var data = item.data("section");
19300            var clinicalTrials = item.closest(".clinical_trials");
19301            var selectedSection = clinicalTrials.find(".clinical-trials-sections").find("[data-section='" + data + "']");
19302
19303            that.clear(clinicalTrials);
19304            item.addClass("active");
19305            selectedSection.show();
19306            that.setToggleWidth();
19307            that.setSliderHeight();
19308
19309            var activeText = $(this).text();
19310            $(this).closest(".clinical-trials-tab-nav").siblings(".clinical-trials-tab-nav-current").find(".dropdown-text").text(activeText).siblings(".dropdown-arrow").removeClass("open");
19311            $(this).closest(".clinical-trials-tab-nav").hide();
19312        };
19313        
19314        var disableLink = function(e) {
19315            e.preventDefault();
19316        };
19317
19318        var initTabs = function() {
19319            if (hasOpenTrials && !hasClosedTrials) {
19320                nav.find(".currently-recruiting-link").css("border-right", "none");
19321            }
19322        };
19323
19324        $(nav).each(setupDropdown);
19325        initTabs();
19326        if(hasOpenTrials && hasClosedTrials) {
19327            $(nav).find("a").on("click", onNavClick);
19328            $(nav).siblings(".clinical-trials-tab-nav-current").find("a").on("click", toggleDropdown);
19329        } else { //only one section
19330            //hide dropdown arrow in small, make cursor default, disable click
19331            nav.find("a").css("cursor", "default"); //cursor default
19332            nav.siblings(".clinical-trials-tab-nav-current").find("a").css("cursor", "default"); //cursor default small
19333            nav.find("a").on("click", disableLink); //disable link
19334            $(nav).siblings(".clinical-trials-tab-nav-current").find("a").on("click", disableLink); //disable link small
19335            $(".clinical-trials-tab-nav-current").find(".dropdown-arrow").hide(); //hide dropdown arrow small
19336        } 
19337    },
19338    /*
19339     * resets all tabs and carousels
19340     */
19341    clear: function(clinicalTrials) {
19342        clinicalTrials.find("a").removeClass("active");
19343        clinicalTrials.find(".clinical-trials-sections").children("div").hide();
19344        clinicalTrials.find(".clinical-trials-slider").css("left", this.sliderLeftPadding);
19345        clinicalTrials.find(".clinical-trials-slider-toggle").removeClass("active").parent().find("a:first").addClass("active");
19346    }
19347});
19348SHC.Namespace(SHC, "SHC.ui.Calculator");
19349SHC.ui.Calculator = new SHC.Class();
19350SHC.ui.Calculator.bmi = null;
19351SHC.ui.Calculator.error = false;
19352SHC.ui.Calculator.showResult = true;
19353
19354SHC.ui.Calculator.show = function (target) {
19355    jQuery('#modal_container_bmi').find('.resultTitle').append("<h4>BMI: " + SHC.ui.Calculator.bmi + "</h4>");
19356    jQuery('#modal_container_bmi').find('#meld_form').find('form').append('<input id="bimindex" class="bmiInput hidden" onkeydown="" size="35" value="' + SHC.ui.Calculator.bmi + '" name="bmi"></input>');
19357    if (SHC.ui.Calculator.bmi < 18.5) {
19358        jQuery('.under_weight').removeClass('hidden');
19359    } else if (SHC.ui.Calculator.bmi > 18.49 && SHC.ui.Calculator.bmi < 25) {
19360        jQuery('.normal_weight').removeClass('hidden');
19361    } else if (SHC.ui.Calculator.bmi > 24.99 && SHC.ui.Calculator.bmi < 30) {
19362        jQuery('.over_weight').removeClass('hidden');
19363    } else {
19364        jQuery('.obese_weight').removeClass('hidden');
19365    }
19366    var isIE = SHC.util.msieVersion();
19367    if (isIE === 8 || isIE === 9) {
19368        SHC.util.addPlaceholder('height_feet', 'feet');
19369        SHC.util.addPlaceholder('height_inch', 'inch');
19370        SHC.util.addPlaceholder('weight', 'pounds');
19371    }
19372};
19373
19374SHC.ui.Calculator.include({
19375    init: function (parent) {
19376
19377        "use strict";
19378        var that = this;
19379
19380        this.bmi_btn = $('#calculate_bmi');
19381        $('#calculate_bmi').addClass('disabled');
19382        $('#bmi_form').find('input').on('keydown', function () {
19383            setTimeout(function () {
19384                SHC.ui.Calculator.showResult = true;
19385                that.inspectInputs();
19386                that.inspectAllInputFields();
19387                var weight_input = $('input[name="weight"]').val();
19388                var feet_input = $('input[name="height_feet"]').val();
19389                var inch_input = $('input[name="height_inch"]').val();
19390                if (weight_input === null || weight_input === "") {
19391                    SHC.ui.Calculator.showResult = false;
19392                    $('#calculate_bmi').addClass('disabled');
19393                    $('#calculate_bmi').attr('tabindex', -1);
19394                }
19395                if (feet_input === null || feet_input === "") {
19396                    SHC.ui.Calculator.showResult = false;
19397                    $('#calculate_bmi').addClass('disabled');
19398                    $('#calculate_bmi').attr('tabindex', -1);
19399                }
19400                if (inch_input === null || inch_input === "") {
19401                    SHC.ui.Calculator.showResult = false;
19402                    $('#calculate_bmi').addClass('disabled');
19403                    $('#calculate_bmi').attr('tabindex', -1);
19404                }
19405                if (SHC.ui.Calculator.showResult) {
19406                    $('#calculate_bmi').attr('tabindex', 0);
19407                }
19408            }, 50);
19409        });
19410        $('.touch').find('#bmi_form').find('input').bind('change', function () {
19411            if (SHC.ui.Calculator.showResult) {
19412                $('#calculate_bmi').removeClass('disabled');
19413                $('#calculate_bmi').attr('tabindex', 0);
19414            }
19415        });
19416        $("#calculate_bmi").bind('click', function () {
19417            var weight = $('input[name="weight"]').val() / 2.20462;
19418            var height_feet = $('input[name="height_feet"]').val();
19419            var height_inch = $('input[name="height_inch"]').val();
19420            //Converting Height into cm
19421            var height = ((height_feet * 30.48) + (height_inch * 2.54));
19422            that.calculateBmi(weight, height);
19423        });
19424
19425    },
19426    calculateBmi: function (weight, height) {
19427        if (weight > 0 && height > 0) {
19428            SHC.ui.Calculator.bmi = (weight / (height / 100 * height / 100)).toFixed(2);
19429        } else {
19430            $('span.error').removeClass('hidden');
19431            SHC.ui.Calculator.error = true;
19432            return false;
19433        }
19434    },
19435    inspectAllInputFields: function () {
19436        var count = 0;
19437        $('.health_calculator input[type="text"]').each(function (i) {
19438            var inputValue = $(this).val();
19439            if ($(this).val()) {
19440                //show a warning?
19441                if (inputValue.match(/^[0-9]+$/) != null) {
19442                    count++;
19443                    SHC.ui.Calculator.error = false;
19444                    $(this).removeClass('error');
19445                } else {
19446                    $(this).addClass('error');
19447                    SHC.ui.Calculator.error = true;
19448                    $('span.error').removeClass('hidden');
19449                    $('#calculate_bmi').addClass('disabled');
19450                }
19451            }
19452            if (count === 0) {
19453                $('#calculate_bmi').addClass('disabled');
19454            } else if (count === 3) {
19455
19456                if (SHC.ui.Calculator.error === false) {
19457                    $('#calculate_bmi').removeClass('disabled');
19458                    $('span.error').addClass('hidden');
19459                } else {
19460                    $('#calculate_bmi').addClass('disabled');
19461                }
19462            }
19463        });
19464    },
19465
19466    inspectInputs: function () {
19467        if (($('input#height_feet').val()).match(/^[0-9]+$/) == null && ($('input#height_feet').val()) !== "") {
19468            $('.error_msg_feet').removeClass('hidden');
19469            $('input#height_feet').addClass('error');
19470            return false;
19471        } else {
19472            $('.error_msg_feet').addClass('hidden');
19473            $('input#height_feet').removeClass('error');
19474        }
19475
19476        if ($('input#height_inch').val().match(/^[0-9]+$/) == null && ($('input#height_inch').val()) !== "") {
19477            $('.error_msg_inch').removeClass('hidden');
19478            $('input#height_inch').addClass('error');
19479            return false;
19480        } else {
19481            $('.error_msg_inch').addClass('hidden');
19482            $('input#height_inch').removeClass('error');
19483        }
19484        if ($('input#weight').val().match(/^[0-9]+$/) == null && ($('input#weight').val()) !== "") {
19485            $('.error_msg_weight').removeClass('hidden');
19486            $('input#weight').addClass('error');
19487            return false;
19488        } else {
19489            $('.error_msg_weight').addClass('hidden');
19490            $('input#weight').removeClass('error');
19491        }
19492    },
19493    calculatorOnlyAllowNumbers: function (element) {
19494        element.value = element.value.replace(/\D/g, '');
19495    }
19496});
19497
19498
19499SHC.Namespace(SHC, "SHC.ui.InfoblocksContainer");
19500SHC.ui.InfoblocksContainer = new SHC.Class();
19501SHC.ui.InfoblocksContainer.include({
19502    /*
19503     * constructor
19504     *
19505     * @param handlePop Tells us whether or not to listen for pop state
19506     */
19507    init: function(parent) {
19508        var _this = this;
19509        this.parent = jQuery(parent);
19510        
19511        this.leftParsys = this.parent.find('.info-blocks-parsys-left');
19512        this.rightParsys = this.parent.find('.info-blocks-parsys-right');
19513
19514        // get started
19515        this.equalHeights();
19516        
19517        $(window).on("resizeEnd", function (e) {
19518            if (SHC.ui.screenMode === 'large') {
19519                _this.equalHeights();
19520            }
19521        });
19522    },
19523    /*
19524     * equal heights
19525     */
19526    equalHeights: function() {
19527        var _this = this;
19528        var $leftItems = _this.leftParsys.children('div');
19529        var $rightItems = _this.rightParsys.children('div');
19530        var currentIndex = 0;
19531        
19532        $leftItems.each(function() {
19533            var $this = $(this);
19534            var leftHeight = $this.outerHeight();
19535            
19536            if (currentIndex <= $rightItems.length - 1) {
19537                var $rightItem = $rightItems.eq(currentIndex);
19538                var rightHeight = $rightItem.outerHeight();
19539                
19540                if (leftHeight > rightHeight) {
19541                    $rightItem.outerHeight(leftHeight);
19542                } else {
19543                    $this.outerHeight(rightHeight);
19544                }
19545            }
19546            
19547            currentIndex++;
19548        });
19549    }
19550});
19551
19552SHC.Namespace(SHC, "SHC.ui.Marquee");
19553SHC.ui.Marquee = new SHC.Class();
19554
19555SHC.ui.Marquee.include({
19556    /*
19557     * constructor
19558     */
19559    init: function(parent) {
19560        this.parent = parent;
19561        this.disableFullImageTilePointerEventsForIE10();
19562    },
19563    // needed to mimic 'pointer-events: none' for IE10 and older
19564    disableFullImageTilePointerEventsForIE10: function() {
19565        jQuery(".make-unclickable").find("a").on("click", function(e) {
19566            e.preventDefault();
19567        });          
19568    }
19569});
19570SHC.Namespace(SHC, 'SHC.ui.EdTile');
19571SHC.ui.EdTile = new SHC.Class();
19572
19573function getThanksgivingDate(year) {
19574  // Find the fourth Thursday in November
19575  const novFirst = new Date(year, 10, 1); // November is month 10
19576  let thursdaysCount = 0;
19577  let thanksgivingDate;
19578  for (let day = 1; day <= 30; day++) {
19579      const currentDate = new Date(year, 10, day);
19580      if (currentDate.getMonth() === 10 && currentDate.getDay() === 4) {
19581          thursdaysCount++;
19582          if (thursdaysCount === 4) {
19583              thanksgivingDate = currentDate;
19584              break;
19585          }
19586      }
19587  }
19588  return thanksgivingDate;
19589}
19590
19591function isHoliday(date) {
19592  // Check if the input is a valid Date object
19593  if (!(date instanceof Date)) {
19594      throw new Error("Input must be a Date object");
19595  }  
19596  const year = date.getFullYear();
19597  // Create an array to hold the holiday dates for the specified year
19598  const holidays = [
19599      getThanksgivingDate(year),              // Thanksgiving
19600      new Date(year, 6, 4),                   // July 4th (Independence Day)
19601      new Date(year, 11, 25)                  // December 25th (Christmas)
19602  ];
19603  // Compare the year, month, and date parts against each holiday
19604  return holidays.some(holiday => 
19605      date.getFullYear() === holiday.getFullYear() && 
19606      date.getMonth() === holiday.getMonth() && 
19607      date.getDate() === holiday.getDate()
19608  );
19609}
19610
19611function isClinicOpen(currentDate) {
19612    if (!(currentDate instanceof Date)) {
19613        throw new Error("Input must be a Date object");
19614    }
19615    const currentHour = currentDate.getHours();
19616    const currentMinute = currentDate.getMinutes();
19617    const holiday = isHoliday(currentDate);
19618    let openingHour, closingHour;
19619    if (holiday) {
19620        openingHour = 10; // 10:00 AM
19621        closingHour = 15; // 3:00 PM
19622    } else {
19623        openingHour = 10; // 10:00 AM
19624        closingHour = 21; // 9:00 PM
19625    }
19626    const currentMinutes = currentHour * 60 + currentMinute;
19627    const openingMinutes = openingHour * 60; // 10:00 AM in minutes
19628    const closingMinutes = closingHour * 60; // 9:00 PM / 3:00 PM in minutes
19629    return currentMinutes >= openingMinutes && currentMinutes < closingMinutes;
19630}
19631
19632SHC.ui.EdTile.include({
19633  init: function(parent, waitTimeSource) {
19634    this.parent = parent;
19635    this.waitTimeSource = waitTimeSource;
19636    this.learnMoreLink = jQuery(parent).find('.learn-more-link');
19637    this.learnMoreLinkMobile = jQuery('.learn-more-link-mobile');
19638    this.linkToCheck = jQuery(
19639      'a.tab-heading-link[href^="' + this.learnMoreLink.attr('href') + '"]'
19640    );
19641    this.learnMoreClickHandler();
19642    this.learnMoreClickHandlerMobile();
19643    this.fetchData();
19644  },
19645  fetchData: function() {
19646    var that = this,
19647      error = jQuery(that.parent).attr('errorMsg'),
19648      errorMessage = function(text) {
19649        $(that.parent + ' .sub-text p').text(text);
19650      },
19651      getWaitTimeInMinutes = function(events) {
19652        for (var i = 0, n = events.length; i < n; i++) {
19653          var desc = events[i].description;
19654          if (desc === 'Door-First MD'|| desc === 'Door-First Provider') {
19655            return events[i].waittimes[0].waitTimeInMinutes;
19656          }
19657        }
19658        return null;
19659      },
19660      extractTime = function (str) {
19661        const date = new Date(str);
19662        const options = { hour: 'numeric', minute: 'numeric', hour12: true };
19663        return date.toLocaleTimeString('en-US', options)
19664          .replace("AM", "a.m.")
19665          .replace("PM", "p.m.");
19666      },
19667      convertToWaitTime = function(wt) {
19668        var hours = Math.floor(wt / 60);
19669        var minutes = wt % 60;
19670        if (hours > 0) {
19671          return hours + ' hr ' + minutes + ' min';
19672        } else {
19673          return minutes + ' min';
19674        }
19675      },
19676      ts = new Date().valueOf(),
19677      baseURL ='/bin/connector/er.json',
19678      url = baseURL + '?ts=' + ts;
19679    
19680    let source = "shc";
19681    if (that.waitTimeSource === 'shc-pedia') {
19682      url = baseURL+'?source=ped&ts=' + ts;
19683    } else if (that.waitTimeSource === 'valleycare') {
19684      url = baseURL+'?source=vc&ts=' + ts;
19685    } else if (that.waitTimeSource === 'dublin') {
19686      url = baseURL+'?source=dublin&ts=' + ts;
19687    } else if (that.waitTimeSource === 'livermore') {
19688      url = baseURL+'?source=livermore&ts=' + ts;
19689    }
19690
19691    var isUrgentCare = (that.waitTimeSource === 'dublin' || that.waitTimeSource === 'livermore');
19692    var dateNow = new Date();
19693    var options = { hour: 'numeric', minute: 'numeric', hour12: true };
19694    var now = dateNow.toLocaleTimeString('en-US', options)
19695      .replace("AM", "a.m.")
19696      .replace("PM", "p.m.");
19697    $(this.parent + ' .last-updated').text('Last updated ' + now);
19698    
19699    $.ajax({
19700      type: 'GET',
19701      url: url, // client to new MyHealth hosted service.
19702      success: function (data) {
19703        if (isUrgentCare && !isClinicOpen(dateNow)) {
19704          $(that.parent + ' .display-time').html('<span>Opens at 10 a.m.</span>');
19705
19706        } else if (data && data.meta && data.meta.code === 200) {
19707          var waittime = null;
19708          var lastUpdated;
19709          if (data && data.lastUpdatedAt) {
19710            lastUpdated = extractTime(data.lastUpdatedAt);
19711            // console.log('lastUpdated', lastUpdated);
19712            $(that.parent + ' .last-updated').text('Last updated ' + lastUpdated);
19713          }
19714          if (typeof data.events !== 'undefined') {
19715            waittime = getWaitTimeInMinutes(data.events);
19716          }
19717          if (waittime !== null) {
19718            var time = convertToWaitTime(waittime);
19719            // console.log('time', time);
19720            $(that.parent + ' .display-time').text(time);
19721          } else {
19722            errorMessage(error);
19723          }
19724        } else {
19725          errorMessage(error);
19726        }
19727      },
19728      error: function (jqXHR, textStatus, errorThrown) {
19729        errorMessage(error);
19730      },
19731    });
19732
19733    setInterval(function() {
19734      window.location.reload();
19735    }, 600000);
19736  },
19737  //Learn more click handler for large and medium screens
19738  learnMoreClickHandler: function() {
19739    var that = this;
19740    // treat as a normal link if it's not a subpage
19741    if (that.checkTabsForLink(that.linkToCheck)) {
19742      that.learnMoreLink.on('click', function(e) {
19743        e.preventDefault();
19744
19745        //get heights and whatnot
19746        var linkedTab = that.linkToCheck.eq(1); //get desktop link
19747        var positionOfTopOfTabnav = jQuery('#tab-nav').offset().top;
19748        var heightOfSearch = jQuery('#search-inpagenav').height();
19749        var heightOfTitle = jQuery(
19750          '.shared-top-content-iparsys .general_container .title'
19751        ).height();
19752        var mobileOffset = jQuery('#tab-nav-toggle-wrapper').offset().top;
19753        var currentPosition = $('body').scrollTop();
19754        var positionToScrollTo =
19755          positionOfTopOfTabnav +
19756          mobileOffset -
19757          heightOfSearch -
19758          heightOfTitle -
19759          currentPosition;
19760
19761        // simulate tab click
19762        linkedTab.click();
19763
19764        // scroll to opened tab
19765        $('html, body').animate({ scrollTop: positionToScrollTo }, 500);
19766      });
19767    }
19768  },
19769  learnMoreClickHandlerMobile: function() {
19770    var that = this;
19771    // treat as a normal link if it's not a subpage
19772    if (that.checkTabsForLink(that.linkToCheck)) {
19773      that.learnMoreLinkMobile.on('click', function(e) {
19774        e.preventDefault();
19775
19776        //get heights and whatnot
19777        var linkedTab = that.linkToCheck.eq(0);
19778        var positionOfTopOfTabnav = 0;
19779        var heightOfSearch = 0;
19780        //medium size uses elements from mobile and large screen size, adjusting accordingly
19781        if (SHC.ui.screenMode !== 'small') {
19782          positionOfTopOfTabnav = jQuery('#tab-nav').offset().top;
19783          heightOfSearch = jQuery('#search-inpagenav').height();
19784        } else {
19785          positionOfTopOfTabnav = jQuery('#tab-nav-mobile').offset().top;
19786        }
19787        var heightOfTitle = jQuery(
19788          '.shared-top-content-iparsys .general_container .title'
19789        ).height();
19790        var mobileOffset = jQuery('#tab-nav-toggle-wrapper').offset().top;
19791        var currentPosition = $('body').scrollTop();
19792        var positionToScrollTo =
19793          positionOfTopOfTabnav +
19794          mobileOffset -
19795          heightOfTitle -
19796          heightOfSearch -
19797          currentPosition;
19798
19799        // simulate tab click
19800        linkedTab.click();
19801
19802        // scroll to opened tab
19803        $('html, body').animate({ scrollTop: positionToScrollTo }, 500);
19804      });
19805    }
19806  },
19807  //Check if Learn More links to a subpage
19808  checkTabsForLink: function(link) {
19809    var that = this;
19810    if (link.attr('href')) {
19811      return true;
19812    }
19813    return false;
19814  },
19815});
19816
19817SHC.Namespace(SHC, "SHC.ui.MultiMapTile");
19818SHC.ui.MultiMapTile = new SHC.Class();
19819
19820SHC.ui.MultiMapTile.include({
19821    init: function () {
19822        this.$dataHubpageName = jQuery(".multi-location-tile").attr("data-hubpage-name");
19823        this.$imageTarget = jQuery(".multi-map-static-image");
19824        this.l3ServletRequestPath = "/bin/api/v1/content/shcmap.clinic.";
19825        this.campaignServletRequestPath = "/bin/api/v1/content/shcmap.campaign.";
19826        this.defaultImgPath = "/etc/clientlibs/shc/main/img/Default_Clinic_Image_320_Marquee.jpg";
19827
19828        this.getStaticMapImage();
19829    },
19830
19831    getStaticMapImage: function (){
19832        var that = this;
19833        var googleStaticUrl = "";
19834        var targetUrl = "";
19835        var currentPagePath = window.location.pathname;
19836
19837        if(currentPagePath.indexOf("campaigns") > -1) {
19838            targetUrl = that.campaignServletRequestPath + that.$dataHubpageName + ".add-clinics.json";
19839        }
19840        else {
19841            targetUrl = that.l3ServletRequestPath + that.$dataHubpageName + ".add-clinics.json";
19842        }
19843
19844        // hit our servlet to give us our info about related l3 clinics
19845        var request = jQuery.ajax({
19846            url: targetUrl,
19847            async: true,
19848            contentType: "application/json",
19849            statusCode: {
19850                500: function() {
19851                    jQuery(".multi-location-tile .tile-box-overlay-text.open-modal").html('No L3 clinics associated with this page');
19852                    that.$imageTarget.attr("src", that.defaultImgPath);
19853                }
19854            }
19855        }).done(function(data) {
19856                googleStaticUrl = that.buildMapUrl(data);
19857                that.$imageTarget.attr("src", googleStaticUrl);
19858        });
19859    },
19860
19861    buildMapUrl: function(data){
19862
19863        var baseUrl = "https://maps.googleapis.com/maps/api/staticmap?center=";
19864        var center = data.mapaverages[0].avgLat + "," + data.mapaverages[0].avgLng;
19865        var iconPath = "&size=221x221&scale=2&sensor=false";
19866        var coords = "";
19867        var apiKey = "&key=" + SHC.util.getGoogleAPIKey();
19868
19869        jQuery.each(data.maplocations, function(key, locationInfo){
19870            var endString = "&markers=";
19871
19872            var markerString = endString + locationInfo.latitude + "," + locationInfo.longitude;
19873            coords += markerString;
19874            return (key < 5);
19875        });
19876
19877        var finishedUrl = baseUrl + center + iconPath + coords + apiKey;
19878
19879        return finishedUrl;
19880    }
19881
19882});
19883SHC.Namespace(SHC, "SHC.ui.AwardsTile");
19884SHC.ui.AwardsTile = new SHC.Class();
19885
19886SHC.ui.AwardsTile.include({
19887    init: function (parent) {
19888        this.parent = $(parent);
19889        this.learnMoreLink = this.parent.find(".learn-more-link");
19890        this.linkToCheck = jQuery('a.tab-heading-link[href^="' + this.learnMoreLink.attr("href") + '"]');
19891        this.learnMoreClickHandler();
19892    },
19893    //Learn more click handler for large and medium screens
19894    learnMoreClickHandler: function () {
19895        var that = this;
19896        // treat as a normal link if it's not a subpage
19897        if (that.checkTabsForLink(that.linkToCheck)) {
19898            that.learnMoreLink.on("click", function (e) {
19899                e.preventDefault();
19900                
19901                //get heights and whatnot
19902                var linkedTab = that.linkToCheck.eq(1); //get desktop link
19903                var positionOfTopOfTabnav = jQuery("#tab-nav").offset().top;
19904                var heightOfSearch = jQuery("#search-inpagenav").height();
19905                var heightOfTitle = jQuery(".shared-top-content-iparsys .general_container .title").height();
19906                var mobileOffset = jQuery("#tab-nav-toggle-wrapper").offset().top;
19907                var currentPosition = $("body").scrollTop();
19908                var positionToScrollTo = positionOfTopOfTabnav + mobileOffset - heightOfSearch - heightOfTitle - currentPosition;
19909                
19910                // simulate tab click
19911                linkedTab.click();
19912                
19913                // scroll to opened tab
19914                $("html, body").animate({scrollTop: positionToScrollTo}, 500);
19915            });
19916        }
19917    },
19918    
19919    //Check if Learn More links to a subpage
19920    checkTabsForLink: function (link) {
19921        var that = this;
19922        if (link.attr('href')) {
19923            return true;
19924        }
19925        return false;
19926    }
19927});
19928SHC.Namespace(SHC, "SHC.ui.TileTruncation");
19929SHC.ui.TileTruncation = new SHC.Class();
19930
19931SHC.ui.TileTruncation.include({
19932    init: function () {
19933        var that = this;          
19934        that.setTileTruncation();
19935        that.truncateVideoArticleTiles();
19936        //call trunk8 again to redo truncation on a resize of the window
19937        $(window).on('resizeEnd', function(){
19938            that.setTileTruncation();
19939        });
19940        
19941    },
19942    //sets truncation of long text for event and story tiles in the marquee
19943    setTileTruncation: function () {   
19944        if(SHC.ui.screenMode === "medium") {               
19945            $('.tile.section .story-tile').find('.description').trunk8({
19946               lines: 4
19947            });
19948            $('.has-location .tile.section .story-tile').find('.description').trunk8({
19949               lines: 6
19950            }); 
19951        } else {             
19952            $('.tile.section .story-tile').find('.description').trunk8({
19953               lines: 6
19954            });
19955        }
19956        $('.event-tile').find('.hidden-for-mobile').trunk8({
19957            lines: 4
19958        });
19959        $('.event-tile').find('.visible-for-mobile').trunk8({
19960            lines: 3
19961        });                      
19962    },
19963    
19964    truncateVideoArticleTiles: function() {
19965        var fadeSpeed = 250;
19966        var wordAnimateSpeed = 350;
19967        var animationEasing = 'easeOutQuad';
19968        var oldHeight;
19969        jQuery('.shc-tile-article').find('.tile-overlay-hover').hide();
19970        var videoTileDescription = jQuery('.shc-tile-article').find('span.description');
19971        //tell our plugin to truncate our tile description to the word and not letter
19972        videoTileDescription.dotdotdot({
19973            height: 40,
19974            wrap: 'word'
19975         });
19976         //on hover behavior
19977         jQuery('.shc-tile-article').unbind('mouseenter mouseleave').hover(
19978            function() {
19979                //calculate the beginning height of the truncated div
19980                oldHeight = $(this).find('span.description').outerHeight();
19981                $(this).find('span.description').css({height:oldHeight});
19982                //on hover in:
19983                //fade in the darker overlay
19984                $(this).find('.tile-overlay-hover').stop(true,true).fadeIn(fadeSpeed);
19985                //fade out the lighter overlay so the bottom isn't too dark
19986                $(this).find('.tile-overlay-gradient').stop(true,true).fadeOut(fadeSpeed);
19987                //get the original content (untruncated version)
19988                var fullContent = $(this).find('span.description').triggerHandler('originalContent');    
19989                //empty the description div
19990                $(this).find('span.description').empty();
19991                //add the full content back in the description div
19992                $(this).find('span.description').append(fullContent);
19993                //calculate new height of the new content
19994                var newHeight = $(this).find('span.description')[0].scrollHeight;
19995                //animate the description with the new full text up to the full height so all of it is showing
19996                if ((newHeight - 1) > oldHeight){
19997                    $(this).find('span.description').stop().animate({height:newHeight}, wordAnimateSpeed, animationEasing);
19998                }
19999                //animate the duration into the tile
20000                $(this).find('span.duration').stop().animate({height : '42px', opacity : 1}, wordAnimateSpeed, animationEasing);
20001            }, function() {
20002                //on hover out:
20003                var that = this;
20004                //bring back our original overlay 
20005                $(this).find('.tile-overlay-gradient').stop(true, true).fadeIn(100);
20006                //get rid of the darker overlay
20007                $(this).find('.tile-overlay-hover').stop(true,true).fadeOut(fadeSpeed);
20008                //change our description div height to the original beginning height
20009                $(this).find('span.description').stop().animate({height:oldHeight}, wordAnimateSpeed, animationEasing, function(){
20010                    //upon completion, update our truncation
20011                    $(that).find('span.description').trigger('update.dot');
20012                });
20013                //get rid of duration
20014                $(this).find('span.duration').stop().animate({height : '0px', opacity : 0}, wordAnimateSpeed, animationEasing);
20015            });
20016    }
20017});
20018SHC.Namespace(SHC, "SHC.ui.Disclaimer_Button");
20019SHC.ui.Disclaimer_Button = new SHC.Class();
20020
20021SHC.ui.Disclaimer_Button.include({
20022    /*
20023     constructor
20024     */
20025    init: function(buttons) {
20026        var that = this;
20027        this.buttons = $(buttons);
20028
20029
20030        this.buttons.each(function() {
20031            that.activate($(this));
20032        });
20033    },
20034    /*
20035     * activate disclaimer buttons
20036     */
20037    activate: function(button) {
20038        var that = this;
20039
20040        var handleClick = function() {
20041            that.setDisclaimerCookieTrue();
20042            window.location.replace(that.urlParam("url"));
20043        };
20044
20045        button.on("click", handleClick);
20046
20047    },
20048    urlParam: function(name) {
20049        var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
20050        if (results === null) {
20051            return null;
20052        } else {
20053            return results[1] || 0;
20054        }
20055    },
20056    setDisclaimerCookieTrue: function() {
20057        var setDisclaimer = "disclaimer";
20058        var setTrue = "true";
20059        document.cookie = setDisclaimer + "=" + setTrue + ";path=/;";
20060    }
20061});
20062SHC.Namespace(SHC, "SHC.ui.DrStory");
20063SHC.ui.DrStory = new SHC.Class();
20064
20065SHC.ui.DrStory.include({
20066    /*
20067     * constructor
20068     */
20069    init: function() {
20070        
20071        this.$viewAllStoriesButton = jQuery('.doctor-story-tile-wrapper').find('.view-all-stories-btn');
20072        this.$restOfVids = jQuery('.doctor-story-tile-wrapper').find('.rest-of-the-vids');
20073        this.$fourthTile = jQuery('.doctor-story-tile-wrapper').find('.shc-tile.fourth');
20074        
20075        this.activate();
20076    },
20077
20078    activate: function() {
20079        var that = this;
20080        //set up handler for button to show all videos
20081        var viewAllStoriesButtonHandler = function(e) {
20082            e.preventDefault();
20083            that.$fourthTile.removeClass('fourth');
20084            that.$viewAllStoriesButton.hide();
20085            that.$restOfVids.addClass('show');
20086            
20087            var tileTruncation = new  SHC.ui.TileTruncation();
20088        };
20089        
20090        $(document).on('smallBreakpointChange', function() {
20091            if(($(this).data('size') !== 'small')){
20092                var tileTruncation = new SHC.ui.TileTruncation();
20093            }
20094        });
20095      
20096        that.$viewAllStoriesButton.off().on('click.dr-story', viewAllStoriesButtonHandler);
20097      
20098    }
20099});
20100SHC.Namespace(SHC, "SHC.ui.InPageNav");
20101SHC.ui.InPageNav = new SHC.Class();
20102SHC.ui.InPageNav.include({
20103    /**
20104     * constructor
20105     */
20106    init: function(parent) {
20107        this.self = $(parent);
20108        this.parent = parent;
20109        this.initInPageNav();
20110        this.setup();
20111        this.isAuthorMode = SHC.util.WCM.isAuthorMode();
20112    },
20113    setup: function() {
20114        var that = this;
20115        var scrollHeight = jQuery('#search-inpagenav').height();
20116
20117        var dropDownButtonClickHandler = function(e) {
20118            e.preventDefault();
20119            that.self.find('#drop-nav-wrapper').slideToggle("fast");
20120        };
20121
20122        var dropDownNavWrapperClickHandler = function(e) {
20123            jQuery('#drop-nav-wrapper').hide();
20124            var elementToScrollTo = $(this).attr('href') + "_";
20125            var scrollHeight = jQuery('#search-inpagenav').height() + 12;
20126
20127            var emergencyAlert = $('#new-emergency-alert');
20128            if (emergencyAlert.length > 0) {
20129              scrollHeight += emergencyAlert.height();
20130            }
20131            $('html, body').animate({
20132                scrollTop: ($(elementToScrollTo).offset().top - scrollHeight)
20133            }, 500);
20134        };
20135
20136        var backToTopClickHandler = function(e) {
20137            $("html, body").animate({scrollTop: 0}, 500);
20138            return false;
20139        };
20140
20141        // clicking heading in small mode opens dropdown, in large scrolls
20142        var navButtonClickHandler = function(e) {
20143                e.preventDefault();
20144                var elementToScrollTo = $(this).attr('href') + "_";
20145                scrollHeight = jQuery('#search-inpagenav').height() + 31;
20146
20147                var emergencyAlert = $('#new-emergency-alert');
20148                if (emergencyAlert.length > 0) {
20149                  scrollHeight += emergencyAlert.height();
20150                }
20151                $('html, body').animate({
20152                    scrollTop: ($(elementToScrollTo).offset().top - scrollHeight)
20153                }, 500);
20154        };
20155
20156        that.setHeights();
20157
20158        that.self.find('.drop-down-button').on("click", dropDownButtonClickHandler);
20159        that.self.find('#drop-nav-wrapper a').on("click", dropDownNavWrapperClickHandler);
20160        that.self.find('#back-to-top').on("click", backToTopClickHandler);
20161        that.self.find('.nav-button').on("click", navButtonClickHandler);
20162    },
20163    initInPageNav: function() {
20164        var that = this;
20165        var collapsing = false;
20166
20167        /*****************/
20168        /** in-page-nav **/
20169        /*****************/
20170        /** NOTE: offest calculations may need to be changed depending on how final template is set up **/
20171        var inPageNavOffset = that.self.find('#header').outerHeight();
20172        var inPageNavHeight = that.self.find('#in-page-nav').outerHeight(true);
20173        this.self.find('#in-page-nav-wrapper').height(inPageNavHeight);
20174
20175        var count = 0;
20176        var sections = jQuery("h1[data-nav-show='true'], h2[data-nav-show='true'], h3[data-nav-show='true'], h4[data-nav-show='true'], h5[data-nav-show='true'], h6[data-nav-show='true']");
20177        if (sections.length > 0) {
20178            // add 'nospy' class which tells scrollspy not to track this element
20179            sections.addClass("nospy");
20180            sections.each(function() {
20181                if ((count < 6)) {
20182                    var title = jQuery(this).data('nav') || jQuery(this).attr('nav');
20183                    var id = jQuery(this).attr('id');
20184                    if (id.charAt(id.length - 1) === '_') {
20185                        id = id.substring(0, id.length - 1); // cut of the trailing underscore
20186                    }
20187                    var string = '<li><a href="#' + id + '" class="nav-button">' + title + '</a><a href="#" class="drop-down-button"><span></span></a></li>';
20188                    var dropString = '<li><a href="#' + id + '">' + title + '</a></li>';
20189                    jQuery('#in-page-nav ul.nav').append(string);
20190                    jQuery('#in-page-nav ul.drop-nav').append(dropString);
20191                }
20192                count++;
20193            });
20194
20195            that.self.find('#in-page-nav').show();
20196        } else {
20197            that.self.find('#in-page-nav').hide();
20198        }
20199
20200        jQuery(window).on('load', function() {
20201            that.showOrCollapseNav(count);
20202        });
20203
20204        //stop search-inpagenav when it hits the footer
20205        $(window).scroll(function() {
20206            var offsetAmount = 60;
20207            if ($('#filter-area')) {
20208                offsetAmount = ($('#filter-area').height() + 55);
20209            }
20210            if ((jQuery('#search-inpagenav').height() + $(window).scrollTop()) > (jQuery('.fatfooter').offset().top - offsetAmount)) {
20211                $('#search-inpagenav').addClass('footer-locked');
20212                $('#search-inpagenav').css({
20213                    top: (jQuery('.fatfooter').offset().top - ($('#search-inpagenav').height()) - offsetAmount)
20214                });
20215            }
20216            if ((jQuery('#search-inpagenav').height() + $(window).scrollTop()) < ($('.fatfooter').offset().top - offsetAmount)) {
20217                $('#search-inpagenav').removeClass('footer-locked');
20218                $('#search-inpagenav').css({
20219                    top: 0
20220                });
20221            }
20222        });
20223
20224        var reTimer;
20225        jQuery(window).on('resize', function() {
20226            setTimeout(function(){that.showOrCollapseNav(count);}, 200);
20227            clearTimeout(reTimer);
20228            that.setHeights();
20229        });
20230
20231    },
20232    showOrCollapseNav: function(count) {
20233            var windowSize = SHC.ui.screenMode;
20234            //hide the medium in-page-nav when in large screen
20235            if(windowSize === 'large'){
20236                jQuery('#drop-nav-wrapper').hide();
20237                jQuery("#in-page-nav-wrapper").removeClass("toolong");
20238            }
20239            else if (windowSize !== 'large' && count > 3){
20240                jQuery("#in-page-nav-list-wrapper li.active").removeClass("active");
20241                jQuery("#in-page-nav-list-wrapper li:first").addClass("active");
20242                jQuery("#in-page-nav-wrapper").addClass("toolong");
20243            }
20244    },
20245    setHeights: function() {
20246        if ($('#in-page-nav').css('display') === 'none') {
20247            jQuery('#in-page-nav-wrapper').hide();
20248            jQuery('.in-page-nav-shadow').hide();
20249        } else {
20250            jQuery('.search-container-shadow').hide();
20251        }
20252
20253        //set offset and scrolling for anchor tags found in rich text components and phone number component
20254        var offsetCushion;
20255        if(SHC.ui.screenMode === "small"){
20256            offsetCushion = 12;
20257        } else {
20258            offsetCushion = 31;
20259        }
20260        var scrollHeight = jQuery('#search-inpagenav').height() + offsetCushion;
20261//            $('.rte-has-anchor-link').localScroll({
20262//                offset : -(scrollHeight),
20263//                duration : 500,
20264//                hash: true
20265//            });
20266    }
20267});
20268SHC.Namespace(SHC, "SHC.ui.Modal");
20269SHC.ui.Modal = new SHC.Class();
20270
20271function loadYoutube() {
20272    if (typeof onYouTubeIframeAPIReady === "undefined") {
20273        window.requestAnimationFrame(loadYoutube);
20274    } else {
20275        if (typeof onYouTubeIframeAPIReady !== 'undefined' && jQuery.isFunction(onYouTubeIframeAPIReady)) {
20276            onYouTubeIframeAPIReady();
20277        }
20278    }
20279}
20280
20281SHC.ui.Modal.include({
20282    /**
20283     * constructor
20284     * @param parent
20285     */
20286    init: function (parent, modalLoadedEvent) {
20287        this.DEFAULT_TOP_OFFSET = 40;
20288        this.NEW_MODAL_TOP_OFFSET = 304;
20289        this.NEW_MODAL_TOP_OFFSET_MOBILE = 70;
20290        this.parent = parent;
20291        this.modalLoadedEvent = modalLoadedEvent;
20292        // Containers and elements
20293        this.htmlTag = $('html');
20294        this.overlay = $('#overlay');
20295        this.modalCloseBtn = $('#modal-close');
20296        this.modal = $('#modal');
20297        this.modalContainer = $('#modal-container');
20298        this.modalContent = $('#modal-content');
20299        this.modalHeight = 0;
20300        this.modalTopOffset = this.DEFAULT_TOP_OFFSET;
20301        this.main = $('#main');
20302        this.mainContainer = $('#main-container');
20303        this.contentContainer = $('#content');
20304        this.imageModal = false;
20305        this.modalPadding = true;
20306        this.modalCaption = false;
20307        this.preventClickiness = false;
20308        this.modalAnimateToPosition = this.modalTopOffset;
20309        this.mainPageFocus = null;
20310        this.focusableElementsString = "a[href], area[href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), button:not([disabled]), iframe, object, embed, *[tabindex], *[contenteditable]";
20311        this.spinner = $("#overlay").find(".spinner-container");
20312
20313        this.searchInPageNav = $('#search-inpagenav');
20314        this.inPageNav = $('#in-page-nav');
20315        this.inPageNavAnchors = this.inPageNav.find(".nav li a");
20316        this.underline = $('#underline');
20317        this.backToTop = $('#back-to-top');
20318        this.shadow = $('.in-page-nav-shadow');
20319        this.activeNavActive = null;
20320        var self = this,
20321            modals = $(parent);
20322
20323        modals.each(function () {
20324            self.setupModal(this);
20325        });
20326    },
20327    clearModalContent: function () {
20328        // shut it down / reset stuff.
20329        this.spinner.hide();
20330        this.overlay.hide();
20331        this.htmlTag.removeClass('fixed');
20332        this.modal.attr('style', '');
20333        this.modalContainer.attr('style', '').hide();
20334        this.modalContent.empty().attr('style', '');
20335        this.modalCloseBtn.attr('style', '').removeClass('fixed');
20336        this.modalPadding = true;
20337        this.imageModal = false;
20338        $(window).scrollTop(this.scrollPosition);
20339        this.main.css({top: '0px'});
20340    },
20341    setupModal: function (modal) {
20342        var that = this,
20343            modalLink = $(modal);
20344        modalLink.off('click.modalLink').on('click.modalLink', function (event) {
20345            var clickedModalLink = this;
20346            var l3DocProfile = $('.l3-doctor-profile');
20347            var currentNPI = "";
20348            if (l3DocProfile.length > 0) {
20349                currentNPI = event.target.getAttribute('data-npi') || "";
20350            }
20351            //Set focusable element
20352            that.mainPageFocus = $(document.activeElement);
20353            //add aria-label attribute to modal container - RSW-17965
20354            if(modalLink.data('modaltitle')) {
20355                that.modalContainer.attr('aria-label',modalLink.data('modaltitle'));
20356            }
20357            //hide content outside of modal from screenreader
20358            $('body').children('div:not(#modal),a').each(function(){
20359                $(this).attr('inert','');
20360            });
20361            event.preventDefault();
20362            if (!that.preventClickiness) {
20363                // set variable to true to prevent multiple clicks from happening
20364                // and possibly loading in duplicate content.
20365                that.preventClickiness = true;
20366                // clear things out just in case and set things to their default state.
20367                //that.clearModalContent();
20368                // get window and scroll properties on click.
20369                that.getWindowProperties();
20370                //update top offset for new/redesigned modal
20371                if($(clickedModalLink).hasClass('new-modal')) {
20372                    that.modalTopOffset = $(window).width() > 767 ? that.NEW_MODAL_TOP_OFFSET : that.NEW_MODAL_TOP_OFFSET_MOBILE;
20373                } else {
20374                    that.modalTopOffset = that.DEFAULT_TOP_OFFSET;
20375                }
20376                that.modalAnimateToPosition = that.modalTopOffset;
20377                // get url for page to load content from.
20378                var modalLinkURL = modalLink.attr('href'),
20379                    modalLinkAltText = modalLink.attr('alt'),
20380                    targetContainer = '',
20381                    contentType = '',
20382                    caption = '';
20383
20384                if (modalLink.data('modalcontainer')) {
20385                    targetContainer = modalLink.data('modalcontainer');
20386                }
20387                if (modalLink.data('modalcontenttype')) {
20388                    contentType = ' ' + modalLink.data('modalcontenttype');
20389                }
20390                if ((!modalLink.data('modalpadding')) &&
20391                    (typeof(modalLink.data('modalpadding')) !== 'undefined')) {
20392                    that.modalPadding = false;
20393                } else {
20394                    that.modalPadding = true;
20395                }
20396                if (modalLink.data('caption')) {
20397                    that.modalCaption = true;
20398                    caption = modalLink.data('caption');
20399                    // create caption contianer
20400                    $('<div />').attr({'class': 'caption'}).appendTo(that.modalContainer);
20401                }
20402                // if external link, use separate handling
20403                if (targetContainer === ".external-link") {
20404                    that.externalLinkHandling(clickedModalLink);
20405                } else {
20406                    that.getModalData(modalLinkURL, targetContainer, contentType, caption, modalLinkAltText, currentNPI);
20407                }
20408            }
20409            if ($(window).width() > 767) {
20410                that.main.css({top: '-' + that.scrollPosition + 'px'});
20411            } else {
20412                that.main.css({top: '0px'});
20413            }
20414        });
20415    },
20416    getWindowProperties: function () {
20417        this.windowHeight = $(window).height();
20418        this.scrollPosition = $(window).scrollTop();
20419    },
20420    sizeModalImage: function () {
20421        var modalImage = this.modalContent.find('img'),
20422            imageWidth = modalImage.data('origwidth'),
20423            imageHeight = modalImage.data('origheight'),
20424            windowWidth = $(window).width(),
20425            resizedWidth = (windowWidth - 150);
20426
20427        if (resizedWidth !== imageWidth) {
20428            var aspectRatio = (imageHeight / imageWidth),
20429                newHeight = parseInt((resizedWidth * aspectRatio), 10);
20430
20431            if (imageWidth < resizedWidth) {
20432                newHeight = imageHeight;
20433            } else {
20434                imageWidth = resizedWidth;
20435            }
20436            if (this.modalPadding) {
20437                modalImage.css({width: '100%', height: parseInt((newHeight - this.DEFAULT_TOP_OFFSET), 10)});
20438            } else {
20439                modalImage.width(imageWidth).height(newHeight);
20440            }
20441            this.modal.css({'width': imageWidth});
20442            this.modalCloseBtn.css({'width': imageWidth});
20443        }
20444    },
20445    externalLinkHandling: function (modalLink) {
20446        var modalLinkObj = jQuery(modalLink);
20447        var linkHref = modalLinkObj.attr("href");
20448        window.location.href = linkHref;
20449    },
20450    getModalData: function (modalURL, targetContainer, contentType, caption, altText, npi) {
20451        if (modalURL.indexOf(".mapmodal.") !== -1) {
20452            modalURL = modalURL.replace(".mapmodal.", ".mapmodalcontent.");
20453        }
20454        if (modalURL.indexOf(".multimapmodal.") !== -1) {
20455            modalURL = modalURL.replace(".multimapmodal.", ".multi_clinic_map.");
20456        }
20457        var that = this,
20458            link = modalURL,
20459            imageFileTypes = ['jpg', 'png', 'jpeg', 'gif', 'bmp', 'wbmp'],
20460            hashPos = modalURL.indexOf('?'),
20461            questionPos = modalURL.indexOf('#'),
20462            urlExtension = modalURL;
20463
20464        that.modalContainer.css({display: 'block', visibility: 'hidden'});
20465        if (!that.modalPadding) {
20466            that.modalContent.css({padding: 0});
20467        }
20468        if (hashPos > -1) {
20469            urlExtension = urlExtension.substr(0, hashPos);
20470        }
20471        if (questionPos > -1) {
20472            urlExtension = urlExtension.substr(0, questionPos);
20473        }
20474
20475        urlExtension = urlExtension.substr(urlExtension.lastIndexOf('.') + 1);
20476
20477        // test if modal content is image or html
20478        if ($.inArray(urlExtension, imageFileTypes) > -1 || contentType === 'image') {
20479            // load image and put it in the modal.
20480            // imgLoadCheck will wait until image is loaded before continuing.
20481            SHC.util.imgLoadCheck($('<img />', {src: modalURL, alt: altText}), {
20482                onComplete: function (loadedImgs) {
20483                    var modalImage = loadedImgs[0];
20484                    modalImage.appendTo(that.modalContent);
20485                    modalImage.attr('data-origWidth', modalImage.width());
20486                    modalImage.attr('data-origHeight', modalImage.height());
20487                    that.sizeModalImage();
20488                    that.imageModal = true;
20489                    that.modal.addClass('lightbox');
20490                    that.positionModalOffPage();
20491
20492                }
20493            });
20494            if (that.modalCaption) {
20495                that.modalContainer.find('.caption').append(caption);
20496            }
20497            that.spinner.hide();
20498        } else {
20499            $.ajax({
20500                url: link,
20501                dataType: "html"
20502            }).done(function (data) {
20503                that.spinner.hide();
20504                if (targetContainer) {
20505                    var modalContentData = $(data).find(targetContainer);
20506                    if (modalContentData.length > 0) {
20507                        that.modalContent.empty();
20508                        modalContentData.appendTo(that.modalContent);
20509                    } else {
20510                        modalContentData = jQuery(jQuery.parseHTML(data)).filter(targetContainer);
20511                        if (modalContentData.length > 0) {
20512                            that.modalContent.empty();
20513                            modalContentData.appendTo(that.modalContent);
20514                        } else {
20515                            //In the ajax request, we didn't find the target container we wanted, return without opening anything. :(
20516                            //TODO: We need to figure out something better to do when we don't have to proper modal content...
20517                            that.closeListener();
20518                            $('.close-modal').trigger("click");
20519                            return;
20520                        }
20521                    }
20522                } else {
20523                    $(data).appendTo(that.modalContent);
20524                }
20525
20526                if ($('.location-page.clinic-mapmodalcontent').length) {
20527                    var officeMarkerPath = $('.location-page.clinic-mapmodalcontent').attr('officeMarkerPath');
20528                    var showLink = true;
20529                    jQuery('.map-target').load(officeMarkerPath + '.html #map-container', function () {
20530                        var locationPage = new SHC.ui.LocationPage(showLink);
20531                    });
20532                } else if ($('.location-page.clinic-multi-clinic-map').length) {
20533                    var slingResourcePath = $('.location-page.clinic-multi-clinic-map').attr('requestPath');
20534                    var map;
20535                    var splitSlashArray = slingResourcePath.split('/');
20536                    var l2Name = splitSlashArray[splitSlashArray.length - 2];
20537                    map = new SHC.ui.Map(function () {
20538                        map.doL3Request(l2Name);
20539                    });
20540                }
20541
20542                // Initialize YTPlayer for all iframes in the modal
20543                const iframes = that.modalContent.find('iframe[type="text/html"]');
20544                iframes.each(function () {
20545                    const iframe = $(this);
20546                    iframe.YTPlayer({
20547                        fitToBackground: false,
20548                        mute: false,
20549                        repeat: false,
20550                        playerVars: {
20551                            autoplay: 1,
20552                            controls: 1,
20553                            modestbranding: 1,
20554                            rel: 0,
20555                            showinfo: 0
20556                        }
20557                    });
20558                });
20559
20560                // display correct image for window size.
20561                $(document).trigger('debouncedresize');
20562                that.positionModalOffPage();
20563
20564                var calc;
20565                if (targetContainer === ".make-an-appt") {
20566                    that.renderMakeAppointment(data, npi);
20567                    $('input, textarea').placeholder();
20568                } else if (targetContainer === "#quizcontainer") {
20569                    that.renderTakeQuiz();
20570                } else if (targetContainer === "#modal_container_bmi") {
20571                    calc = new SHC.ui.Calculator.show();
20572                    attachValidation();
20573                } else if (targetContainer === ".location-page") {
20574                    var locationPage = new SHC.ui.LocationPage();
20575                } else if (targetContainer === "#comments") {
20576                    if ($('.numericRatings').attr('value')) {
20577                        var rating = parseFloat($('.numericRatings').attr('value'));
20578                        var width = ((parseFloat(rating) / 5) * 100) + '%';
20579                        $('.press_ganey_ratings').find('.rating_bar_big').find('div').css('width', width);
20580                        $('.press_ganey_ratings').find('.rating_bar').find('div').css('width', width);
20581                    } else {
20582                        $('.press_ganey_ratings').find('.rating_bar_big').find('div').css('width', '0%');
20583                        $('.press_ganey_ratings').find('.rating_bar').find('div').css('width', '0%');
20584                    }
20585                }
20586                // check if the modal contents contain a form. If so, attach form validation
20587                if ($(targetContainer).has('form').length > 0) {
20588                    attachValidation();
20589                }
20590                if (typeof loadLargeImageGallery === 'function') {
20591                    $('.gallery-items.slick-initialized').slick('unslick');
20592                    loadLargeImageGallery();
20593                }
20594                that.modalLinkClickListener();
20595                that.fireModalLoadedEvent(that);
20596            }).fail(function () {
20597                that.spinner.hide();
20598                that.closeListener();
20599                $('.close-modal').trigger("click");
20600            });
20601        }
20602    },
20603    fireModalLoadedEvent: function (context) {
20604        if (context.modalLoadedEvent) {
20605            var e = jQuery.Event(context.modalLoadedEvent);
20606            jQuery(window).trigger(e);
20607        }
20608    },
20609    getModalDimensions: function () {
20610        this.modalHeight = this.modalContainer.outerHeight(true);
20611        /*
20612         Check if modal height is greater then window height.
20613         If so set modal postion to scrollPosition and not top of page.
20614         */
20615        if (this.modalHeight > this.windowHeight) {
20616            this.modalAnimateToPosition = (this.scrollPosition + this.modalTopOffset);
20617        } else {
20618            this.modalAnimateToPosition = this.modalTopOffset;
20619        }
20620    },
20621    positionModalOffPage: function () {
20622        var modalOffPagePosition = (this.windowHeight + this.scrollPosition);
20623        this.getModalDimensions();
20624        /*
20625         Alright lets do this.
20626         CSS changes on required elements.
20627         */
20628        this.htmlTag.addClass('fixed');
20629        this.overlay.css({display: 'block'});
20630        this.spinner.show();
20631        //that.main.css({top: '-' + that.scrollPosition + 'px'}).attr('data-top', that.scrollPosition);
20632        this.contentContainer.css({top: '-' + this.scrollPosition + 'px'});
20633        this.modalContainer.css({top: modalOffPagePosition + "px", visibility: 'visible'});
20634        this.animateModalOpen();
20635        $('#main').addClass('no-print');
20636    },
20637    positionModalOnResize: function () {
20638        /*
20639         Lets see what things look like now
20640         */
20641        this.getWindowProperties();
20642        this.getModalDimensions();
20643        /*
20644         On vertical resize check to see if modal is now smaller then window.
20645         Animate modal position to correct position if it is.
20646         Otherwise change modalAnimateToPosition position and scrollPositon
20647         for scrollListener prevent scroll from proper spot.
20648         */
20649        if (this.modalHeight < this.windowHeight) {
20650            //this.animateModalOpen();
20651            this.modalCloseBtn.removeClass('fixed');
20652        } else if ($(window).scrollTop() > this.modalContainer.offset().top) {
20653            this.modalAnimateToPosition = this.modalContainer.offset().top;
20654            this.scrollPosition = this.modalAnimateToPosition - this.modalTopOffset;
20655        }
20656    },
20657    //limits focusable items to presentation mode (can't select main page with keys)
20658    restrictMainPageAccess: function () {
20659        jQuery('#main').attr('aria-hidden', 'true');
20660        this.modalContainer.attr('aria-hidden', 'false');
20661    },
20662    //reinstates main page items as the focusable group
20663    grantMainPageAccess: function () {
20664        jQuery('#main').attr('aria-hidden', 'false');
20665        this.modalContainer.attr('aria-hidden', 'true');
20666    },
20667    //used for AA compliance for people with disabilities
20668    //sets focus to the first focusable element in presentation mode
20669    setFocus: function () {
20670        this.restrictMainPageAccess();
20671        var objectList = this.modalContainer.find('*');
20672        objectList.filter(this.focusableElementsString).filter(':visible').first().focus();
20673        loadYoutube();
20674    },
20675    /*
20676     Giddy up. Time to get animated.
20677     */
20678    animateModalOpen: function () {
20679        var that = this;
20680        this.activeNavActive = $('#in-page-nav').find('.active');
20681        this.activeNavActive.find(".nav-button").css({color: '#8c1515'});
20682        if (this.searchInPageNav.hasClass('affix')) {
20683            this.searchInPageNav.css({position: 'fixed'});
20684        } else {
20685            this.searchInPageNav.css({position: 'relative'});
20686        }
20687        if (this.mainPageFocus == null) {
20688            this.mainPageFocus = $(document.activeElement);
20689        }
20690        this.spinner.hide();
20691        this.modalContainer.transition(
20692            {
20693                top: this.modalTopOffset,
20694                opacity: 1,
20695                complete: function () {
20696                    that.setEventListeners();
20697                    that.restrictMainPageAccess();
20698                    that.setFocus();
20699                }
20700            }, 300, 'snap'
20701        );
20702    },
20703    setEventListeners: function () {
20704        var that = this;
20705        this.scrollListener();
20706        this.modalResizeListener();
20707        this.closeListener();
20708        this.modalCloseBtn.on("keyup", function (e) {
20709            if (e.keyCode === 13) {
20710                that.closer(e);
20711            }
20712        });
20713    },
20714    scroller: function () {
20715        var scrollTop = $(window).scrollTop();
20716        if (scrollTop <= 0) {
20717            scrollTop = 0;
20718        }
20719        /*
20720         Woah, where you going there. Prevent scrolling up past top of modal window.
20721         */
20722        if (scrollTop < (this.modalAnimateToPosition - this.modalTopOffset)) {
20723            //window.scrollTo(0, this.scrollPosition);
20724        }
20725        /*
20726         Fix modal close button position once you scroll past top of fixed modal window.
20727         */
20728        if (scrollTop > (this.modalContainer.offset().top)) {
20729            this.modalCloseBtn.addClass('fixed');
20730        } else {
20731            this.modalCloseBtn.removeClass('fixed');
20732        }
20733    },
20734    resizeEventListener: function () {
20735        this.positionModalOnResize();
20736        if (this.imageModal) {
20737            this.sizeModalImage();
20738        }
20739    },
20740    keyUpListener: function () {
20741        if (event.keyCode === 27) {
20742            $('.close-modal').click();
20743        }
20744    },
20745    /*
20746     Add listener on scroll event.
20747     */
20748    scrollListener: function () {
20749        var that = this;
20750        that.scrollify = function (evt) {
20751            that.scroller(evt);
20752        };
20753        $(window).on("scroll", this.scrollify);
20754    },
20755    modalResizeListener: function () {
20756        var that = this;
20757        this.resizeEndCatcher = function (evt) {
20758            that.resizeEventListener(evt);
20759        };
20760        $(window).on('resizeEnd', this.resizeEndCatcher);
20761    },
20762    modalLinkClickListener: function () {
20763        var that = this;
20764        $('#modal-content a.open-modal').on("click", function (e) {
20765            e.preventDefault();
20766            that.clearData($(this));
20767        });
20768    },
20769    clearData: function (modalLink) {
20770        this.modalContent.empty().attr('style', '');
20771        this.repopulateModal(modalLink);
20772    },
20773    repopulateModal: function (modalLink) {
20774        // get url for page to load content from.
20775        var modalLinkURL = modalLink.attr('href'),
20776            modalLinkAltText = modalLink.attr('alt'),
20777            targetContainer = '',
20778            contentType = '',
20779            caption = '';
20780
20781        if (modalLink.data('modalcontainer')) {
20782            targetContainer = modalLink.data('modalcontainer');
20783        }
20784        if (modalLink.data('modalcontenttype')) {
20785            contentType = ' ' + modalLink.data('modalcontenttype');
20786        }
20787        if ((!modalLink.data('modalpadding')) &&
20788            (typeof(modalLink.data('modalpadding')) !== 'undefined')) {
20789            this.modalPadding = false;
20790        } else {
20791            this.modalPadding = true;
20792        }
20793        if (modalLink.data('caption')) {
20794            this.modalCaption = true;
20795            caption = modalLink.data('caption');
20796            // create caption contianer
20797            $('<div />').attr({'class': 'caption'}).appendTo(this.modalContainer);
20798        }
20799        this.getModalData(modalLinkURL, targetContainer, contentType, caption, modalLinkAltText);
20800    },
20801    closeListener: function () {
20802        var that = this;
20803        // listen for escape key press to close modal.
20804        $(document).on('keyup', that.keyUpListener);
20805
20806        // listen for click on close modal button.
20807        this.closer = function (event) {
20808
20809            //show content outside of modal
20810            $('body').children('div:not(#modal),a').each(function(){
20811                $(this).removeAttr('inert');
20812            });
20813            event.preventDefault();
20814            //Used to reset the Quiz, need to move it to
20815            //TODO extend version of modal.js to include this logic
20816            if (that.modalContainer.find('#quizcontainer').length) {
20817                var quiz = new SHC.ui.Quiz.restore();
20818            }
20819            // position window where we left off.
20820            window.scrollTo(0, $('#main').attr('data-top'));
20821            if (that.imageModal) {
20822                that.modal.removeClass('lightbox');
20823                if (that.modalCaption) {
20824                    that.modalContainer.find('.caption').remove();
20825                }
20826            }
20827            that.inPageNav.find(".active").removeClass('active');
20828            if (that.activeNavActive !== null) {
20829                that.activeNavActive.addClass('active');
20830                that.activeNavActive.find(".nav-button").attr("style", "");
20831                var width = that.activeNavActive.find('a').outerWidth(),
20832                    position;
20833                if (that.activeNavActive.position()) {
20834                    position = that.activeNavActive.position().left;
20835                }
20836                that.underline.css({
20837                    width: width + 'px',
20838                    left: position + 'px'
20839                });
20840            }
20841            that.preventClickiness = false;
20842            that.clearModalContent();
20843            that.grantMainPageAccess();
20844            if (that.mainPageFocus !== null) {
20845                that.mainPageFocus.focus();
20846            }
20847            that.removeListeners();
20848            that.inPageNavAnchors.removeAttr('style');
20849            that.searchInPageNav.removeAttr('style');
20850            that.underline.removeClass('hidden');
20851            that.backToTop.removeClass('hidden');
20852            that.shadow.removeClass('hidden');
20853            $('#main').removeClass('no-print');
20854            jQuery('#modal-content').attr('data-show-links', 'false');
20855        };
20856        $('.close-modal').on('click', this.closer);
20857    },
20858    removeListeners: function () {
20859        //scrollListener
20860        $(window).off("scroll", this.scrollify);
20861        //modalResizeListener
20862        $(window).off('resizeEnd', this.resizeEndCatcher);
20863        //escape key listener
20864        $(document).unbind('keyup', this.keyUpListener);
20865        $('.close-modal').off('click', this.closer);
20866
20867    },
20868    renderMakeAppointment: function (data, npi) {
20869        var isIE = SHC.util.msieVersion();
20870        var $data = $(data);
20871        var l3DocProfile = $('.l3-doctor-profile');
20872        var apptAnchor = $('.make-an-appt-overview .make-an-appt-link');
20873        var aptLinks = $('.make-an-appt-online .make-an-appt-link, .make-an-appt-online input[type="submit"]');
20874        if (isIE === 8 || isIE === 9) {
20875            SHC.util.addPlaceholder('username', 'Username');
20876            SHC.util.addPlaceholder('password', 'Password');
20877        }
20878        if (isIE) {
20879            if ($data.find('.make-an-appt-online').length > 0) {
20880                $('.make-an-appt-online').addClass("ie" + isIE);
20881            }
20882        }
20883        if (!$data.find('.make-an-appt-content').length && !$data.find('#make-an-appt-login').length) {
20884            $('.make-an-appt-info').css({'border': "none", 'padding-left': '0px'});
20885        }
20886        if (npi.length > 0 && l3DocProfile.length > 0 && apptAnchor.length > 0 ) {
20887            for (var i = 0; i < apptAnchor.length; i++) {
20888                var anchor = $(apptAnchor[i]),
20889                    href = anchor.attr('href'),
20890                    hrefSplit = href.split("?"),
20891                    npiParam = hrefSplit[hrefSplit.length - 1];
20892                if (npiParam.trim() === "npi=") {
20893                    anchor.attr('href', href + npi);
20894                }
20895            }
20896        }
20897        if (aptLinks.length) {
20898            $(aptLinks).each((i,link) => {
20899                const btnText = link.innerText || link.value;
20900                link.addEventListener("click", function () {
20901                        stanford.analytics.send(stanford.analytics.createComponentClickButton(btnText, "button", 'Make An Appointment'));
20902                    });
20903                }
20904            );
20905        }
20906    },
20907    renderTakeQuiz: function () {
20908        var quiz = new SHC.ui.Quiz('#quizcontainer');
20909    }
20910});
20911
20912SHC.Namespace(SHC, "SHC.ui.ReviewCarousel");
20913SHC.ui.ReviewCarousel = new SHC.Class();
20914
20915SHC.ui.ReviewCarousel.include({
20916    /**
20917     * constructor
20918     * @param id
20919     */
20920    init: function (ref) {
20921        var self = this;
20922        self.$carousel = $(ref);
20923        // Containers and elements
20924        self.$container = self.$carousel.find('.container-inf');
20925        self.$paddlesContainer = self.$carousel.find('.rc_paddles');
20926        self.$textPrevious = self.$paddlesContainer.find('.textprev'); //element previous button
20927        self.$textNext = self.$paddlesContainer.find('.textnext'); //element next button
20928        self.$paddles = self.$paddlesContainer.find('a');
20929        self.$textContainerParent = self.$carousel.find('.rc_slides');
20930        self.$textContainer = self.$textContainerParent.find('ul');
20931        self.$textSlides = self.$textContainerParent.find('li.rc_slide');
20932        self.$first = self.$textContainer.find('li:first-child');
20933        self.$background = self.$textContainerParent.find('.rc-bg');
20934        self.item_width = self.$textContainer.width();
20935        self.isMobile = SHC.ui.screenMode === 'small';
20936        self.setupCarousel();
20937        self.setupClickHandlers();
20938    },
20939
20940    setupCarousel: function () {
20941        var that = this;
20942        if (that.$textSlides.length < 2) {
20943            that.$paddlesContainer.addClass('hide-item');
20944            that.$textContainerParent.addClass('single-slide-div');
20945        }
20946        if (that.isMobile) {
20947            var bg = that.$background.detach();
20948            bg.addClass('row');
20949            bg.insertBefore(that.$textContainerParent);
20950            that.$paddles.css('margin', '81px 0 0 0');
20951        }
20952        that.$first.removeClass('hide-item');
20953        that.centerPaddles();
20954    },
20955
20956    setupClickHandlers: function () {
20957        var that = this;
20958        that.$textNext.click(function (e) {
20959            e.preventDefault();
20960            that.carouselNext();
20961        });
20962
20963        that.$textPrevious.click(function (e) {
20964            e.preventDefault();
20965            that.carouselPrev();
20966        });
20967    },
20968
20969    carouselNext: function () {
20970        var that = this;
20971        that.$textContainer.filter(':not(:animated)').animate({
20972            right: '+=' + (that.item_width + 80)
20973        }, 500, function () {
20974            $(that.$textSlides[0]).addClass('hide-item');
20975            that.$textSlides = SHC.util.rotate(that.$textSlides, 1);
20976            $(that.$textSlides[0]).removeClass('hide-item');
20977            that.$textContainer.empty();
20978            for (var i = 0; i < that.$textSlides.length; i++) {
20979                that.$textContainer.append(that.$textSlides[i]);
20980            }
20981            $(this).css({
20982                right: '-=' + (that.item_width + 80)
20983            });
20984            that.centerPaddles();
20985        });
20986    },
20987
20988    carouselPrev: function () {
20989        var that = this;
20990        that.$textContainer.filter(':not(:animated)').animate({
20991            right: '-=' + (that.item_width + 80)
20992        }, 500, function () {
20993            $(that.$textSlides[0]).addClass('hide-item');
20994            that.$textSlides = SHC.util.rotate(that.$textSlides, -1);
20995            $(that.$textSlides[0]).removeClass('hide-item');
20996            that.$textContainer.empty();
20997            for (var i = 0; i < that.$textSlides.length; i++) {
20998                that.$textContainer.append(that.$textSlides[i]);
20999            }
21000            $(this).css({
21001                right: '+=' + (that.item_width + 80)
21002            });
21003            that.centerPaddles();
21004        });
21005    },
21006
21007    centerPaddles: function () {
21008        var that = this;
21009        if (!that.isMobile) {
21010            var containerHeight = that.$textContainerParent.height();
21011            var marginTop = (containerHeight / 2) - 19 + 'px';
21012            that.$paddles.css('margin-top', marginTop);
21013        }
21014    }
21015});
21016
21017SHC.Namespace(SHC, "SHC.ui.Share");
21018SHC.ui.Share = new SHC.Class();
21019
21020SHC.ui.Share.include({
21021
21022    init: function(parent){
21023        //declare variables
21024        this.parent = $(parent);
21025        this.$icon_open = this.parent.find('#icon_open');
21026        this.$icon_close = this.parent.find('#icon_close');
21027        this.$social_icons = this.parent.find('#social_icons');
21028        this.$icon = this.$social_icons.find('.icon');
21029        this.$icon_open.off('click.share');
21030        this.$icon_close.off('click.share');
21031        this.$icon.off('click.share');
21032
21033        this.cachedFBHref = "";
21034        this.cachedTWHref = "";
21035        this.cachedEmailHref = "";
21036        //do stuff
21037        this.activate();
21038    },
21039
21040    activate: function() {
21041        var that = this;
21042        // share button to open behavior on a large screen
21043        var openShareComponentLarge = function(e) {
21044            if (e) {
21045                e.preventDefault();
21046            }
21047            that.$social_icons.slideDown('fast', function(){
21048                 $(this).css("overflow", "visible");
21049            });
21050            that.$icon_open.slideUp('fast');
21051        };
21052
21053        // share button close behavior on a large screen
21054        var closeShareComponentLarge = function(e){
21055            if (e) {
21056                e.preventDefault();
21057            }
21058            that.$social_icons.slideUp('fast');
21059            that.$icon_open.removeClass('hidden');
21060            that.$icon_open.slideDown('fast');
21061        };
21062
21063        // share button to open behavior on a medium and small screen
21064        var openShareComponentMobile = function(e) {
21065            if (e) {
21066                e.preventDefault();
21067            }
21068            that.$social_icons.slideUp('fast', function(){
21069                 $(this).css("overflow", "visible");
21070            });
21071            that.$icon_open.animate({"top": "0px"}, 'fast');
21072            that.$icon_close.animate({"top": "0px"}, 'fast');
21073        };
21074
21075        // prevent default action and wire up socialPopup
21076        var preventPopUp = function(e){
21077            e.preventDefault();
21078            var iconID = $(this).attr('id');
21079            var iconHref = $(this).find('a').attr('href');
21080            that.socialPopup(iconID, iconHref);
21081        };
21082
21083        if (jQuery(".share-component").length > 0) {
21084            // share button bindings
21085            that.$icon_open.on('click.share', openShareComponentLarge);
21086            that.$icon_close.on('click.share', closeShareComponentLarge);
21087            that.$icon.on('click.share', preventPopUp);
21088            if (SHC.ui.screenMode === "small") {
21089                closeShareComponentLarge();
21090            } else {
21091                openShareComponentLarge();
21092            }
21093            // set up share links for bitly urls
21094            that.setUpBitly();
21095        }
21096    },
21097    // Bitly Magic
21098    // TODO: I think the current url needs to be url encoded per bitly requirements doc
21099    setUpBitly: function(){
21100        /*
21101        this.setUpBitlyFB();
21102        this.setUpBitlyTW();
21103        this.setUpBitlyEmail();
21104        this.setUpBitlyGPlus();
21105        */
21106    },
21107    getBitlyFB: function(){
21108        var locationHref = window.location.href;
21109        // for local testing
21110        if (locationHref.indexOf("localhost") > -1) {
21111            locationHref = locationHref.replaceAll("http://localhost:4502/","https://stanfordhealthcare.org/");
21112        }
21113        locationHref = this.appendDecodedSocialID(locationHref, "ecid=soc-fb");
21114        var getter = "https://www.facebook.com/sharer/sharer.php?u=" + locationHref;
21115        return getter;
21116    },
21117    getBitlyTW: function(){
21118        var locationHref = window.location.href;
21119        // for local testing
21120        if (locationHref.indexOf("localhost") > -1) {
21121            locationHref = locationHref.replaceAll("http://localhost:4502/","https://stanfordhealthcare.org/");
21122        }
21123        locationHref = this.appendDecodedSocialID(locationHref, "ecid=soc-tw");
21124        var shareTitle = jQuery('meta[name="mail_title"]').attr('content');
21125        if(jQuery('.share-data').length > 0){
21126            shareTitle = jQuery("meta[name='twitter:title']").attr('content');
21127        }
21128        getter = "https://twitter.com/share?text=" + encodeURIComponent(shareTitle) + "&url=" + locationHref + "&via=StanfordHealth";
21129        return getter;
21130    },
21131    // Bitly Magic - Email
21132    // TODO: I think the current url needs to be url encoded per bitly requirements doc
21133    getBitlyEmail: function(){
21134        var locationHref = window.location.href;
21135        // for local testing
21136        if (locationHref.indexOf("localhost") > -1) {
21137            locationHref = locationHref.replaceAll("http://localhost:4502/","https://stanfordhealthcare.org/");
21138        }
21139        locationHref = this.appendDecodedSocialID(locationHref, "ecid=soc-em");
21140        var getter = "mailto:?subject=Stanford Health Care&body=Stanford Health Care " + locationHref;
21141        if(jQuery('.share-data').length > 0){
21142            shareTitle = jQuery(".share-data meta[name='twitter:title']").attr('content');
21143            shareDescription = jQuery('.share-data meta[name="twitter:description"]').attr('content');
21144            getter = "mailto:?subject=" + shareTitle + "&body=" + shareDescription;
21145        }
21146        return getter;
21147    },
21148
21149    appendSocialID: function(currentURL, socID) {
21150        if (currentURL.indexOf("/presentation-mode") > -1) {
21151            currentURL = this.removeExistingKwcid(currentURL);
21152            var pmodeIdx = currentURL.indexOf("/presentation-mode");
21153            var baseURL = currentURL.substr(0,pmodeIdx);
21154            var pmodeURL = currentURL.substr(pmodeIdx);
21155            if (baseURL.indexOf("?") > -1) {
21156                if (baseURL.indexOf("ecid") > -1) {
21157                    baseURL = this.removeExistingEcid(baseURL);
21158                }
21159                if (baseURL.indexOf("?") === (baseURL.length - 1)) {
21160                    return encodeURIComponent(baseURL + socID + pmodeURL);
21161                } else {
21162                    return encodeURIComponent(baseURL + "&" + socID + pmodeURL);
21163                }
21164            } else {
21165                return encodeURIComponent(baseURL + "?" + socID + pmodeURL);
21166            }
21167        } else {
21168            if (currentURL.indexOf("?") > -1) {
21169                if (currentURL.indexOf("ecid") > -1) {
21170                    currentURL = this.removeExistingEcid(currentURL);
21171                }
21172                currentURL = this.removeExistingKwcid(currentURL);
21173                if (currentURL.indexOf("?") === (currentURL.length - 1)) {
21174                    return encodeURIComponent(currentURL + socID);
21175                } else {
21176                    return encodeURIComponent(currentURL + "&" + socID);
21177                }
21178            } else {
21179                return encodeURIComponent(currentURL + "?" + socID);
21180            }
21181        }
21182    },
21183
21184    appendDecodedSocialID: function(currentURL, socID) {
21185        if (currentURL.indexOf("/presentation-mode") > -1) {
21186            currentURL = this.removeExistingKwcid(currentURL);
21187            var pmodeIdx = currentURL.indexOf("/presentation-mode");
21188            var baseURL = currentURL.substr(0,pmodeIdx);
21189            var pmodeURL = currentURL.substr(pmodeIdx);
21190            if (baseURL.indexOf("?") > -1) {
21191                if (baseURL.indexOf("ecid") > -1) {
21192                    baseURL = this.removeExistingEcid(baseURL);
21193                }
21194                if (baseURL.indexOf("?") === (baseURL.length - 1)) {
21195                    return baseURL + socID + pmodeURL;
21196                } else {
21197                    return baseURL + "&" + socID + pmodeURL;
21198                }
21199            } else {
21200                return baseURL + "?" + socID + pmodeURL;
21201            }
21202        } else {
21203            if (currentURL.indexOf("?") > -1) {
21204                if (currentURL.indexOf("ecid") > -1) {
21205                    currentURL = this.removeExistingEcid(currentURL);
21206                }
21207                currentURL = this.removeExistingKwcid(currentURL);
21208                if (currentURL.indexOf("?") === (currentURL.length - 1)) {
21209                    currentURL + socID;
21210                } else {
21211                    return currentURL + "&" + socID;
21212                }
21213            } else {
21214                return currentURL + "?" + socID;
21215            }
21216        }
21217    },
21218
21219    /**
21220    * Strips out all instances of ecid=soc- if it exists. Based off the current ecid=soc-tw with 11 characers
21221    * @param url
21222    * @returns {*}
21223    */
21224    removeExistingEcid: function(url) {
21225        var ecidIndex = url.indexOf('ecid=soc-'),
21226            beforeEcid,
21227            afterEcid;
21228        while (ecidIndex !== -1) {
21229            // cut it out
21230            if (url.charAt(ecidIndex - 1) === "&") {
21231                beforeEcid = url.substr(0, ecidIndex - 1);
21232                afterEcid = url.substr(ecidIndex + 11);
21233            } else {
21234                beforeEcid = url.substr(0, ecidIndex);
21235                afterEcid = url.substr(ecidIndex + 12);
21236            }
21237            url = beforeEcid + afterEcid;
21238            ecidIndex = url.indexOf('ecid=soc-');
21239        }
21240        return url;
21241    },
21242
21243    /**
21244    * Strips out all instances of kwcid parameter if it exists.
21245    * @param url
21246    * @returns {*}
21247    */
21248    removeExistingKwcid: function(url) {
21249        var kwcidIndex = url.indexOf('kwcid=');
21250        var presmode = false;
21251        if (url.indexOf(HOME_PAGE_PATH + ".html/presentation-mode") > -1) {
21252            presmode = true;
21253        }
21254        while (kwcidIndex !== -1) {
21255            // cut it out
21256            var endofparamIndex = url.length;
21257            var i = kwcidIndex;
21258            // can't rely on an exact character count, so we need to detect the end of the parameter
21259            while (i < endofparamIndex) {
21260                if (url.charAt(i) === "&") {
21261                    if (i < endofparamIndex) {
21262                        endofparamIndex = i + 1;
21263                    } else {
21264                        endofparamIndex = i;
21265                    }
21266                    break;
21267                }
21268                //need to account for presentation mode special case on home page
21269                if (presmode) {
21270                    if (url.substr(i, 37) === HOME_PAGE_PATH + ".html/presentation-mode") {
21271                        endofparamIndex = i;
21272                        if (url.charAt(kwcidIndex - 1) === "?") {
21273                            kwcidIndex = kwcidIndex - 1;
21274                        }
21275                        break;
21276                    }
21277                }
21278                i++;
21279                if (i === endofparamIndex) {
21280                    if (url.charAt(kwcidIndex - 1) === "&") {
21281                        kwcidIndex = kwcidIndex - 1;
21282                    }
21283                    endofparamIndex = i;
21284                }
21285            }
21286            var beforeEcid = url.substr(0, kwcidIndex);
21287            var afterEcid = url.substr(endofparamIndex);
21288            url = beforeEcid + afterEcid;
21289            kwcidIndex = url.indexOf('kwcid=');  // detect multiple instances of the parameter
21290        }
21291        return url;
21292    },
21293
21294    socialPopup: function(elementID, url) {
21295           // detect which network we're on
21296           // get bit.ly link
21297           // then open window
21298        var bitLink;
21299           switch (elementID) {
21300                case "icon_facebook":
21301                    bitLink = this.getBitlyFB();
21302                    window.open(bitLink, 'shcsocial', 'width=400,height=500');
21303                    break;
21304                case "icon_twitter":
21305                    bitLink = this.getBitlyTW();
21306                    window.open(bitLink, 'shcsocial', 'width=400,height=500');
21307                    break;
21308                case "icon_email":
21309                    bitLink = this.getBitlyEmail();
21310                    //window.open(bitLink, 'shcsocial', 'width=400,height=500');
21311                    window.location = bitLink;
21312                    break;
21313                default:
21314                    document.location.href = url;
21315           }
21316       },
21317
21318    getSelectedText: function() {
21319        var selectedText = jQuery("h1").text();
21320        if(window.getSelection){
21321            selectedText = window.getSelection();
21322        } else if(document.getSelection){
21323            selectedText = document.getSelection();
21324        } else if(document.selection){
21325            selectedText = document.selection.createRange();
21326        }
21327        return selectedText;
21328    },
21329
21330    updateShareHrefs: function(params) {
21331        //update share components - when entering or exiting presentation mode, we need to adjust the href values of the anchor tags for each of the share icons
21332        var enterPresentation = params.enterPresentation || false,
21333            fb = $("#icon_facebook").find("a"),
21334            tw = $("icon_twitter").find("a"),
21335            email = $("#icon_email").find("a");
21336        if (enterPresentation) {
21337            var currentPageTitle = document.title,
21338                titleNoSpaces = currentPageTitle.replace(" ", "%20"),
21339                pageDescription = $('meta[property="description"]').attr("content");
21340
21341            // cache out the old hrefs
21342            this.cachedFBHref = fb.attr("href");
21343            this.cachedTWHref = tw.attr("href");
21344            this.cachedEmailHref = email.attr("href");
21345
21346            // set new hrefs
21347            fb.attr("href", "https://www.facebook.com/sharer/sharer.php?u=" + window.location.href);
21348            tw.attr("href", "https://twitter.com/share?text=" + titleNoSpaces + "%20" + window.location.href + "via=StanfordHealth");
21349            email.attr("href", "mailto:?subject=" + currentPageTitle + "&body=" + currentPageTitle + "%0D" + pageDescription + " - " + window.location.href);
21350        } else {
21351            // reset hrefs
21352            fb.attr("href", this.cachedFBHref);
21353            tw.attr("href", this.cachedTWHref);
21354            email.attr("href", this.cachedEmailHref);
21355
21356            // dump cache
21357            this.cachedFBHref = "";
21358            this.cachedTWHref = "";
21359            this.cachedEmailHref = "";
21360        }
21361    }
21362});
21363
21364SHC.Namespace(SHC, "SHC.ui.GenericTabNavTabNav");
21365SHC.ui.GenericTabNavTabNav = new SHC.Class();
21366
21367SHC.ui.GenericTabNavTabNav.include({
21368    //constructor
21369    init: function(parent) {
21370        this.self = $(parent);
21371        this.parent = parent;
21372        this.spinner = this.self.find('.spinner-container');
21373        this.docWindow = $(window);
21374        this.mobileScreen = this.docWindow.width() < 768;
21375        this.spinnerContainer = this.spinner.parent();
21376        this.tabbedNav = this.self.find('#tabbed-nav');
21377        this.sideNav = jQuery('.side-nav');
21378        this.sideNavParent = jQuery('.side-nav-parent');
21379        this.fadeSpeed = 50;
21380        this.navAnimateSpeed = 400;
21381        this.isAuthorMode = SHC.util.WCM.isAuthorMode();
21382        if (this.mobileScreen) {
21383            this.initMobileTabNav();
21384        }
21385        else {
21386            this.initTabNav();
21387            this.setup(this);
21388        }
21389        this.hideUnneededFeatures();
21390        this.computeAndSetOffsetsForTabnav();
21391        this.adjustTabnavHeights();
21392    },
21393    setup: function(ref) {
21394        var that = this;
21395
21396        // tab nav item click
21397        var navItemClickHandler = function(e) {
21398            if (window.history.pushState) {
21399                e.preventDefault();
21400                var item = $(this);
21401                var $url = item.attr('href');
21402                if (that.mobileScreen) {
21403                    //find heading with active class
21404                    var headingDivActive = item.closest('.mobile-tab-heading.active');
21405                    //if heading has active class, then close the tab
21406                    if (headingDivActive.length > 0 && !item.hasClass('parent-heading-anchor')) {
21407                        collapseMobile();
21408                    }
21409                    else {
21410                        //if heading is the anchor with back arrow, set anchor to parent heading anchor
21411                        if (item.hasClass('parent-heading-anchor')) {
21412                            item = item.closest('.panel.menu-expanded').find('.mobile-tab-heading-link');
21413                        }
21414                        setActivePanel(item);
21415                        if(SHC.ui.screenMode === 'small'){
21416                            SHC.mobileClickItem = item;
21417                        }
21418                        loadContent(item);
21419                        if(SHC.ui.screenMode !== 'small'){
21420                            $('html, body').animate({
21421                                scrollTop: item.closest("#mobile-tabs").offset().top
21422                            }, 500);
21423                        }
21424                    }
21425                }
21426                else {
21427                    setActivePanel(item);
21428                    loadContentFromUrl($url);
21429                }
21430                pushUrl($url, item.text());
21431            }
21432        };
21433
21434        //intercepts the browswer back/forward button clicks
21435        var browserBackAndForwardButtonIntercepts = function(e) {
21436            var landingUrl = $('div#original-landing-url-tab-nav').text();
21437            try {
21438                if (e.state) {
21439                    landingUrl = e.state.path;
21440                }
21441
21442                //if mobile
21443                if (that.mobileScreen) {
21444                    that.initMobileTabNav();
21445                }
21446                else {
21447                    loadContentFromUrl(landingUrl);
21448
21449                    // Desktop - the content is already loaded just update tabs
21450                    that.self.find("#tab-nav a.active").removeClass("active");
21451                    that.self.find("#tab-nav a").each(function() {
21452                        if (landingUrl.indexOf($(this).attr("href")) !== -1) {
21453                            $(this).addClass('active');
21454                            if (!($(this).hasClass('tab-heading-link'))) {
21455                                var parentPanel = $(this).closest('.panel-collapse');
21456                                parentPanel.removeClass('collapse').addClass('in').css("height", "auto");
21457                                $(this).closest('.panel').find('.tab-heading-link').addClass('active');
21458                            }
21459                        }
21460                    });
21461                }
21462            } catch (excpt) {
21463                //console.log(excpt);
21464            }
21465        };
21466
21467        // mobile tab-nav-toggle click
21468        var toggleMobileTabNav = function(e) {
21469            e.preventDefault();
21470            var $navToggle = that.self.find('#tab-nav-toggle');
21471            //toggle expanded state
21472            if ($navToggle.hasClass('open')) {
21473                that.collapseMobileTabNav();
21474            } else {
21475                that.expandMobileTabNav();
21476            }
21477        };
21478
21479        /*
21480         * Pushes the url to the history object and ajax loads the target page
21481         * Or goes directly to the page when authoring
21482         * @param url the target page
21483         * @param anchorText the title for the history object
21484         */
21485        function pushUrl($url, $anchorText) {
21486            // edit history if not authoring and ajax load content
21487            if (!that.isAuthorMode && window.history.pushState) {
21488                var savedHash = "";
21489                var newUrl = "";
21490                if (window.location.hash) {
21491                    savedHash = window.location.hash;
21492                    newUrl = $url + savedHash;
21493                } else {
21494                    newUrl = $url;
21495                }
21496                window.history.pushState({
21497                    "path": newUrl
21498                }, $anchorText, newUrl);
21499                if (!that.mobileScreen) {
21500                    $(document.body).scrollspycustom('refresh');
21501                }
21502            }
21503            // go to page when authoring
21504            else {
21505                window.location = $url;
21506            }
21507        }
21508
21509        /*
21510         * Loads the tabbed nav div from the dom element
21511         * Binds any child lists after ajax load
21512         * @param {type} dom element - the target dom element
21513         * @returns {undefined}
21514         */
21515        function loadContent(item) {
21516            that.spinnerContainer.height(that.sideNavParent.height());
21517            var $url = item.attr('href');
21518            var $anchor = $('#mobile-tabs a[href^="' + $url + '"]');
21519            that.scrollToTopOfNav();
21520
21521            //if mobile
21522            if (that.mobileScreen) {
21523                //determine if the anchor is part of panel
21524                if ($anchor.closest(".panel-collapse").length > 0) {
21525                    //heading with active class
21526                    var $activeParentHeading = that.tabbedNav.closest('.mobile-tab-heading.active');
21527                    if ($activeParentHeading.length === 0) {
21528                        $activeParentHeading = that.tabbedNav.closest('.panel.menu-expanded').find('.mobile-tab-heading.active');
21529                    }
21530                    var parentAnchor = $activeParentHeading.find('a.mobile-tab-heading-link');
21531                    //store h2 text for back arrow heading
21532                    var linkText = that.tabbedNav.find('h2').text().toUpperCase();
21533                    //insert back arrow div after active heading
21534                    $('<div class="parent-list-heading"><a class="parent-heading-anchor"></a></div>').insertAfter($($activeParentHeading));
21535                    var $backArrowHeadingAnchor = $('.parent-list-heading a.parent-heading-anchor');
21536                    //set href attribute for the back arrow heading anchor
21537                    $backArrowHeadingAnchor.attr('href', parentAnchor[0].pathname);
21538                    //append arrow image span and arrow text span to the anchor
21539                    $backArrowHeadingAnchor.append($('<span class="back-arrow-heading"></span><span class="back-arrow-text"></span>'));
21540                    //set the back arrow span text
21541                    $backArrowHeadingAnchor.find('span.back-arrow-text').text(linkText);
21542                    //reattach click handlers since new anchor is added
21543                    attachClickHandlers();
21544                }
21545                that.scrollToTopOfNav();
21546                that.tabbedNav.load($url + " .tab-nav-parsys, .healthwise-parsys", function() {
21547                    that.tabbedNav.show();
21548                    appendContent(item);
21549                    adjustMobileViewPanels(item);
21550                    if ($anchor.hasClass('mobile-tab-heading-link')) {
21551                        $('#mobile-tabs').find('.parent-list-heading').hide();
21552                        var mobileCollapsiblePanels = $anchor.closest('.panel.menu-expanded').find('.panel-collapse');
21553                        var listsToCollapse = mobileCollapsiblePanels.find('li');
21554                        var listAnchors = mobileCollapsiblePanels.find('li a');
21555                        listsToCollapse.show();
21556                        listAnchors.show();
21557                    }
21558                    that.secondContentLoad();
21559                    window.dispatchEvent(new Event('mobileGenericTabNavLoaded'));
21560                });
21561            }
21562            else {
21563                that.tabbedNav.fadeOut(that.fadeSpeed, function() {
21564                    that.spinner.show();
21565                    that.scrollToTopOfNav();
21566                    that.tabbedNav.load($url + " .tab-nav-parsys, .healthwise-parsys", function() {
21567                        that.spinner.hide();
21568                        var autoHeight = that.sideNavParent.css('height', 'auto').outerHeight();
21569                        that.spinnerContainer.animate({
21570                            height: autoHeight
21571                        }, that.navAnimateSpeed, function() {
21572                            that.tabbedNav.fadeIn(that.fadeSpeed, function() {
21573                                that.spinnerContainer.height('auto');
21574                                that.tabbedNav.height('auto');
21575                                that.reinitJS();
21576                                $(document).trigger('debouncedresize');
21577                                $(document.body).scrollspycustom('refresh');
21578                                jQuery('.tab_nav').css('overflow', 'visible');
21579                            });
21580                            // we call this twice (here and in reinit) as a fallback in case
21581                            // infoblocks doesn't have a height yet, which is needed for equal heights
21582                            var infoblocksContainer = new SHC.ui.InfoblocksContainer("#tabbed-nav-content-wrapper .info-blocks-container");
21583                        });
21584                    });
21585                });
21586            }
21587            $(document.body).scrollspycustom('refresh');
21588        }
21589
21590        /*
21591         * Loads the tabbed nav div from the target url
21592         * Binds any child lists after ajax load
21593         * @param {type} url - the target url
21594         * @returns {undefined}
21595         */
21596        function loadContentFromUrl($url) {
21597            that.spinnerContainer.height(that.sideNavParent.height());
21598            that.tabbedNav.fadeOut(that.fadeSpeed, function() {
21599                if (!this.mobileScreen) {
21600                    that.spinner.show();
21601                }
21602                that.scrollToTopOfNav();
21603                that.tabbedNav.load($url + " .tab-nav-parsys, .healthwise-parsys", function() {
21604                    if (!this.mobileScreen) {
21605                        that.spinner.hide();
21606                    }
21607                    var autoHeight = that.sideNavParent.css('height', 'auto').outerHeight();
21608                    that.spinnerContainer.animate({
21609                        height: autoHeight
21610                    }, that.navAnimateSpeed, function() {
21611                        that.tabbedNav.fadeIn(that.fadeSpeed, function() {
21612                            that.spinnerContainer.height('auto');
21613                            that.tabbedNav.height('auto');
21614                            that.reinitJS();
21615                            $(document).trigger('debouncedresize');
21616                            $(document.body).scrollspycustom('refresh');
21617                            jQuery('.tab_nav').css('overflow', 'visible');
21618
21619                            if (jQuery('.searchbar-container').length > 0){
21620                                var event = jQuery.Event('searchbarInTabnav');
21621                                jQuery(window).trigger(event);
21622                            }
21623                        });
21624                        // we call this twice (here and in reinit) as a fallback in case
21625                        // infoblocks doesn't have a height yet, which is needed for equal heights
21626                        var infoblocksContainer = new SHC.ui.InfoblocksContainer("#tabbed-nav-content-wrapper .info-blocks-container");
21627                    });
21628                });
21629            });
21630            $(document.body).scrollspycustom('refresh');
21631        }
21632
21633        function setActivePanel($this) {
21634            var $pageUrl = $this.attr('href');
21635            var $anchor = $('#tab-nav a[href^="' + $pageUrl + '"]');
21636            if (!that.mobileScreen) {
21637                adjustLargeViewPanels($anchor);
21638            }
21639            $(document.body).scrollspycustom('refresh');
21640        }
21641
21642        function adjustLargeViewPanels($anchor) {
21643            var $currentPanel = $anchor.closest('.panel').find('.panel-collapse');
21644            var $currentTabHeading = $anchor.closest('.panel').find('.tab-heading-link');
21645            $currentTabHeading.addClass('active');
21646            var $panelToCollapse = $('#tab-nav .panel-collapse').not('.collapse');
21647
21648            var adjustPanels = function() {
21649                $currentPanel.find('a').removeClass('active');
21650                that.self.find('#tab-nav a').removeClass('active');
21651                $anchor.addClass('active');
21652
21653                //open new panel
21654                $currentPanel.slideDown(that.navAnimateSpeed, function() {
21655                    that.adjustTabnavHeights();
21656                }).removeClass('collapse');
21657                $panelToCollapse.addClass('collapse');
21658            };
21659            //clicking in different panel
21660            if ($panelToCollapse.get(0) !== $currentPanel.get(0) || ($panelToCollapse.length === $currentPanel.length && $currentPanel.length === 0)) {
21661                //we need to check if there's a panel to close (sometimes overview panel will be empty), if there is we need to slide it up before doing anything else
21662                if ($panelToCollapse.length) {
21663                    $panelToCollapse.slideUp(that.navAnimateSpeed, function() {
21664                        that.adjustTabnavHeights();
21665                    });
21666                }
21667                adjustPanels();
21668            } else {
21669                //just change active link
21670                that.self.find('#tab-nav .panel-collapse a').removeClass('active');
21671                $anchor.addClass('active');
21672            }
21673        }
21674
21675        function adjustMobileViewPanels(item) {
21676            var $currentTabHeading = item.closest('.panel').find('.mobile-tab-heading');
21677            var arrowSpan = $currentTabHeading.find('span.tab-heading-carat');
21678            var mobileTabs = $('#mobile-tabs');
21679            var mobileCollapsiblePanels = $('#mobile-tabs').find('.panel-collapse');
21680            var thisPanel = $currentTabHeading.closest('.panel');
21681            var thisCollapsiblePanel = thisPanel.find('.panel-collapse');
21682            var mobileTabHeadings = mobileTabs.find('.mobile-tab-heading');
21683            var arrowSpans = mobileTabs.find('.arrow').find('span');
21684            var listHeadings = that.tabbedNav.find('.parsys.tab-nav-parsys .parbase .rte-has-anchor-link p b');
21685            var redStyleHeaders = that.tabbedNav.find('.parsys.tab-nav-parsys .parbase .rte-has-anchor-link p .red-header-style');
21686            that.self.find('#mobile-tabs .mobile-tab-heading, #mobile-tabs a').removeClass('active');
21687            $currentTabHeading.addClass('active');
21688            that.self.find('#mobile-tabs span').removeClass('active');
21689
21690            //add list-heading class if p has b
21691            if (listHeadings.length > 0) {
21692                var headingP = listHeadings.closest('p');
21693                headingP.addClass('list-heading');
21694            }
21695            //add has-red-header class if such a child exists
21696            //add red-style-header-para class to p
21697            if (redStyleHeaders.length > 0) {
21698                var tabHeading = redStyleHeaders.closest('.mobile-tab-heading').find('.mobile-tab-heading-link');
21699                tabHeading.addClass('has-red-header');
21700                var redStyleHeaderPara = redStyleHeaders.closest('p');
21701                redStyleHeaderPara.addClass('red-style-header-para');
21702            }
21703            //collapse all panels but the one you want to open
21704            mobileCollapsiblePanels.not(thisCollapsiblePanel).collapse('hide');
21705            //show current
21706            thisCollapsiblePanel.collapse('show');
21707            //remove heading actives and add to current
21708            mobileTabHeadings.removeClass('active');
21709            $currentTabHeading.addClass('active');
21710
21711            if (item.closest(".panel-collapse").length > 0) {
21712                item.addClass('active');
21713                var listsToCollapse = mobileCollapsiblePanels.find('li');
21714                var activeAnchor = mobileCollapsiblePanels.find('li a.active');
21715                var activeList = activeAnchor.closest('li');
21716                listsToCollapse.hide();
21717                activeAnchor.hide();
21718                activeList.show();
21719            }
21720
21721            //remove arrow actives and add to current
21722            arrowSpans.not(arrowSpan).removeClass('active');
21723            arrowSpan.addClass('active');
21724            if (!that.mobileScreen) {
21725                $(document.body).scrollspycustom('refresh');
21726            }
21727        }
21728
21729        function appendContent(item) {
21730            if (that.mobileScreen) {
21731                that.tabbedNav.insertAfter(item);
21732                that.reinitJS();
21733            }
21734        }
21735
21736        function collapseMobile() {
21737            var mobileCollapsiblePanels = $('#mobile-tabs').find('.panel-collapse');
21738            var mobileTabs = $('#mobile-tabs');
21739            var mobileTabHeadings = mobileTabs.find('.mobile-tab-heading');
21740            that.self.find('#mobile-tabs .mobile-tab-heading, #mobile-tabs a').removeClass('active');
21741            that.self.find('#mobile-tabs span').removeClass('active');
21742            $('.parent-list-heading').hide();
21743
21744            //collapse all panels but the one you want to open
21745            mobileCollapsiblePanels.collapse('hide');
21746            that.tabbedNav.hide();
21747
21748            //remove heading actives and add to current
21749            mobileTabHeadings.removeClass('active');
21750        }
21751
21752        function attachClickHandlers() {
21753            that.self.find('#tab-nav-toggle').on("click", toggleMobileTabNav);
21754            that.self.find('#tab-nav a, #mobile-tabs a').not('.arrow').unbind('click').on("click", navItemClickHandler);
21755            jQuery(window).on('resizeEnd', that.adjustTabnavHeights);
21756            if (!window.addEventListener) {
21757                window.attachEvent("popstate", browserBackAndForwardButtonIntercepts);
21758            } else {
21759                window.addEventListener("popstate", browserBackAndForwardButtonIntercepts);
21760            }
21761        }
21762
21763        attachClickHandlers();
21764        that.scrollToTabNav();
21765        if (that.mobileScreen) {
21766            loadContent($(ref));
21767        }
21768    },
21769    // mobile tab-nav-toggle click
21770    collapseMobileTabNav: function() {
21771        var that = this;
21772        var $navToggle = that.self.find('#tab-nav-toggle');
21773        var $tabsToToggle = $('#mobile-tabs').find('.mobile-tab-heading').closest('.panel');
21774        //toggle expanded state
21775        $navToggle.removeClass('open');
21776        $tabsToToggle.removeClass('menu-expanded');
21777        //collapse panel if needed
21778        var $currentTab = $('#mobile-tabs .mobile-tab-heading.active');
21779        //keep child tab open
21780        $currentTab.next('.panel-collapse').collapse('show');
21781        $currentTab.find('span').addClass('active');
21782        $navToggle.get(0).firstChild.nodeValue = 'Show Menu';
21783
21784        $(document.body).scrollspycustom('refresh');
21785    },
21786    // mobile tab-nav-toggle click
21787    expandMobileTabNav: function() {
21788        var that = this;
21789        var $navToggle = that.self.find('#tab-nav-toggle');
21790        var $tabsToToggle = $('#mobile-tabs').find('.mobile-tab-heading').closest('.panel');
21791        //toggle expanded state
21792        $navToggle.addClass('open');
21793        $tabsToToggle.addClass('menu-expanded');
21794        $navToggle.get(0).firstChild.nodeValue = 'Hide Menu';
21795
21796        $(document.body).scrollspycustom('refresh');
21797    },
21798
21799    // Figure out which nav links should be active and collapsed on page load
21800    initTabNav: function() {
21801        var that = this;
21802        var pageUrl = $(location).attr('href');
21803        $('body').append('<div id="original-landing-url-tab-nav" style="display: none">' + window.location.href + '</div>');
21804        that.self.find('#tab-nav a').not('.arrow').each(function() {
21805            // if element is the current page, make active
21806            var $linkSplit = $(this).attr('href').split("/");
21807            var $linkLastBit = $linkSplit[$linkSplit.length - 2] + "/" + $linkSplit[$linkSplit.length - 1];
21808            var $pageUrlSplit = pageUrl.split("/");
21809            var $strippedOfQueryParam = $pageUrlSplit[$pageUrlSplit.length - 1].split("?")[0];
21810            var $pageUrlLastBit = $pageUrlSplit[$pageUrlSplit.length - 2] + "/" + $strippedOfQueryParam;
21811            var $pageUrlLastBitStrippedOfHash = $pageUrlLastBit.split("#")[0];
21812            var $currentTabHeading = $(this).closest('.panel').find('.tab-heading-link');
21813            var $parentPanel;
21814            // check if it is sub item
21815            if (!($(this).hasClass('tab-heading-link'))) {
21816                $parentPanel = $(this).closest('.panel-collapse');
21817            } else {
21818                $parentPanel = $(this).parent().next('.panel-collapse');
21819            }
21820            if (!$parentPanel.length) {
21821                $currentTabHeading.find('span').addClass('no-children');
21822            }
21823
21824            if ($linkLastBit === $pageUrlLastBitStrippedOfHash) {
21825                $(this).addClass('active');
21826                // uncollapse if not already
21827                if (!$parentPanel.hasClass('in')) {
21828                    that.self.find('#tab-nav .panel-collapse').removeClass('in').addClass('collapse');
21829                    $parentPanel.removeClass('collapse').addClass('in').css("height", "auto");
21830                }
21831                $currentTabHeading.addClass('active');
21832            }
21833        });
21834
21835        //initialize sidenav links as collapsable objects (needed for bootstrap)
21836        that.self.find('#tab-nav .panel-collapse').each(function() {
21837            $(this).collapse({
21838                toggle: false
21839            });
21840        });
21841        $(document.body).scrollspycustom('refresh');
21842    },
21843    // Figure out which nav links should be active and collapsed on page load (Mobile)
21844    initMobileTabNav: function() {
21845        var that = this;
21846        var pageUrl = $(location).attr('href');
21847        that.self.find('#mobile-tabs a').not('.arrow, #tab-nav-toggle').each(function() {
21848            // if element is the current page, make active
21849            var $linkSplit = $(this).attr('href').split("/");
21850            var $linkLastBit = $linkSplit[$linkSplit.length - 2] + "/" + $linkSplit[$linkSplit.length - 1];
21851            var $pageUrlSplit = pageUrl.split("/");
21852            var $strippedOfQueryParam = $pageUrlSplit[$pageUrlSplit.length - 1].split("?")[0];
21853            var $pageUrlLastBit = $pageUrlSplit[$pageUrlSplit.length - 2] + "/" + $strippedOfQueryParam;
21854            var $pageUrlLastBitStrippedOfHash = $pageUrlLastBit.split("#")[0];
21855            var $currentTabHeading = $(this).closest('.panel').find('.mobile-tab-heading');
21856
21857            var $parentPanel;
21858            // check if it is sub item
21859            if (!($(this).hasClass('mobile-tab-heading-link'))) {
21860                $parentPanel = $(this).closest('.panel-collapse');
21861            } else {
21862                $parentPanel = $(this).parent().next('.panel-collapse');
21863            }
21864            if (!$parentPanel.length) {
21865                $currentTabHeading.find('span').addClass('no-children');
21866            }
21867
21868            //show each tab on load
21869            $currentTabHeading.parent().addClass('menu-expanded');
21870            if ($linkLastBit === $pageUrlLastBitStrippedOfHash) {
21871                var ref = this;
21872                $('#tabbed-nav-content-wrapper').hide();
21873                var domRef = $(ref);
21874                if (domRef.hasClass('mobile-tab-heading-link')) {
21875                    that.setup(ref);
21876                }
21877                else {
21878                    var $currentPanel = domRef.closest('.panel.menu-expanded');
21879                    var $parentAnchor = $currentPanel.find('.mobile-tab-heading-link');
21880                    var anchorDom = $parentAnchor[0];
21881                    that.contentLoadFlag.reference = ref;
21882                    that.contentLoadFlag.secondLoadNeeded = true;
21883                    that.setup(anchorDom);
21884                }
21885            }
21886        });
21887        //initialize sidenav links as collapsable objects (needed for bootstrap)
21888        that.self.find('#mobile-tabs .panel-collapse').each(function() {
21889            $(this).collapse({
21890                toggle: false
21891            });
21892        });
21893    },
21894    secondContentLoad: function() {
21895        var that = this;
21896        if (that.contentLoadFlag.secondLoadNeeded === true) {
21897            that.setup(that.contentLoadFlag.reference);
21898            that.contentLoadFlag.secondLoadNeeded = false;
21899            that.contentLoadFlag.reference = null;
21900        }
21901        if(typeof SHC.mobileClickItem !== 'undefined' && SHC.ui.screenMode === 'small'){
21902            $('html, body').animate({
21903                scrollTop: SHC.mobileClickItem.offset().top
21904            }, 500);
21905        }
21906    },
21907    hideUnneededFeatures: function() {
21908        var that = this;
21909        that.self.find('.quick-nav-bar').hide();
21910        that.self.find('.quick-nav-bar').parent().hide();
21911        that.self.find('a.quick-nav-next').hide();
21912        that.self.find('a.quick-nav-prev').hide();
21913    },
21914    computeAndSetOffsetsForTabnav: function() {
21915        if (!Modernizr.touch && !SHC.util.isIE()) {
21916            var that = this;
21917            var searchHeight = $('#search-inpagenav').height();
21918        }
21919    },
21920    adjustTabnavHeights: function() {
21921        var that = this;
21922        if (typeof that.sideNavParent !== 'undefined') {
21923            that.sideNavParent.css("min-height", that.sideNav.height());
21924        }
21925    },
21926    scrollToTopOfNav: function() {
21927        var that = this;
21928        var sideNavTop = (that.sideNav.offset() ? that.sideNav.offset().top : 0);
21929        var tabnavWrapperTop = that.sideNavParent.offset().top;
21930        var searchHeight = $('#search-inpagenav').height();
21931        var scrollToHere = tabnavWrapperTop - searchHeight - that.designOffsetForSidenav;
21932        if (!isNaN(scrollToHere)) {
21933            // if sidenav is below top of tabnav, scroll up
21934            if (sideNavTop > tabnavWrapperTop || $(document).scrollTop() + searchHeight > jQuery('#tabbed-nav-content-wrapper').offset().top) {
21935                $('body,html').animate({
21936                    scrollTop: scrollToHere + "px"
21937                }, 0);
21938            }
21939        }
21940    },
21941    /**
21942     * Scrolls to the tab nav on load for sub pages
21943     */
21944    scrollToTabNav: function() {
21945        var pageTemplate = jQuery('#shc-search-title').data('page-template');
21946        var isHub = pageTemplate.indexOf('hubpage') !== -1 ||
21947            pageTemplate.indexOf('conditionhub') !== -1 ||
21948            pageTemplate.indexOf('clinicl') !== -1 ||
21949            pageTemplate.indexOf('generictabnav') !== -1;
21950        var hash = location.hash;
21951        var searchHeight = jQuery('#search-inpagenav').outerHeight();
21952        var h2Height = jQuery('.general_container .shc-title h2.scroll-adjust').first().outerHeight(true);
21953        var sidenavHeight = 0;
21954        //if small, no searchheight plus sidenav
21955        if (!jQuery('#checkBootStrapXS').is(':visible')) {
21956            // no search
21957            searchHeight = 0;
21958            sidenavHeight = jQuery('#side-nav').outerHeight();
21959        }
21960        var topOffset = searchHeight + h2Height + sidenavHeight + 15;
21961        if (!hash && !isHub) {
21962            var $anchor = jQuery("#tab-navigation_.clinic-with-h2");
21963            if ($anchor.length) {
21964                setTimeout(function() {
21965                    var animation = {
21966                        scrollTop: $anchor.offset().top - topOffset
21967                    };
21968                    $('html,body').animate(animation, 500, 'swing', function() {
21969                    });
21970                }, 1000);
21971            }
21972        }
21973    },
21974    reinitJS: function() {
21975        var modal = new SHC.ui.Modal(this.parent + " .open-modal");
21976        var revealBoxes = new SHC.ui.RevealBox("#tabbed-nav-content-wrapper .reveal-box");
21977        var presentationMode = new SHC.ui.PresentationMode("#tabbed-nav-content-wrapper .presentation", true);
21978        var eventCollection = new SHC.ui.Event.Collection("#tabbed-nav-content-wrapper .event-collection");
21979        var revealBoxesExpert = new SHC.ui.RevealBoxExpert(".reveal-box-expert");
21980        var infoblocksContainer = new SHC.ui.InfoblocksContainer("#tabbed-nav-content-wrapper .info-blocks-container");
21981        var quiz = new SHC.ui.Quiz('#quizcontainer');
21982        var display = new SHC.ui.Calculator(".health_Calculator");
21983        // re-intializing Modal
21984        SHC.ui.modalInstance = new SHC.ui.Modal(".open-modal");
21985        jQuery(".inline-video").each(function(index, item) {
21986            var inlineVideo = new SHC.ui.InlineVideo(item);
21987        });
21988        var tileTruncation = new SHC.ui.TileTruncation();
21989        if(SHC.ui.screenMode === 'small'){
21990            if($('.form_button_submit.g-recaptcha').length === 1){
21991                $('.form_button_submit.g-recaptcha').empty();
21992                $.getScript("https://www.google.com/recaptcha/enterprise.js?render=6Le3JkAtAAAAAGJJ78Y9PgYBYEJReLxwtoVTUse9");
21993            }
21994            //we only want to re attach on mobile, this breaks de
21994sktop google recaptcha causing having to submit 2 times
21995            attachValidation(); //form.js
21996        }
21997    },
21998    contentLoadFlag: {"secondLoadNeeded": false, "reference": null}
21999});
22000SHC.Namespace(SHC, "SHC.ui.TabNav");
22001SHC.ui.TabNav = new SHC.Class();
22002SHC.ui.TabNav.include({
22003    /**
22004     * constructor
22005     */
22006    init: function(parent) {
22007        this.self = $(parent);
22008        this.parent = parent;
22009        this.spinner = this.self.find('.spinner-container');
22010        this.spinnerContainer = this.spinner.parent();
22011        this.tabbedNav = this.self.find('#tabbed-nav');
22012        this.sideNav = jQuery('.side-nav');
22013        this.sideNavParent = jQuery('.side-nav-parent');
22014        this.outerQuickNavBar = jQuery('.outer-quick-nav-bar');
22015        this.isAuthorMode = SHC.util.WCM.isAuthorMode();
22016        this.fadeSpeed = 50;
22017        this.navAnimateSpeed = 400;
22018        this.loadedImages = 0;
22019        this.initTabNav();
22020        this.initMobileTabNav();
22021        this.setup();
22022        this.computeAndSetOffsetsForTabnav();
22023        this.adjustTabnavHeights();
22024        this.adjustTriangleColor();
22025    },
22026    setup: function() {
22027        var that = this;
22028
22029        // tab nav item click
22030        var navItemClickHandler = function(e) {
22031            if (window.history.pushState) {
22032                e.preventDefault();
22033                var item = $(this);
22034                var $url = item.attr('href');
22035                setActivePanel(item);
22036                loadContent($url);
22037                pushUrl($url, item.text());
22038            }
22039        };
22040
22041        //setup next button
22042        var nextButtonClickHandler = function(e) {
22043            e.preventDefault();
22044            var $nextPanel = $('a.tab-heading-link.active:last').closest('.panel').next();
22045            setQuickNavClickHandler($nextPanel);
22046        };
22047
22048        //setup previous button
22049        var prevButtonClickHandler = function(e) {
22050            e.preventDefault();
22051            var $prevPanel = $('a.tab-heading-link.active:last').closest('.panel').prev();
22052            setQuickNavClickHandler($prevPanel);
22053        };
22054
22055        //intercepts the browswer back/forward button clicks
22056        var browserBackAndForwardButtonIntercepts = function(e) {
22057            var previousTabHeading = $('a.tab-heading-link.active').text();
22058            if (window.history.pushState) {
22059                var pathLoad;
22060                if(e.state){
22061                    pathLoad = e.state.path;
22062                }
22063                else{
22064                    pathLoad = $('div#original-landing-url-tab-nav').text();
22065                }
22066                loadContent(pathLoad);
22067
22068                that.self.find("#tab-nav a.active").removeClass("active");
22069                that.self.find("#tab-nav-mobile .active").removeClass("active");
22070                that.self.find("#mobile-tabs .panel-collapse.in").removeClass('in').addClass('collapse');
22071                $('#tab-nav .panel-collapse').addClass('collapse');
22072
22073                // === DESKTOP === //
22074                that.self.find("#tab-nav a").each(function() {
22075                    var parentPanel = $(this).closest('.panel');
22076                    if (pathLoad.indexOf($(this).attr("href")) !== -1) {
22077                        $(this).addClass('active');
22078
22079                        if (!($(this).hasClass('tab-heading-link'))) {
22080                            parentPanel.find('.tab-heading-link').addClass('active');
22081                            parentPanel.find('.panel-collapse').slideDown(that.navAnimateSpeed, function() {
22082                                that.adjustTabnavHeights();
22083                            });
22084                        }
22085                        else{
22086                            $('#tab-nav .panel-collapse').addClass('collapse');
22087                            if(parentPanel.find('.panel-collapse').length === 0){
22088                                parentPanel.find('.panel-collapse:visible').slideUp(that.
22088navAnimateSpeed, function() {
22089                                    that.adjustTabnavHeights();
22090                                    parentPanel.find('.panel-collapse').addClass('collapse');
22091                                });
22092                            }
22093                            else{
22094                                parentPanel.find('.panel-collapse').slideDown(that.navAnimateSpeed, function() {
22095                                    that.adjustTabnavHeights();
22096                                });
22097                            }
22098                        }
22099                    }
22100                    that.updateQuickNav();
22101                });
22102
22103                var closePanel = $('.panel-collapse:visible').siblings().find('.tab-heading-link').not('.active');
22104                if (closePanel.length === 1){
22105                    closePanel.closest('.panel').find('.panel-collapse:visible').slideUp(that.navAnimateSpeed, function() {
22106                        that.adjustTabnavHeights();
22107                    });
22108                }
22109
22110                // === MOBILE === //
22111                that.self.find("#tab-nav-mobile a").each(function() {
22112                    var parentPanel = $(this).closest('.panel');
22113                    if (pathLoad.indexOf($(this).attr("href")) !== -1) {
22114                        $(this).addClass('active');
22115                        if (!($(this).hasClass('mobile-tab-heading'))) {
22116                            parentPanel.find('.mobile-tab-heading').addClass('active');
22117                            parentPanel.find('.tab-heading-carat').addClass('active');
22118                            parentPanel.find('.panel-collapse').removeClass('collapse').addClass('in');
22119                            parentPanel.find('.panel-collapse.in').css('height','auto');
22120                        }
22121                    }
22122                });
22123            }
22124
22125            that.touchDeviceCleanup(previousTabHeading);
22126            $('#tab-nav .tab-heading-link.active').closest('.panel').find('.panel-collapse').removeClass('collapse');
22127
22128        };
22129
22130        // mobile tab-nav-toggle click
22131        var toggleMobileTabNav = function(e) {
22132            e.preventDefault();
22133            var $navToggle = that.self.find('#tab-nav-toggle');
22134            //toggle expanded state
22135            if ($navToggle.hasClass('open')) {
22136                that.collapseMobileTabNav();
22137            } else {
22138                that.expandMobileTabNav();
22139            }
22140        };
22141
22142        function setQuickNavClickHandler($panel) {
22143            if ($panel.size() > 0) {
22144                // change active
22145                that.self.find('#tab-nav a.active').removeClass("active");
22146                $panel.find('a.tab-heading-link').addClass("active");
22147                // add active
22148                var $pageRef = $panel.find('.tab-heading-link');
22149                $pageRef.addClass("active");
22150                // push and load
22151                var $pageUrl = $pageRef.attr("href");
22152                var $anchorText = $pageRef.text();
22153                if (window.history.pushState) {
22154                    setActivePanel($pageRef);
22155                    loadContent($pageUrl);
22156                    pushUrl($pageUrl, $anchorText);
22157                } else {
22158                    window.location = $pageUrl;
22159                }
22160            }
22161            if (window.history.pushState) {
22162                that.updateQuickNav();
22163            }
22164        }
22165
22166        /*
22167         * Pushes the url to the history object and ajax loads the target page
22168         * Or goes directly to the page when authoring
22169         * @param url the target page
22170         * @param anchorText the title for the history object
22171         */
22172        function pushUrl($url, $anchorText) {
22173            // edit history if not authoring and ajax load content
22174            if (!that.isAuthorMode && window.history.pushState) {
22175                var savedHash = "";
22176                var newUrl = "";
22177                if (window.location.hash) {
22178                    savedHash = window.location.hash;
22179                    newUrl = $url + savedHash;
22180                } else {
22181                    newUrl = $url;
22182                }
22183                window.history.pushState({
22184                    "path": newUrl
22185                }, $anchorText, newUrl);
22186                $(document.body).scrollspycustom('refresh');
22187            }
22188            // go to page when authoring
22189            else {
22190                window.location = $url;
22191            }
22192        }
22193
22194        /*
22195         * Loads the tabbed nav div from the target url
22196         * Binds any child lists after ajax load
22197         * @param {type} url - the target url
22198         * @returns {undefined}
22199         */
22200        function loadContent($url) {
22201            that.spinnerContainer.height(that.sideNavParent.height() - that.outerQuickNavBar.height());
22202            that.hideQuickNav();
22203            that.tabbedNav.fadeOut(that.fadeSpeed, function() {
22204                that.spinner.show();
22205                that.scrollToTopOfNav();
22206                that.tabbedNav.load($url + " #tabbed-nav .tab-nav-parsys, .healthwise-parsys", function(responseText) {
22207                    that.spinner.hide();
22208                    var autoHeight = that.sideNavParent.css('height', 'auto').outerHeight() - that.outerQuickNavBar.height();
22209                    var seoH1Title = $(responseText).find('.shc-page-title');
22210                    if(seoH1Title.length > 0) {
22211                        var seoH1TitleText = seoH1Title.text();
22212                        $(".shc-page-title").text(seoH1TitleText);
22213                    }
22214                    else {
22215                        var title = that.self.find('#tab-nav a.active').text();
22216                        $(".shc-page-title").text(title);
22217                    }
22218                    that.spinnerContainer.animate({
22219                        height: autoHeight
22220                    }, that.navAnimateSpeed, function() {
22221                        that.tabbedNav.fadeIn(that.fadeSpeed, function() {
22222                            that.spinnerContainer.height('auto');
22223                            that.tabbedNav.height('auto');
22224                            that.showQuickNav();
22225                            that.reinitJS();
22226                            $(document).trigger('debouncedresize');
22227                            $(document.body).scrollspycustom('refresh');
22228                            jQuery('.tab_nav').css('overflow', 'visible');
22229
22230                            if (jQuery('.searchbar-container').length > 0){
22231                                var event = jQuery.Event('searchbarInTabnav');
22232                                jQuery(window).trigger(event);
22233                            }
22234                        });
22235                        // we call this twice (here and in reinit) as a fallback in case
22236                        // infoblocks doesn't have a height yet, which is needed for equal heights
22237                        var infoblocksContainer = new SHC.ui.InfoblocksContainer("#tabbed-nav-content-wrapper .info-blocks-container");
22238                    });
22239                });
22240            });
22241        }
22242
22243        function setActivePanel($this) {
22244            var $pageUrl = $this.attr('href');
22245            var $anchor = $('#tab-nav a[href="' + $pageUrl + '"]');
22246            adjustLargeViewPanels($anchor);
22247            $anchor = $('#mobile-tabs a[href^="' + $pageUrl + '"]');
22248            adjustMobileViewPanels($anchor);
22249            that.adjustTriangleColor();
22250            that.updateQuickNav();
22251            $(document.body).scrollspycustom('refresh');
22252            that.touchDeviceCleanup();
22253        }
22254
22255        function adjustLargeViewPanels($anchor) {
22256            var $currentPanel = $anchor.closest('.panel').find('.panel-collapse');
22257            var $currentTabHeading = $anchor.closest('.panel').find('.tab-heading-link');
22258            $currentTabHeading.addClass('active');
22259            var $panelToCollapse = $('#tab-nav .panel-collapse').not('.collapse');
22260
22261            //combinations of browser back button and tab clicks can leave a panel visible even when it has the collapse class
22262            if( $('div.panel-collapse.collapse li:visible').parent().length > 0){
22263                $('div.panel-collapse.collapse li:visible').closest('div').hide();
22264            }
22265
22266            var adjustPanels = function() {
22267                $currentPanel.find('a').removeClass('active');
22268                that.self.find('#tab-nav a').removeClass('active');
22269                $anchor.addClass('active');
22270
22271                //force the tab heading link active when an item on the dropdown is active
22272                if ($('#tab-nav .panel li a.active').length === 1){
22273                    var tabHeading = $('#tab-nav .panel li a.active').closest('div.panel').find('.tab-heading-link');
22274                    if (tabHeading.not('active')){
22275                        tabHeading.addClass('active');
22276                    }
22277                }
22278
22279                //open new panel
22280                $currentPanel.slideDown(that.navAnimateSpeed, function() {
22281                    that.adjustTabnavHeights();
22282                }).removeClass('collapse');
22283                $panelToCollapse.addClass('collapse');
22284            };
22285            //clicking in different panel
22286            if ($panelToCollapse.get(0) !== $currentPanel.get(0) || ($panelToCollapse.length === $currentPanel.length && $currentPanel.length === 0)) {
22287                //we need to check if there's a panel to close (sometimes overview panel will be empty), if there is we need to slide it up before doing anything else
22288                if ($panelToCollapse.length) {
22289                    $panelToCollapse.slideUp(that.navAnimateSpeed, function() {
22290                        that.adjustTabnavHeights();
22291                    });
22292                }
22293                adjustPanels();
22294            } else {
22295                //just change active link
22296                that.self.find('#tab-nav .panel-collapse a').removeClass('active');
22297                $anchor.addClass('active');
22298            }
22299        }
22300
22301        function adjustMobileViewPanels($anchor) {
22302            var $currentTabHeading = $anchor.closest('.panel').find('.mobile-tab-heading');
22303            var arrowSpan = $currentTabHeading.find('span.tab-heading-carat');
22304            var mobileTabs = $('#mobile-tabs');
22305            var mobileCollapsiblePanels = $('#mobile-tabs').find('.panel-collapse');
22306            var thisPanel = $currentTabHeading.closest('.panel');
22307            var thisCollapsiblePanel = thisPanel.find('.panel-collapse');
22308            var mobileTabHeadings = mobileTabs.find('.mobile-tab-heading');
22309            var arrowSpans = mobileTabs.find('.arrow').find('span');
22310            that.self.find('#mobile-tabs .mobile-tab-heading, #mobile-tabs a').removeClass('active');
22311            $anchor.addClass('active');
22312            $currentTabHeading.addClass('active');
22313            that.self.find('#mobile-tabs span').removeClass('active');
22314
22315            //collapse all panels but the one you want to open
22316            mobileCollapsiblePanels.not(thisCollapsiblePanel).collapse('hide');
22317            //show current
22318            thisCollapsiblePanel.collapse('show');
22319            //remove heading actives and add to current
22320            mobileTabHeadings.removeClass('active');
22321            $currentTabHeading.addClass('active');
22322            //remove arrow actives and add to current
22323            arrowSpans.not(arrowSpan).removeClass('active');
22324            arrowSpan.addClass('active');
22325
22326            that.adjustTriangleColor();
22327
22328            $(document.body).scrollspycustom('refresh');
22329
22330        }
22331
22332        that.self.find('a.quick-nav-next').on("click", nextButtonClickHandler);
22333        that.self.find('a.quick-nav-prev').on("click", prevButtonClickHandler);
22334        that.self.find('#tab-nav-toggle').on("click", toggleMobileTabNav);
22335        that.self.find('#tab-nav a, #mobile-tabs a').not('.arrow').on("click", navItemClickHandler);
22336        jQuery(window).on('resizeEnd', that.adjustTabnavHeights);
22337        if (!window.addEventListener) {
22338            window.attachEvent("popstate", browserBackAndForwardButtonIntercepts);
22339        } else {
22340            window.addEventListener("popstate", browserBackAndForwardButtonIntercepts);
22341        }
22342        that.scrollToTabNav();
22343    },
22344    // mobile tab-nav-toggle click
22345    collapseMobileTabNav: function() {
22346        var that = this;
22347        var $navToggle = that.self.find('#tab-nav-toggle');
22348        var $tabsToToggle = $('#mobile-tabs').find('.mobile-tab-heading').closest('.panel');
22349        //toggle expanded state
22350        $navToggle.removeClass('open');
22351        $tabsToToggle.removeClass('menu-expanded');
22352        //collapse panel if needed
22353        var $currentTab = $('#mobile-tabs .mobile-tab-heading.active');
22354        that.adjustTriangleColor();
22355        //keep child tab open
22356        $currentTab.next('.panel-collapse').collapse('show');
22357        $currentTab.find('span').addClass('active');
22358        $navToggle.get(0).firstChild.nodeValue = 'Show Menu';
22359
22360        $(document.body).scrollspycustom('refresh');
22361    },
22362    // mobile tab-nav-toggle click
22363    expandMobileTabNav: function() {
22364        var that = this;
22365        var $navToggle = that.self.find('#tab-nav-toggle');
22366        var $tabsToToggle = $('#mobile-tabs').find('.mobile-tab-heading').closest('.panel');
22367        //toggle expanded state
22368        $navToggle.addClass('open');
22369        $tabsToToggle.addClass('menu-expanded');
22370        that.adjustTriangleColor();
22371        $navToggle.get(0).firstChild.nodeValue = 'Hide Menu';
22372
22373        $(document.body).scrollspycustom('refresh');
22374    },
22375
22376    // Figure out which nav links should be active and collapsed on page load
22377    initTabNav: function() {
22378        var that = this;
22379        var pageUrl = $(location).attr('href');
22380        $('body').append('<div id="original-landing-url-tab-nav" style="display: none">'+ window.location.href+'</div>');
22381        that.self.find('#tab-nav a').each(function() {
22382            // if element is the current page, make active
22383            var $linkSplit = $(this).attr('href').split("/");
22384            var $linkLastBit = $linkSplit[$linkSplit.length - 2] + "/" + $linkSplit[$linkSplit.length - 1];
22385            var $pageUrlSplit = pageUrl.split("/");
22386            var $strippedOfQueryParam = $pageUrlSplit[$pageUrlSplit.length - 1].split("?")[0];
22387            var $pageUrlLastBit = $pageUrlSplit[$pageUrlSplit.length - 2] + "/" + $strippedOfQueryParam;
22388            var $pageUrlLastBitStrippedOfHash = $pageUrlLastBit.split("#")[0];
22389            var $currentTabHeading = $(this).closest('.panel').find('.tab-heading-link');
22390            var $parentPanel;
22391            // check if it is sub item
22392            if (!($(this).hasClass('tab-heading-link'))) {
22393                $parentPanel = $(this).closest('.panel-collapse');
22394            } else {
22395                $parentPanel = $(this).parent().next('.panel-collapse');
22396            }
22397            if (!$parentPanel.length) {
22398                $currentTabHeading.find('span').addClass('no-children');
22399            }
22400
22401            if ($linkLastBit === $pageUrlLastBitStrippedOfHash) {
22402                $(this).addClass('active');
22403                // uncollapse if not already
22404                if (!$parentPanel.hasClass('in')) {
22405                    that.self.find('#tab-nav .panel-collapse').removeClass('in').addClass('collapse');
22406                    $parentPanel.removeClass('collapse').addClass('in').css("height", "auto");
22407                }
22408                $currentTabHeading.addClass('active');
22409            }
22410        });
22411
22412        //initialize sidenav links as collapsable objects (needed for bootstrap)
22413        that.self.find('#tab-nav .panel-collapse').each(function() {
22414            $(this).collapse({
22415                toggle: false
22416            });
22417        });
22418
22419        that.updateQuickNav();
22420
22421        $(document.body).scrollspycustom('refresh');
22422        that.showQuickNav();
22423    },
22424    // Figure out which nav links should be active and collapsed on page load (Mobile)
22425    initMobileTabNav: function() {
22426        var that = this;
22427        var pageUrl = $(location).attr('href');
22428        that.self.find('#mobile-tabs a').not('.arrow, #tab-nav-toggle').each(function() {
22429            // if element is the current page, make active
22430            var $linkSplit = $(this).attr('href').split("/");
22431            var $linkLastBit = $linkSplit[$linkSplit.length - 2] + "/" + $linkSplit[$linkSplit.length - 1];
22432            var $pageUrlSplit = pageUrl.split("/");
22433            var $strippedOfQueryParam = $pageUrlSplit[$pageUrlSplit.length - 1].split("?")[0];
22434            var $pageUrlLastBit = $pageUrlSplit[$pageUrlSplit.length - 2] + "/" + $strippedOfQueryParam;
22435            var $pageUrlLastBitStrippedOfHash = $pageUrlLastBit.split("#")[0];
22436            var $currentTabHeading = $(this).closest('.panel').find('.mobile-tab-heading');
22437
22438            var $parentPanel;
22439            // check if it is sub item
22440            if (!($(this).hasClass('mobile-tab-heading-link'))) {
22441                $parentPanel = $(this).closest('.panel-collapse');
22442            } else {
22443                $parentPanel = $(this).parent().next('.panel-collapse');
22444            }
22445            if (!$parentPanel.length) {
22446                $currentTabHeading.find('span').addClass('no-children');
22447            }
22448
22449            //show each tab on load
22450            $currentTabHeading.parent().addClass('menu-expanded');
22451            if ($linkLastBit === $pageUrlLastBitStrippedOfHash) {
22452                $(this).addClass('active');
22453                $currentTabHeading.addClass('active');
22454                // uncollapse if not already
22455                if (!$parentPanel.hasClass('in')) {
22456                    that.self.find('#mobile-tabs .panel-collapse').removeClass('in').addClass('collapse');
22457                    $parentPanel.removeClass('collapse').addClass('in').css("height", "auto");
22458                }
22459                $currentTabHeading.find('span').addClass('active');
22460            }
22461        });
22462
22463        //initialize sidenav links as collapsable objects (needed for bootstrap)
22464        that.self.find('#mobile-tabs .panel-collapse').each(function() {
22465            $(this).collapse({
22466                toggle: false
22467            });
22468        });
22469        $(document.body).scrollspycustom('refresh');
22470    },
22471    adjustTriangleColor: function() {
22472        var triangle = $('#inner-border-triangle-tab-nav-mobile');
22473        if ($('#tab-nav-toggle').hasClass('open')) {
22474            if ($('.first-tab.active').length) {
22475                triangle.addClass('active');
22476            } else {
22477                triangle.removeClass('active');
22478            }
22479        } else {
22480            triangle.addClass('active');
22481        }
22482    },
22483    updateQuickNav: function() {
22484        var that = this;
22485        var $spanNextText = that.self.find('#tab-nav a.active:first').closest('.panel').next().find('.hiddenoverride').text();
22486        var $spanPrevText = that.self.find('#tab-nav a.active:first').closest('.panel').prev().find('.hiddenoverride').text();
22487        var $nextText = that.self.find('#tab-nav a.active:first').closest('.panel').next().find('.tab-heading-link').text();
22488        var $prevText = that.self.find('#tab-nav a.active:first').closest('.panel').prev().find('.tab-heading-link').text();
22489        var $quicknavbar = that.self.find('.quick-nav-bar');
22490
22491        // Somehow only negative validation is working
22492        if ($spanNextText !== null && $spanNextText !== '') {
22493            $nextText = $spanNextText;
22494        }
22495        if ($spanPrevText !== null && $spanPrevText !== '') {
22496            $prevText = $spanPrevText;
22497        }
22498        if ($nextText === '' && $prevText === '') {
22499            $quicknavbar.hide();
22500            $quicknavbar.parent().hide();
22501        }
22502        if ($nextText === '') {
22503            that.self.find('a.quick-nav-next').hide();
22504        } else {
22505            $quicknavbar.show();
22506            $quicknavbar.parent().removeClass('hidden');
22507            that.self.find('a.quick-nav-next').text($nextText).show();
22508            $('<span></span>').appendTo(that.self.find('a.quick-nav-next'));
22509        }
22510        if ($prevText === '') {
22511            that.self.find('a.quick-nav-prev').hide();
22512        } else {
22513            $quicknavbar.show();
22514            $quicknavbar.parent().removeClass('hidden');
22515            that.self.find('a.quick-nav-prev').text($prevText).show();
22516            $('<span></span>').prependTo(that.self.find('a.quick-nav-prev'));
22517        }
22518    },
22519    showQuickNav: function() {
22520        var that = this;
22521        var navbar = that.self.find('.quick-nav-bar');
22522        navbar.find('.quick-nav-bar-buffer').show();
22523        navbar.removeClass('nopadding-hidden');
22524        navbar.show();
22525    },
22526    hideQuickNav: function() {
22527        var that = this;
22528        var navbar = that.self.find('.quick-nav-bar');
22529        navbar.find('.quick-nav-bar-buffer').hide();
22530        navbar.addClass('nopadding-hidden');
22531        navbar.hide();
22532    },
22533    computeAndSetOffsetsForTabnav: function() {
22534        if (!Modernizr.touch && !SHC.util.isIE()) {
22535            var that = this;
22536            var searchHeight = $('#search-inpagenav').height();
22537        }
22538    },
22539    adjustTabnavHeights: function() {
22540        var that = this;
22541        if (typeof that.sideNavParent !== 'undefined') {
22542            that.sideNavParent.css("min-height", that.sideNav.height());
22543        }
22544    },
22545    scrollToTopOfNav: function() {
22546        var that = this;
22547        var sideNavTop = that.sideNav.offset().top;
22548        var tabnavWrapperTop = that.sideNavParent.offset().top;
22549        var searchHeight = $('#search-inpagenav').height();
22550        // if sidenav is below top of tabnav, scroll up
22551
22552        if(SHC.ui.screenMode === "small"){
22553            var contentArea = $('#tabbed-nav-content-wrapper.with-sidenav');
22554            $('html, body').animate({
22555                scrollTop: contentArea.offset().top
22556            }, 500);
22557        }else{
22558            if (sideNavTop > tabnavWrapperTop || $(document).scrollTop() + searchHeight > jQuery('#tabbed-nav-content-wrapper').offset().top) {
22559                var scrollToHere = tabnavWrapperTop - searchHeight - that.designOffsetForSidenav;
22560                $('body,html').animate({
22561                    scrollTop: scrollToHere + "px"
22562                }, 0);
22563            }
22564        }
22565    },
22566    /**
22567     * Scrolls to the tab nav on load for sub pages
22568     */
22569    scrollToTabNav: function() {
22570        var pageTemplate = jQuery('#shc-search-title').data('page-template');
22571        var isHub = pageTemplate.indexOf('hubpage') !== -1 ||
22572            pageTemplate.indexOf('conditionhub') !== -1 ||
22573            pageTemplate.indexOf('clinicl') !== -1 ||
22574            pageTemplate.indexOf('generictabnav') !== -1;
22575        var hash = location.hash;
22576        var searchHeight = jQuery('#search-inpagenav').outerHeight();
22577        var h2Height = jQuery('.general_container .shc-title h2.scroll-adjust').first().outerHeight(true);
22578        var sidenavHeight = 0;
22579        //if small, no searchheight plus sidenav
22580        if (!jQuery('#checkBootStrapXS').is(':visible')) {
22581            // no search
22582            searchHeight = 0;
22583            sidenavHeight = jQuery('#side-nav').outerHeight();
22584        }
22585        var topOffset = searchHeight + h2Height + sidenavHeight + 15;
22586        if (!hash && !isHub) {
22587            var $anchor = jQuery("#tab-navigation_.clinic-with-h2");
22588            if ($anchor.length) {
22589                setTimeout(function() {
22590                    var animation = {
22591                        scrollTop: $anchor.offset().top - topOffset
22592                    };
22593                    $('html,body').animate(animation, 500, 'swing', function() {
22594                    });
22595                }, 1000);
22596            }
22597        }
22598    },
22599    reinitJS: function() {
22600        var tileTruncation = new SHC.ui.TileTruncation();
22601        var modal = new SHC.ui.Modal(this.parent + " .open-modal");
22602        var revealBoxes = new SHC.ui.RevealBox("#tabbed-nav-content-wrapper .reveal-box");
22603        var presentationMode = new SHC.ui.PresentationMode("#tabbed-nav-content-wrapper .presentation", true);
22604        var eventCollection = new SHC.ui.Event.Collection("#tabbed-nav-content-wrapper .event-collection");
22605        var revealBoxesExpert = new SHC.ui.RevealBoxExpert(".reveal-box-expert");
22606        var display = new SHC.ui.Calculator(".health_Calculator");
22607        var infoblocksContainer = new SHC.ui.InfoblocksContainer("#tabbed-nav-content-wrapper .info-blocks-container");
22608        // re-intializing Modal
22609        SHC.ui.modalInstance = new SHC.ui.Modal(".open-modal");
22610        jQuery(".inline-video").each(function(index, item) {
22611            var inlineVideo = new SHC.ui.InlineVideo(item);
22612        });
22613    },
22614    touchDeviceCleanup: function(previousTabHeading){
22615        // on touch devices when you click a sub menu and then go back on the browser it will inherit 'nav a:hover' style
22616        // this causes the active link and the previous one to be highlighted red, this will force an element even when
22617        // touch on hover to be gray instead of red(selected)
22618        if(Modernizr.touch){
22619            //fix panel headings
22620            $('a.tab-heading-link:contains("' + previousTabHeading + '")').addClass('touchdevice-hover-cleanup');
22621            $('a.tab-heading-link.active').removeClass('touchdevice-hover-cleanup');
22622
22623            //fix sub panel menus
22624            var inheritedHoverStyle = $('#tab-nav .tab-heading-link.active').closest('.panel').find('.panel-collapse a').not('.active');
22625            inheritedHoverStyle.addClass('touchdevice-hover-cleanup');
22626
22627            var activeTabLink =  $('#tab-nav .tab-heading-link.active').closest('.panel').find('.panel-collapse a.active');
22628            activeTabLink.removeClass('touchdevice-hover-cleanup');
22629        }
22630    }
22631});
22632
22633SHC.Namespace(SHC, "SHC.ui.EventCarousel");
22634SHC.ui.EventCarousel = new SHC.Class();
22635
22636SHC.ui.EventCarousel.include({
22637    /*
22638     * constructor
22639     */
22640    init: function (parent) {
22641
22642        this.parent = parent;
22643        this.carousel = jQuery(this.parent).find('.carousel');
22644        this.activate();
22645        this.equalHeights();
22646    },
22647
22648    activate: function () {
22649
22650        var _this = this;
22651        var $controlLeft = jQuery(_this.parent).find(".carousel-control.left");
22652        var $controlRight = jQuery(_this.parent).find(".carousel-control.right");
22653
22654        var carouselId = jQuery(".eventcarousel");
22655
22656        jQuery(".eventcarousel").find(".deskTopViewCarousel").on("swipeleft",function(e){
22657
22658            var carouselIndicatorsArray = [];
22659
22660            if(!jQuery(_this.parent).find('.carousel-btn:last-child').hasClass("push")){
22661                jQuery(this).find(".carousel-btn").each(function () {
22662                    carouselIndicatorsArray.push(this);
22663                    jQuery(this).removeClass("push");
22664                });
22665
22666                if(carouselIndicatorsArray.length > 0){
22667
22668                    for (var i = 0; i < carouselIndicatorsArray.length; i++) {
22669
22670                        if (jQuery(carouselIndicatorsArray[i]).hasClass("active")) {
22671
22672                            jQuery(carouselIndicatorsArray[i]).removeClass("active");
22673                            if (i + 1 < carouselIndicatorsArray.length) {
22674
22675                                jQuery(carouselIndicatorsArray[i + 1]).addClass("push");
22676                            }
22677                        }
22678                    }
22679
22680                    if(!jQuery(carouselIndicatorsArray[carouselIndicatorsArray.length]).hasClass("push")){
22681
22682                        jQuery(this).carousel("next");
22683                        $controlRight.addClass("paddle-right");
22684                    }
22685                    if(jQuery(carouselIndicatorsArray[carouselIndicatorsArray.length-1]).hasClass("push")){
22686
22687                        $controlRight.removeClass("paddle-right");
22688                    }
22689                    if(!jQuery(carouselIndicatorsArray[0]).hasClass("push")){
22690
22691                        $controlLeft.addClass("paddle-left");
22692                    }
22693                }
22694            }
22695        });
22696
22697        jQuery(".eventcarousel").find(".deskTopViewCarousel").on("swiperight",function(e){
22698
22699            var carouselIndicatorsArray = [];
22700
22701            if(!jQuery(_this.parent).find('.carousel-btn:first-child').hasClass("push")){
22702
22703                jQuery(this).find(".carousel-btn").each(function () {
22704                    carouselIndicatorsArray.push(this);
22705                    jQuery(this).removeClass("push");
22706
22707                });
22708
22709                if(carouselIndicatorsArray.length !== 0){
22710
22711                    for (var i = 0; i < carouselIndicatorsArray.length; i++) {
22712
22713                        if(jQuery(carouselIndicatorsArray[i]).hasClass("active")){
22714
22715                            jQuery(carouselIndicatorsArray[i]).removeClass("active");
22716                            if(i-1 > -1){
22717
22718                                jQuery(carouselIndicatorsArray[i-1]).addClass("push");
22719                            }
22720                        }
22721                    }
22722
22723                    if(!jQuery(carouselIndicatorsArray[0]).hasClass("push")){
22724
22725                        jQuery(this).carousel("prev");
22726                        $controlLeft.addClass("paddle-left");
22727                    }
22728                    if(jQuery(carouselIndicatorsArray[0]).hasClass("push")){
22729                        jQuery(this).carousel("prev");
22730                        $controlLeft.removeClass("paddle-left");
22731                    }
22732                    if(!jQuery(carouselIndicatorsArray[carouselIndicatorsArray.length]).hasClass("push")){
22733
22734                        $controlRight.addClass("paddle-right");
22735                    }
22736                }
22737            }
22738        });
22739
22740        $controlRight.on("click",function(e){
22741
22742            e.preventDefault();
22743            var carouselIndicatorsArray = [];
22744            var carouselIndicatorFound = false;
22745
22746            $('.deskTopViewCarousel .carousel-indicators .carousel-btn').each(function () {
22747
22748                carouselIndicatorsArray.push(this);
22749                jQuery(this).removeClass("push");
22750            });
22751            for(var i=0;i<carouselIndicatorsArray.length;i++){
22752
22753                if(jQuery(carouselIndicatorsArray[i]).hasClass("active")){
22754
22755                    jQuery(carouselIndicatorsArray[i]).removeClass("active");
22756                    if(i+1 < carouselIndicatorsArray.length){
22757
22758                        jQuery(carouselIndicatorsArray[i+1]).addClass("push");
22759                    }
22760                }
22761            }
22762            if(jQuery(carouselIndicatorsArray[carouselIndicatorsArray.length-1]).hasClass("push")){
22763
22764                $controlRight.removeClass("paddle-right");
22765            }
22766            if(jQuery(carouselIndicatorsArray[0]).hasClass("push")){
22767
22768                $controlLeft.removeClass("paddle-left");
22769            } else {
22770                $controlLeft.addClass("paddle-left");
22771            }
22772        });
22773
22774        $controlLeft.on("click",function(e){
22775
22776            e.preventDefault();
22777            var carouselIndicatorsArray = [];
22778            var carouselIndicatorFound = false;
22779
22780            $('.deskTopViewCarousel .carousel-indicators .carousel-btn').each(function () {
22781                carouselIndicatorsArray.push(this);
22782                jQuery(this).removeClass("push");
22783            });
22784            for(var i=0;i<carouselIndicatorsArray.length;i++){
22785
22786                if(jQuery(carouselIndicatorsArray[i]).hasClass("active")){
22787                    jQuery(carouselIndicatorsArray[i]).removeClass("active");
22788                    if(i-1 > -1){
22789
22790                        jQuery(carouselIndicatorsArray[i-1]).addClass("push");
22791                    }
22792                }
22793            }
22794            if(jQuery(carouselIndicatorsArray[0]).hasClass("push")){
22795
22796                $controlLeft.removeClass("paddle-left");
22797            }
22798            if(jQuery(carouselIndicatorsArray[carouselIndicatorsArray.length-1]).hasClass("push")){
22799
22800                $controlRight.removeClass("paddle-right");
22801            } else {
22802                $controlRight.addClass("paddle-right");
22803            }
22804        });
22805
22806        if($controlRight) {
22807            $('.deskTopViewCarousel .item:first').next().addClass('second');
22808            $('.deskTopViewCarousel .item:last-child').prev().addClass('penultimate');
22809            $('.deskTopViewCarousel .carousel-indicators .carousel-btn:first').addClass('first');
22810            $('.deskTopViewCarousel .carousel-indicators .carousel-btn:last-child').addClass('last');
22811        }
22812
22813        // Carousel button click
22814        jQuery(_this.parent).find(".carousel-btn").on("mousedown", function (e) {
22815
22816            e.preventDefault();
22817
22818            var carouselIndicatorsArray = [];
22819
22820            jQuery('.deskTopViewCarousel .carousel-indicators .carousel-btn').each(function () {
22821
22822                carouselIndicatorsArray.push(this);
22823            });
22824            jQuery(_this.parent).find('.carousel-btn').each(function () {
22825
22826
22827                jQuery(this).removeClass("push");
22828            });
22829
22830            jQuery(this).addClass("push");
22831
22832            if(jQuery(carouselIndicatorsArray[carouselIndicatorsArray.length-1]).hasClass("push")){
22833
22834                $controlRight.removeClass("paddle-right");
22835            }else{
22836
22837                $controlRight.addClass("paddle-right");
22838            }
22839            if(jQuery(carouselIndicatorsArray[0]).hasClass("push")){
22840
22841                $controlLeft.removeClass("paddle-left");
22842            }else{
22843
22844                $controlLeft.addClass("paddle-left");
22845            }
22846        });
22847
22848        var onResizeHandler = function (e) {
22849
22850            jQuery(".deskTopViewCarousel").carousel(0);
22851            $controlRight.addClass("paddle-right");
22852            $controlLeft.removeClass("paddle-left");
22853            jQuery('.deskTopViewCarousel .carousel-indicators .carousel-btn').each(function () {
22854
22855                jQuery(this).removeClass("push");
22856            });
22857            _this.equalHeights();
22858        };
22859
22860        $(window).on('resize', onResizeHandler);
22861        $controlRight.addClass("paddle-right");
22862        _this.equalHeights();
22863    },
22864
22865    equalHeights: function () {
22866        var _this = this;
22867
22868        _this.carousel.each(function () {
22869            var cards = jQuery(this).find('.bordered-container'),
22870                tallestHeight = 0;
22871
22872            cards.each(function () {
22873                jQuery(this).height('auto');
22874
22875                var height = jQuery(this).height();
22876
22877                if (tallestHeight < height) {
22878
22879                    tallestHeight = height;
22880                }
22881            });
22882
22883            cards.each(function () {
22884
22885                jQuery(this).height(tallestHeight);
22886            });
22887        });
22888    }
22889});
22890SHC.Namespace(SHC, "SHC.ui.Event.Catalog");
22891SHC.ui.Event.Catalog = new SHC.Class();
22892
22893SHC.ui.Event.Catalog.include({
22894    /*
22895     * constructor
22896     */
22897    init: function(parent) {
22898        this.parent = parent;
22899        this.courses = ".courses";
22900        this.back = ".previous";
22901        this.forward = ".next";
22902        this.calendar = ".calendar-icon";
22903        this.menu = ".calendar-menu";
22904        this.menuWrapper = ".month-wrapper";
22905        this.month = ".month";
22906        this.dataId = "data-id";
22907
22908        // hide courses for all but first month
22909        jQuery(this.parent).find(this.courses + "[" + this.dataId + "!='0']").hide();
22910
22911        this.trimTitles();
22912        this.activate();
22913    },
22914    activate: function() {
22915        var _this = this;
22916
22917        /* HANDLERS */
22918        var onToggleMenu = function(e) {
22919            jQuery(this).closest(_this.menuWrapper).find(_this.menu).toggle();
22920        };
22921        var onMenuItemClick = function(e) {
22922            e.preventDefault();
22923
22924            var newId = jQuery(this).attr(_this.dataId);
22925
22926            _this.updateMonth(jQuery(this), newId);
22927        };
22928        var onPaddleClick = function(e) {
22929            e.preventDefault();
22930
22931            if (!jQuery(this).hasClass("disabled")) {
22932                var newId = jQuery(this).attr(_this.dataId);
22933
22934                _this.updateMonth(jQuery(this), newId);
22935            }
22936        };
22937
22938        /* ACTUAL SETUP */
22939        jQuery(this.parent).each(function() {
22940            var calendar = jQuery(this).find(_this.calendar);
22941            var month = jQuery(this).find(_this.month);
22942            var menu = jQuery(this).find(_this.menu);
22943            var next = jQuery(this).find(_this.forward);
22944            var previous = jQuery(this).find(_this.back);
22945
22946            // menu toggle
22947            month.on("click", onToggleMenu);
22948            calendar.on("click", onToggleMenu);
22949
22950            // menu items
22951            var count = 0;
22952            menu.find("li a").each(function() {
22953                jQuery(this).on("click", onMenuItemClick);
22954                jQuery(this).attr(_this.dataId, count);
22955                count++;
22956            });
22957
22958            // next and previous buttons
22959            next.attr(_this.dataId, 1);
22960            previous.attr(_this.dataId, "");
22961            next.on("click", onPaddleClick);
22962            previous.on("click", onPaddleClick);
22963        });
22964    },
22965    updateMonth: function(element, newId) {
22966        var parent = element.closest(this.parent);
22967        var menu = parent.find(this.menu);
22968        var monthDisplay = parent.find(this.month);
22969        var monthText = parent.find(this.menu).find("li a[" + this.dataId + "='" + newId + "']").text();
22970
22971        monthDisplay.text(monthText);
22972        menu.hide();
22973
22974        this.updateCourses(element, newId);
22975        this.updatePaddles(element, newId);
22976    },
22977    updateCourses: function(element, newId) {
22978        var parent = element.closest(this.parent);
22979
22980        parent.find(this.courses + "[" + this.dataId + "='" + newId + "']").show();
22981        parent.find(this.courses + "[" + this.dataId + "!='" + newId + "']").hide();
22982    },
22983    updatePaddles: function(element, newId) {
22984        newId = parseInt(newId);
22985        var parent = element.closest(this.parent);
22986        var max = parent.find(this.menu).find("li").length - 1;
22987
22988        if (newId > 0) {
22989            var previousId = newId - 1;
22990            parent.find(this.back).removeClass("disabled").attr(this.dataId, previousId);
22991        } else {
22992            parent.find(this.back).addClass("disabled").attr(this.dataId, "");
22993        }
22994
22995        if (newId < max) {
22996            var nextId = newId + 1;
22997            parent.find(this.forward).removeClass("disabled").attr(this.dataId, nextId);
22998        } else {
22999            parent.find(this.forward).addClass("disabled").attr(this.dataId, "");
23000        }
23001    },
23002    trimTitles: function() {
23003        $(".course-name").each(function() {
23004            var text = $.trim($(this).text());
23005            if (text.length > 40) {
23006                $(this).text(text.substr(0, 40) + '...');
23007            }
23008            else {
23009                $(this).text(text);
23010            }
23011        });
23012    }
23013
23014});
23015SHC.Namespace(SHC, "SHC.ui.Event.Collection");
23016SHC.ui.Event.Collection = new SHC.Class();
23017
23018SHC.ui.Event.Collection.include({
23019	/*
23020	 * constructor
23021	 */
23022	init: function(parent) {
23023		this.parent = $(parent);
23024
23025		this.activate();
23026		this.addTopMarginToFirst();
23027	},
23028	activate: function() {
23029		var _this = this;
23030		var titleDisplacement = 100;
23031
23032		var toggleHideIcon = function(parent) {
23033			plusIcon = parent.find('.plus-icon');
23034			minusIcon = parent.find('.minus-icon');
23035
23036			if (plusIcon.hasClass('hide-icon')) {
23037				plusIcon.removeClass('hide-icon');
23038				minusIcon.addClass('hide-icon');
23039			} else {
23040				plusIcon.addClass('hide-icon');
23041				minusIcon.removeClass('hide-icon');
23042			}
23043		};
23044
23045		var handleCategoryToggle = function(e) {
23046			e.preventDefault();
23047			var clickedDiv = $(this);
23048			if (jQuery("#in-page-nav:hidden").length <= 0) {
23049				titleDisplacement = 167;
23050			}
23051
23052			var alertMessage = $('#new-emergency-alert');
23053			var accordion = $(this).closest('.event-collection');
23054			var section = $(this).closest('.section');
23055			toggleHideIcon(section.find('.plus-icon.hide-icon').parent());
23056			if (section.hasClass('active')) {
23057				section.removeClass('active').find('.events').slideUp(function(){
23058						accordion.removeClass('expand');
23059				});
23060			}
23061
23062			else {
23063				section.find(jQuery('.event-detail-image')).show();
23064				activeSection = jQuery('.event-collection .section.active');
23065				activeSection.removeClass('active').find('.events').slideUp();
23066				toggleHideIcon(activeSection.find('.plus-icon.hide-icon').parent());
23067				section.addClass('active').find('.events').slideDown();
23068				setTimeout(function(){
23069				    var offsetClickedDiv = $(clickedDiv).offset().top - titleDisplacement;
23070                    var animation = alertMessage.length > 0 ? {scrollTop:  offsetClickedDiv - alertMessage.height()} :  {scrollTop: offsetClickedDiv};
23071					$('html,body').animate(animation, 500, 'swing', function() {});
23072				}, 500);
23073			}
23074
23075			$(".event").removeClass("active");
23076			jQuery('.show-hide').slideUp();
23077		};
23078
23079		var handleEventToggle = function(e) {
23080			e.preventDefault();
23081			if (jQuery("#in-page-nav:hidden").length <= 0) {
23082				titleDisplacement = 167;
23083			}
23084
23085			var events = jQuery('.event-collection .events');
23086			var event = $(this).closest('.event');
23087			var eventNameLink = event.find('a:first');
23088			var eventName = $(this).closest('.event-name');
23089
23090			_this.hideDefaultImages();
23091
23092			if (event.hasClass('active')) {
23093				toggleHideIcon(event);
23094				event.removeClass('active').find('.show-hide').slideUp();
23095				eventName.addClass('event-name-closed');
23096			} else {
23097				var activeEvent = events.find('.event.active');
23098				toggleHideIcon(activeEvent);
23099				activeEvent.removeClass('active').find('.show-hide').slideUp();
23100				activeEvent.find('.event-name').addClass('event-name-closed');
23101				if (eventNameLink.hasClass('open-modal')) {
23102					toggleHideIcon(event);
23103					event.addClass('active');
23104					if ($(this).hasClass('toggle-icons')) {
23105						eventNameLink.click();
23106					}
23107				} else {
23108					toggleHideIcon(event);
23109					event.addClass('active').find('.show-hide').slideDown();
23110					setTimeout(function(){
23111						var animation = {scrollTop: $(event).offset().top-titleDisplacement};
23112						$('html,body').animate(animation, 500, 'swing', function() {});
23113					}, 500);
23114				}
23115				if(!$(this).find('a').hasClass("open-modal")) {
23116					eventName.removeClass('event-name-closed');
23117				}
23118			}
23119		};
23120
23121
23122		_this.parent.each(function() {
23123			$(this).find("h2, .toggle").on("click", handleCategoryToggle);
23124		});
23125
23126		_this.parent.each(function() {
23127			$(this).find(".event-name").on("click", handleEventToggle);
23128		});
23129
23130		_this.parent.each(function() {
23131			$(this).find(".toggle-icons").on("click", handleEventToggle);
23132		});
23133	},
23134	hideDefaultImages: function() {
23135		jQuery(".event-detail-image").each(function() {
23136			if (jQuery(this).find('.cq-image-placeholder-off').length > 0) {
23137				jQuery(this).hide();
23138			}
23139			if (jQuery(this).find('.cq-image-placeholder').length > 0) {
23140				jQuery(this).hide();
23141			}
23142		});
23143	},
23144	addTopMarginToFirst: function() {
23145		jQuery('.event-collection').first().css('margin-top', '20px');
23146	}
23147});
23148SHC.Namespace(SHC, "SHC.ui.Event.Detail");
23149SHC.ui.Event.Detail = new SHC.Class();
23150
23151SHC.ui.Event.Detail.include({
23152    /*
23153     * constructor
23154     */
23155    init: function(parent) {
23156        this.parent = $(parent);
23157
23158        if (jQuery('.cq-image-placeholder').length > 0) {
23159            jQuery('.event-detail-image').css("display", "none");
23160        }
23161        else {
23162            jQuery('.event-detail-image').css("display", "block");
23163        }
23164    }
23165});
23166SHC.Namespace(SHC, "SHC.ui.InlineVideo");
23167SHC.ui.InlineVideo = new SHC.Class();
23168
23169SHC.ui.InlineVideo.include({
23170    init: function(parent) {
23171        this.parent = parent;
23172        this.$parent = jQuery(parent);
23173        this.$initialRow = this.$parent.find('.initial-row');
23174        this.$inlineVideoContainer = this.$parent.find('.inline-video-container');
23175        this.$videoRow = this.$parent.find('.video-row');
23176        this.$expandedTitleRow = this.$parent.find('.expanded-title-row');
23177        this.$descriptionRow = this.$parent.find('.description-row');
23178        this.$videoTileLink = this.$inlineVideoContainer.find('.video-tile-container a:not([data-presentation-container])');
23179        this.$initialTitle = this.$inlineVideoContainer.find('.title a:not([data-presentation-container])');
23180        this.$playLink = this.$inlineVideoContainer.find('.play-link a:not([data-presentation-container])');
23181        this.$videoContainer = this.$videoRow.find('.video-container');
23182        this.$closeButton = this.$videoContainer.find('.close-button a');
23183        this.$closeButtonDiv = this.$videoContainer.find('.close-button');
23184        this.$videoTileContainer = this.$inlineVideoContainer.find('.video-tile-container');
23185        this.$titleContainer = this.$inlineVideoContainer.find('.title-container');
23186        this.$window = $(window);
23187        this.$document = $(document);
23188        this.bindClicks();
23189        this.doAdjacentSpacing();
23190    },
23191
23192    bindClicks: function() {
23193        var that = this;
23194
23195        var openComponent = function(e) {
23196            e.preventDefault();
23197            that.$initialRow.removeClass('showing').addClass('hiding');
23198            that.$videoRow.removeClass('hiding').addClass('showing');
23199            that.$expandedTitleRow.removeClass('hiding').addClass('showing');
23200            that.$descriptionRow.removeClass('hiding').addClass('showing');
23201            that.$closeButtonDiv.removeClass('hiding').addClass('showing');
23202            if (that.$closeButton.hasClass('hiding')) {
23203                that.$closeButton.removeClass('hiding').addClass('showing');
23204            }
23205            setTimeout(function() {
23206                that.playVideo();
23207            }, 300);
23208        };
23209
23210        var closeComponent = function(e) {
23211            e.preventDefault();
23212            that.pauseVideo();
23213            that.$initialRow.removeClass('hiding').addClass('showing');
23214            that.$videoRow.removeClass('showing').addClass('hiding');
23215            that.$expandedTitleRow.removeClass('showing').addClass('hiding');
23216            that.$descriptionRow.removeClass('showing').addClass('hiding');
23217            that.$closeButtonDiv.removeClass('showing').addClass('hiding');
23218            if (that.$closeButton.hasClass('showing')) {
23219                that.$closeButton.removeClass('showing').addClass('hiding');
23220            }
23221        };
23222
23223        var setContainerSize = function() {
23224            var containerSize = that.$inlineVideoContainer.width();
23225            var windowSize = that.$window.width();
23226
23227            if (windowSize < 400) {
23228                if (containerSize >= 345) {
23229                    that.$videoTileContainer.removeClass('col-xs-4').removeClass('col-xs-6');
23230                    that.$titleContainer.removeClass('col-xs-5').removeClass('medium-screen').removeClass('col-xs-11');
23231                }
23232                else if (containerSize > 310 && containerSize < 345) {
23233                    that.$videoTileContainer.removeClass('col-xs-6').addClass('col-xs-4');
23234                    that.$titleContainer.removeClass('col-xs-11').removeClass('medium-screen').addClass('col-xs-5');
23235                }
23236                else if (containerSize <= 310) {
23237                    that.$videoTileContainer.removeClass('col-xs-4').addClass('col-xs-6');
23238                    that.$titleContainer.removeClass('col-xs-5').addClass('col-xs-11').addClass('medium-screen');
23239                }
23240            }
23241            else {
23242                if (containerSize >= 345) {
23243                    that.$videoTileContainer.removeClass('col-xs-4').removeClass('col-xs-6');
23244                    that.$titleContainer.removeClass('col-xs-5').removeClass('medium-screen').removeClass('col-xs-11');
23245                }
23246                else if (containerSize > 220 && containerSize < 345) {
23247                    that.$videoTileContainer.removeClass('col-xs-6').addClass('col-xs-4');
23248                    that.$titleContainer.removeClass('col-xs-11').removeClass('medium-screen').addClass('col-xs-5');
23249                }
23250                else if (containerSize <= 220) {
23251                    that.$videoTileContainer.removeClass('col-xs-4').addClass('col-xs-6');
23252                    that.$titleContainer.removeClass('col-xs-5').addClass('col-xs-11').addClass('medium-screen');
23253                }
23254            }
23255        };
23256
23257        that.$videoTileLink.on('click.inline-video', openComponent);
23258        that.$initialTitle.on('click.inline-video', openComponent);
23259        that.$playLink.on('click.inline-video', openComponent);
23260        that.$closeButton.on('click.inline-video', closeComponent);
23261        that.$window.on('resizeEnd', setContainerSize);
23262        that.$document.ready(setContainerSize);
23263        if (that.$closeButton.length > 0) {
23264            that.$closeButton.on('click.inline-video', closeComponent);
23265        }
23266    },
23267
23268    pauseVideo: function() {
23269        var ytplayer = this.getYTplayer();
23270        if (!SHC.util.isIOS()) {
23271            if (typeof ytplayer !== "undefined") {
23272                ytplayer.pauseVideo();
23273            } else {
23274                var iframe = this.$videoContainer[0].getElementsByTagName("iframe")[0].contentWindow.postMessage('{"event":"command","func":"pauseVideo","args":""}', '*');
23275            }
23276        }
23277    },
23278
23279    playVideo: function() {
23280        var ytplayer = this.getYTplayer();
23281        if (!SHC.util.isIOS()) {
23282            if (typeof ytplayer !== "undefined") {
23283                ytplayer.playVideo();
23284            } else {
23285                var iframe = this.$videoContainer[0].getElementsByTagName("iframe")[0].contentWindow.postMessage('{"event":"command","func":"playVideo","args":""}', '*');
23286            }
23287        }
23288    },
23289
23290    doAdjacentSpacing: function() {
23291        if (this.$parent.next().is('.inline-video')) {
23292            this.$parent.css({'margin-bottom': '4px'});
23293        }
23294        if (this.$parent.prev().is('.inline-video')) {
23295            this.$parent.css({'margin-top': '0px'});
23296        }
23297    },
23298
23299    getYTplayer: function() {
23300        var ytIframeID = this.$videoContainer[0].getElementsByTagName("iframe")[0].id;
23301        for (var iter = 0; typeof SHC.ytplayers !== "undefined" && SHC.ytplayers != null && iter < SHC.ytplayers.length; iter++) {
23302            if (SHC.ytplayers[iter].f.id === ytIframeID) {
23303                return SHC.ytplayers[iter];
23304            }
23305        }
23306    }
23307});
23308SHC.Namespace(SHC, "SHC.ui.InlineShare");
23309SHC.ui.InlineShare = new SHC.Class();
23310
23311SHC.ui.InlineShare.include({
23312    
23313    init: function(parent){
23314        //declare variables
23315        this.parent = $(parent);
23316
23317        this.$facebook = this.parent.find('.facebook');
23318        this.$twitter = this.parent.find('.twitter');
23319        this.$email = this.parent.find('.email');
23320        this.$linkedin = this.parent.find('.linkedin');
23321        //do stuff
23322        this.activate();
23323    },
23324
23325    activate: function() { 
23326        let that = this;
23327        
23328        // prevent popup on email click           
23329        let preventPopUp = function(e){
23330            e.preventDefault();
23331            let shareText = $(this).attr('class');
23332            let shareHref = $(this).attr('href');
23333            that.socialPopup(shareText, shareHref);
23334        };
23335        
23336        that.$facebook.off('click.inline-share').on('click.inline-share', preventPopUp);
23337        that.$twitter.off('click.inline-share').on('click.inline-share', preventPopUp);
23338        that.$email.off('click.inline-share').on('click.inline-share', preventPopUp);
23339        that.$linkedin.off('click.inline-share').on('click.inline-share', preventPopUp);
23340
23341        // set up share links for bitly urls
23342        that.setUpBitly();
23343
23344    },
23345    // Bitly Magic
23346    // TODO: I think the current url needs to be url encoded per bitly requirements doc
23347    setUpBitly: function(){
23348//            this.setUpBitlyFB();
23349//            this.setUpBitlyTW();
23350//            this.setUpBitlyEmail();
23351    },
23352
23353    // Bitly Magic - LinkedIn
23354    // TODO: I think the current url needs to be url encoded per bitly requirements doc
23355    getBitlyLI: function(){
23356        let locationHref = window.location.href;
23357        // for local testing
23358        if (locationHref.indexOf("localhost") > -1) {
23359            locationHref = locationHref.replaceAll("http://localhost:4502/","https://stanfordhealthcare.org/");
23360        }
23361        locationHref = this.appendDecodedSocialID(locationHref, "ecid=soc-li");
23362        let getter = "https://www.linkedin.com/shareArticle?mini=true&url="+locationHref;
23363        return getter;
23364    },
23365
23366    // Bitly Magic - FB
23367    // TODO: I think the current url needs to be url encoded per bitly requirements doc
23368    getBitlyFB: function(){
23369        let locationHref = window.location.href;
23370        // for local testing
23371        if (locationHref.indexOf("localhost") > -1) {
23372            locationHref = locationHref.replaceAll("http://localhost:4502/","https://stanfordhealthcare.org/");
23373        }
23374        locationHref = this.appendDecodedSocialID(locationHref, "ecid=soc-fb");
23375        let getter = "https://www.facebook.com/sharer/sharer.php?u=" + locationHref;
23376        return getter;
23377    },
23378    
23379    // Bitly Magic - Twitter
23380    // TODO: I think the current url needs to be url encoded per bitly requirements doc
23381    getBitlyTW: function(){
23382        let locationHref = window.location.href;
23383        // for local testing
23384        if (locationHref.indexOf("localhost") > -1) {
23385            locationHref = locationHref.replaceAll("http://localhost:4502/","https://stanfordhealthcare.org/");
23386        }
23387        locationHref = this.appendDecodedSocialID(locationHref, "ecid=soc-tw");
23388        let shareTitle = jQuery('meta[name="mail_title"]').attr('content');
23389        if(jQuery('.share-data').length > 0){
23390            shareTitle = jQuery("meta[name='twitter:title']").attr('content');
23391        }
23392        getter = "https://twitter.com/share?text=" + encodeURIComponent(shareTitle) + "&url=" + locationHref + "&via=StanfordHealth";
23393        return getter;
23394    },
23395    // Bitly Magic - Email
23396    // TODO: I think the current url needs to be url encoded per bitly requirements doc
23397    getBitlyEmail: function(){
23398        let locationHref = window.location.href;
23399        // for local testing
23400        if (locationHref.indexOf("localhost") > -1) {
23401            locationHref = locationHref.replaceAll("http://localhost:4502/","https://stanfordhealthcare.org/");
23402        }
23403        locationHref = this.appendDecodedSocialID(locationHref, "ecid=soc-em");
23404        let getter = "mailto:?subject=Stanford Health Care&body=Stanford Health Care " + locationHref;
23405        if(jQuery('.share-data').length > 0){
23406            shareTitle = jQuery(".share-data meta[name='twitter:title']").attr('content');
23407            shareDescription = jQuery('.share-data meta[name="twitter:description"]').attr('content');
23408            getter = "mailto:?subject=" + shareTitle + "&body=" + shareDescription;
23409        }
23410        return getter;
23411    },
23412
23413    appendDecodedSocialID: function(currentURL, socID) {
23414        if (currentURL.indexOf("/presentation-mode") > -1) {
23415            currentURL = this.removeExistingKwcid(currentURL);
23416            let pmodeIdx = currentURL.indexOf("/presentation-mode");
23417            let baseURL = currentURL.substr(0,pmodeIdx);
23418            let pmodeURL = currentURL.substr(pmodeIdx);
23419            if (baseURL.indexOf("?") > -1) {
23420                if (baseURL.indexOf("ecid") > -1) {
23421                    baseURL = this.removeExistingEcid(baseURL);
23422                }
23423                if (baseURL.indexOf("?") === (baseURL.length - 1)) {
23424                    return baseURL + socID + pmodeURL;
23425                } else {
23426                    return baseURL + "&" + socID + pmodeURL;
23427                }
23428            } else {
23429                return baseURL + "?" + socID + pmodeURL;
23430            }
23431        } else {
23432            if (currentURL.indexOf("?") > -1) {
23433                if (currentURL.indexOf("ecid") > -1) {
23434                    currentURL = this.removeExistingEcid(currentURL);
23435                }
23436                currentURL = this.removeExistingKwcid(currentURL);
23437                if (currentURL.indexOf("?") === (currentURL.length - 1)) {
23438                    return currentURL + socID;
23439                } else {
23440                    return currentURL + "&" + socID;
23441                }
23442            } else {
23443                return currentURL + "?" + socID;
23444            }
23445        }
23446    },
23447
23448    appendSocialID: function(currentURL, socID) {
23449        if (currentURL.indexOf("/presentation-mode") > -1) {
23450            currentURL = this.removeExistingKwcid(currentURL);
23451            let pmodeIdx = currentURL.indexOf("/presentation-mode");
23452            let baseURL = currentURL.substr(0,pmodeIdx);
23453            let pmodeURL = currentURL.substr(pmodeIdx);
23454            if (baseURL.indexOf("?") > -1) {
23455                if (baseURL.indexOf("ecid") > -1) {
23456                    baseURL = this.removeExistingEcid(baseURL);
23457                }
23458                if (baseURL.indexOf("?") === (baseURL.length - 1)) {
23459                    return encodeURIComponent(baseURL + socID + pmodeURL);
23460                } else {
23461                    return encodeURIComponent(baseURL + "&" + socID + pmodeURL);
23462                }
23463            } else {
23464                return encodeURIComponent(baseURL + "?" + socID + pmodeURL);
23465            }
23466        } else {
23467            if (currentURL.indexOf("?") > -1) {
23468                if (currentURL.indexOf("ecid") > -1) {
23469                    currentURL = this.removeExistingEcid(currentURL);
23470                }
23471                currentURL = this.removeExistingKwcid(currentURL);
23472                if (currentURL.indexOf("?") === (currentURL.length - 1)) {
23473                    return encodeURIComponent(currentURL + socID);
23474                } else {
23475                    return encodeURIComponent(currentURL + "&" + socID);
23476                }
23477            } else {
23478                return encodeURIComponent(currentURL + "?" + socID);
23479            }
23480        }
23481    },
23482
23483    /**
23484    * Strips out all instances of ecid=soc- if it exists. Based off the current ecid=soc-tw with 11 characers
23485    * @param url
23486    * @returns {*}
23487    */
23488    removeExistingEcid: function(url) {
23489        let ecidIndex = url.indexOf('ecid=soc-');
23490        let beforeEcid,
23491            afterEcid;
23492        while (ecidIndex !== -1) {
23493            // cut it out
23494            if (url.charAt(ecidIndex - 1) === "&") {
23495                beforeEcid = url.substr(0, ecidIndex - 1);
23496                afterEcid = url.substr(ecidIndex + 11);
23497            } else {
23498                beforeEcid = url.substr(0, ecidIndex);
23499                afterEcid = url.substr(ecidIndex + 12);
23500            }
23501            url = beforeEcid + afterEcid;
23502            ecidIndex = url.indexOf('ecid=soc-');
23503        }
23504        return url;
23505    },
23506    
23507    removeExistingKwcid: function(url) {
23508        let kwcidIndex = url.indexOf('kwcid=');
23509        let presmode = false;
23510        if (url.indexOf(HOME_PAGE_PATH + ".html/presentation-mode") > -1) {
23511            presmode = true;
23512        }
23513        while (kwcidIndex !== -1) {
23514            // cut it out
23515            let endofparamIndex = url.length;
23516            let i = kwcidIndex;
23517            // can't rely on an exact character count, so we need to detect the end of the parameter
23518            while (i < endofparamIndex) {
23519                if (url.charAt(i) === "&") {
23520                    if (i < endofparamIndex) {
23521                        endofparamIndex = i + 1;
23522                    } else {
23523                        endofparamIndex = i;
23524                    }
23525                    break;
23526                }
23527                //need to account for presentation mode special case on home page
23528                if (presmode) {
23529                    if (url.substr(i, 37) === HOME_PAGE_PATH + ".html/presentation-mode") {
23530                        endofparamIndex = i;
23531                        if (url.charAt(kwcidIndex - 1) === "?") {
23532                            kwcidIndex = kwcidIndex - 1;
23533                        }
23534                        break;
23535                    }
23536                }
23537                i++;
23538                if (i === endofparamIndex) {
23539                    if (url.charAt(kwcidIndex - 1) === "&") {
23540                        kwcidIndex = kwcidIndex - 1;
23541                    }
23542                    endofparamIndex = i;
23543                }
23544            }
23545            let beforeEcid = url.substr(0, kwcidIndex);
23546            let afterEcid = url.substr(endofparamIndex);
23547            url = beforeEcid + afterEcid;
23548            kwcidIndex = url.indexOf('kwcid=');  // detect multiple instances of the parameter
23549        }
23550        return url;
23551    },
23552    
23553   socialPopup: function(elementText, url) {
23554       // detect which network we're on
23555       // get bit.ly link
23556       // then open window
23557       let bitLink;
23558       switch (elementText) {
23559           case "linkedin":
23560               bitLink = this.getBitlyLI();
23561               window.open(bitLink, 'shcsocial', 'width=400,height=500');
23562               break;
23563            case "facebook":
23564                bitLink = this.getBitlyFB();
23565                window.open(bitLink, 'shcsocial', 'width=400,height=500');
23566                break;
23567            case "twitter":
23568                bitLink = this.getBitlyTW();
23569                window.open(bitLink, 'shcsocial', 'width=400,height=500');
23570                break;
23571            case "email":
23572                bitLink = this.getBitlyEmail();
23573                //window.open(bitLink, 'shcsocial', 'width=400,height=500');
23574                window.location = bitLink;
23575                break;
23576            default:
23577                document.location.href = url;
23578       }
23579   },
23580
23581    getSelectedText: function() {
23582        let selectedText = jQuery("h1").text();
23583        if(window.getSelection){
23584            selectedText = window.getSelection();
23585        } else if(document.getSelection){
23586            selectedText = document.getSelection();
23587        } else if(document.selection){
23588            selectedText = document.selection.createRange();
23589        }
23590        return selectedText;
23591    }
23592    
23593});
23594SHC.Namespace(SHC, "SHC.ui.MediaResources");
23595SHC.ui.MediaResources = new SHC.Class();
23596
23597SHC.ui.MediaResources.include({
23598    /*
23599     * constructor
23600     */
23601    init: function(parent) {
23602        this.parent = parent;
23603        this.margin = this.parent.attr("margin_data");
23604        this.activate(parent , this.margin);
23605        if(this.margin){
23606            this.onResizeHandler();
23607        }
23608    },
23609    /**
23610     * Setup event handlers reside here.
23611     */
23612    activate: function () {
23613        var that = this;
23614        var onResizeHandler = function () {
23615            that.onResizeHandler();
23616        };
23617        $(window).on("resizeEnd",onResizeHandler);
23618    },
23619    onResizeHandler:function(){
23620        if(SHC.ui.screenMode === 'small'){
23621            this.parent.css({ 'margin-top' : '17px'});
23622        }else{
23623
23624            this.parent.css({ 'margin' : this.margin});
23625        }
23626    }
23627});
23628SHC.Namespace(SHC, "SHC.ui.RevealBoxExpert");
23629SHC.ui.RevealBoxExpert = new SHC.Class();
23630
23631SHC.ui.RevealBoxExpert.include({
23632    init: function(parent) {
23633        this.parent = $(parent);
23634        this.speed = 200; //animation speed
23635        $('.reveal-box-expert').last().addClass('last');
23636        this.activate();
23637        this.expandDefaultedBoxes();
23638    },
23639    activate: function() {
23640        var that = this;
23641
23642        var handleClick = function(e) {
23643            e.preventDefault();
23644            var wasActive = $(this).closest('.box-active').find('.reveal-arrow-expert').hasClass('active');
23645            $(".reveal-box-expert").removeClass('box-active');
23646            $(this).closest(".reveal-box-expert").addClass('box-active');
23647            $(this).closest(".box-active").find(".reveal-arrow-expert").toggleClass("active");
23648            $(this).closest(".box-active").find(".reveal-content-expert").slideToggle(function() {
23649                if ($(this).closest('#tabbed-nav').length > 0) {
23650                    window.scrollBy(0, 1); //for sticky nav
23651                }
23652                var tileTruncation = new  SHC.ui.TileTruncation();
23653            });
23654            for (var i = 0; i < $(".reveal-box-expert").length; i++) {
23655                if (!$(".reveal-box-expert").eq(i).hasClass('box-active')) {
23656                    $(".reveal-box-expert").eq(i).find(".reveal-content-expert").slideUp();
23657                    $(".reveal-box-expert").eq(i).find(".reveal-arrow-expert").removeClass('active');
23658                }
23659            }
23660            var titleDisplacement = 100;
23661            if (jQuery("#in-page-nav:hidden").length <= 0) {
23662                titleDisplacement += 67;
23663            }
23664            //don't animate to top of page when closing
23665            if (!wasActive) {
23666                setTimeout(function() {
23667                    var alertbox = $("#new-emergency-alert");
23668                    var boxActiveOffset = $('.box-active').find('.reveal-title-expert').offset().top - titleDisplacement;
23669                    var animation = alertbox.length > 0 ? {scrollTop: boxActiveOffset - alertbox.height() } : {scrollTop: boxActiveOffset};
23670                    $('html,body').animate(animation, 500, 'swing', function() {
23671                    });
23672                }, 500);
23673                //push heading text to adobe data layer
23674                var headingText = $(this).closest(".reveal-box-expert").find(".reveal-title-expert .reveal-title").text();
23675            	stanford.analytics.send(stanford.analytics.createComponentClickSection('',headingText, "accordion"));
23676            }
23677        };
23678
23679        that.parent.each(function() {
23680            $(this).find(".expert-trigger").unbind().on("click", handleClick);
23681
23682            $(this).keypress(function(e) {
23683                if (e.which === 13) {
23684                    var $trigger = $(this).find('.expert-trigger');
23685                    if ($trigger.length) {
23686                        $($trigger[0]).click();
23687                    }
23688                }
23689            });
23690        });
23691
23692    },
23693
23694    expandDefaultedBoxes: function () {
23695        var defaultExpanded = $(".reveal-box-expert.expanded");
23696        for (var j = 0; j < defaultExpanded.length; j++) {
23697                 defaultExpanded.eq(j).addClass('box-active');
23698                 defaultExpanded.eq(j).find(".reveal-arrow-expert").addClass("active");
23699                 defaultExpanded.eq(j).find(".reveal-content-expert").show();
23700        }
23701    }
23702});
23703SHC.Namespace(SHC, "SHC.ui.Hub.Detail");
23704SHC.ui.Hub.Detail = new SHC.Class();
23705
23706SHC.ui.Hub.Detail.include({
23707    /*
23708     * constructor
23709     */
23710    init: function(parent) {
23711        var hubTitle = jQuery.trim(jQuery('#hub-name-text').text());
23712        var pageTitle = jQuery.trim(jQuery("#page-name-text").text());
23713        var completePageTitle = "";
23714        if (hubTitle !== pageTitle && jQuery.trim(pageTitle) !== "Overview") {
23715            completePageTitle = hubTitle + ": " + pageTitle;
23716        }
23717        else {
23718            completePageTitle = hubTitle;
23719        }
23720        jQuery(document).attr('title', completePageTitle);
23721        jQuery('#shc-search-title').text(completePageTitle);
23722    }
23723});
23724SHC.Namespace(SHC, "SHC.ui.LocationPage");
23725SHC.ui.LocationPage = new SHC.Class();
23726SHC.ui.LocationPage.include({
23727
23728    // creates the map with accompanying functionality
23729    init: function(showLink) {
23730        var that = this;
23731        this.showLink = showLink;
23732        var slingResourcePath = jQuery(".map-wrapper").attr("data-map");
23733        var splitSlashArray = slingResourcePath.split("/");
23734        var locationSubpath = splitSlashArray[splitSlashArray.length - 3] + "%7C" + splitSlashArray[splitSlashArray.length - 2];
23735        this.map = new SHC.ui.Map(function() {
23736            that.map.doLocationRequest(locationSubpath);
23737            that.setupThumbnails();
23738            that.bindTabClicks();
23739            that.setModalLinks();
23740            that.positionVertically();
23741        });
23742    },
23743
23744    setupThumbnails: function () {
23745        var bottomContentImages = $(".bottom-content-images").find("img");
23746        if (bottomContentImages.length > 1) {
23747            $(".bottom-content-images").show();
23748            $(".bottom-content").removeClass("wide");
23749        }
23750        // add event listeners to newly loaded images
23751        bottomContentImages.on("click", function (e) {
23752            var thumb       = $(this).attr("src");
23753            var title       = $(this).attr("title");
23754            var alt         = $(this).attr("alt");
23755            var src         = thumb.replace("locationthumbnail", "img");
23756            var mapDisplay  = $("#gmap");
23757            var imgDisplay  = $("#map-display-image");
23758
23759            $(this).addClass("active").siblings().removeClass("active");
23760            if (thumb === "/etc/clientlibs/shc/main/img/map-thumb.png") {
23761                mapDisplay.show();
23762                imgDisplay.hide();
23763            } else {
23764                if (imgDisplay.find("img").length < 1) {
23765                    imgDisplay.html("<img src=\"" + src + "\" alt=\"" + alt + "\" title=\"" + title + "\">").show();
23766                    mapDisplay.hide();
23767                } else {
23768                    if (alt.includes('Show ')) {
23769                        alt = alt.replace('Show ', '');
23770                    }
23771                    imgDisplay.find("img").attr("src", src).attr("title", title).attr("alt", alt).parent().show();
23772                    mapDisplay.hide();
23773                }
23774            }
23775            //that.clinicGmap.refresh();
23776        });
23777        bottomContentImages.on("keydown", function (e) {
23778          if (e.keyCode == 13) {
23779            $(this).click();
23780          }
23781        });
23782    },
23783    
23784    bindTabClicks: function() {
23785        var that = this;
23786        jQuery(".map-tab").off("tabclicks").on("click.tabclicks", function() {
23787            var tab = jQuery(this);
23788            jQuery(".map-tab").removeClass("active");
23789            tab.addClass("active");
23790            if(tab.hasClass("overview-tab")) {
23791                jQuery(".parking").hide();
23792                jQuery(".overview").show();
23793               that.map.hideValetMarkers();
23794                that.map.hideParkingMarkers();
23795                that.map.setBuildingBoundaries();
23796                //selected tab is overview tab - put overview tab back to tab order and set aria-selected=true, set tabindex=-1,aria-selected = false for parking tab to remove it from tab order,
23797                 $('#tab-overview').removeAttr('tabindex');
23798                jQuery("#tab-overview").attr("aria-selected", "true");
23799                jQuery("#tab-parking").attr("aria-selected", "false").attr("tabindex","-1");
23800            } else {
23801                jQuery(".parking").removeClass("hidden").show();
23802                jQuery(".overview").hide();
23803                that.map.showParkingMarkers();
23804                that.map.showValetMarkers();
23805                that.map.setAllBoundaries();
23806                //selected tab is parking tab - put parking tab to tab order and set aria-selected=true, set tabindex=-1,aria-selected = false for overview tab to remove it from tab order,
23807                jQuery("#tab-parking").attr("aria-selected", "true");
23808                $('#tab-parking').removeAttr('tabindex');
23809                jQuery("#tab-overview").attr("aria-selected", "false").attr("tabindex","-1");
23810            }
23811            var navHeight = $('#search-inpagenav-wrapper').height();
23812            $.scrollTo('.location-page',{"duration": 500, "offset": {top: -navHeight},"axis": "y" });
23813        });
23814        jQuery(".map-tab a").on('keydown', function (event) {
23815              switch(event.key) {
23816                    case 'Enter': $(this).click(); break;
23817                    case ' ': $(this).click(); break;
23818              case 'ArrowLeft':
23819                if (event.target.id == 'tab-overview') {
23820                    $('#tab-parking').removeAttr('tabindex');
23821                     $('#tab-parking').focus();
23822                } else {
23823                    $('#tab-overview').removeAttr('tabindex');
23824                    $('#tab-overview').focus();
23825                }
23826                break;
23827              case 'ArrowRight':
23828                if (event.target.id == 'tab-overview') {
23829                    $('#tab-parking').removeAttr('tabindex');
23830                     $('#tab-parking').focus();
23831                } else {
23832                    $('#tab-overview').removeAttr('tabindex');
23833                    $('#tab-overview').focus();
23834                }
23835                break;
23836              case 'Home': $('#tab-overview').removeAttr('tabindex'); $('#tab-overview').focus(); break;
23837              case 'End':  $('#tab-parking').removeAttr('tabindex'); $('#tab-parking').focus(); break;
23838              default: break;
23839              }
23840         });
23841    },
23842
23843    setModalLinks: function() {
23844        var l3Path = jQuery('.map-target').attr('data-l3-page');
23845        if (l3Path) {
23846            //TODO /content whatever
23847            jQuery('.clinic-details-link').attr('href', l3Path + '.html');
23848        }
23849        var originalL2Path = jQuery('meta[name="twitter:url"]').attr('content');
23850        var originalL2Title = jQuery('meta[name="twitter:title"]').attr('content');
23851        jQuery('.back-to-locations-link').append(originalL2Title + ' Locations');
23852        jQuery('#map-container .back-to-locations-link').attr('href', originalL2Path.replace('.html','.multimapmodal.html'));
23853
23854        //bind click behavior that changes the href of the back
23855        //links to open in multimap modal or page
23856        jQuery('body').off('click.back-to-locations-link').on('click.back-to-locations-link', '#map-container .back-to-locations-link', function (e) {
23857            e.preventDefault();
23858            var href = $(this).attr('href');
23859            var newHref = href.replace(".multimapmodal.", ".multi_clinic_map.");
23860            jQuery('#modal-content').load(newHref, function() {
23861                var slingResourcePath = $('.location-page.clinic-multi-clinic-map').attr('requestPath');
23862                var map;
23863                var splitSlashArray = slingResourcePath.split('/');
23864                var l2Name = splitSlashArray[splitSlashArray.length - 2];
23865                map = new SHC.ui.Map(function() {
23866                    map.doL3Request(l2Name);
23867                });
23868            });
23869        });
23870
23871        if(document.URL.indexOf('.mapmodal.') !== -1 || this.showLink){
23872           jQuery('.clinic-details-link').show();
23873        }
23874    },
23875    positionVertically: function() {
23876        $(window).scrollTo(SHC.ui.modalInstance.scrollPosition);
23877    }
23878});
23879SHC.Namespace(SHC, 'SHC.ui.Stanford.Now.Article');
23880SHC.ui.Stanford.Now.Article = new SHC.Class();
23881SHC.ui.Stanford.Now.Article.include({
23882    /*
23883     * constructor
23884     */
23885    init: function(parent) {
23886        this.parent = $(parent);
23887        if (this.isIE() !== 8) {
23888            this.activate();
23889        }
23890    },
23891    activate: function() {
23892        var _this = this;
23893
23894        jQuery('.video-js').each(function() {
23895            var myPlayer = videojs(this, {"techOrder": ["youtube"]});
23896        });
23897    },
23898    isIE: function() {
23899        var myNav = navigator.userAgent.toLowerCase();
23900        return (myNav.indexOf('msie') !== -1) ? parseInt(myNav.split('msie')[1]) : false;
23901    }
23902});
23903SHC.Namespace(SHC, 'SHC.ui.Stanford.Now.Tabs');
23904SHC.ui.Stanford.Now.Tabs = new SHC.Class();
23905
23906SHC.ui.Stanford.Now.Tabs.include({
23907    /*
23908     * constructor
23909     */
23910    init: function(parent) {
23911        this.parent = $(parent);
23912        this.getSuffix();
23913        this.activate();
23914        this.setActiveTab();
23915
23916        var startTab = location.hash.split('?')[0];
23917        $('a[href="' + startTab + '"]').click();
23918    },
23919    activate: function() {
23920        var _this = this,
23921                handleTabs = function(event) {
23922            event.preventDefault();
23923
23924            var $this = $(this);
23925            var tabLink = $this.attr('href');
23926            var isActive = $this.parent().hasClass('active');
23927            _this.tabToSetActive = $this;
23928
23929            if (tabLink === '#more') {
23930                $this.siblings('.search-nav-more-container').fadeToggle('fast');
23931                if ($this.parent().hasClass('active')) {
23932                    $this.parent().removeClass("active");
23933                }
23934            } else if (!isActive) {
23935                // pull channel from $this
23936                var channel = $this.attr('data-channel');
23937                // pull id of content div from $this
23938                var contentSelector = '#' + channel;
23939                _this.ajaxedContentSpace = contentSelector;
23940
23941                //check if item is in more list
23942                var isMoreItem = $this.closest('.search-nav-more-container').length > 0;
23943                //if more item
23944                if (isMoreItem) {
23945                    //put it directly after 'latest'
23946                    $('.stanford-now-tabs-nav').children().first().after($this.parent().removeClass("more"));
23947                    reorderTabs();
23948                }
23949
23950                // do query
23951                var url,
23952                    suffixIndex,
23953                    baseURL;
23954                if (channel) {
23955                    _this.startWaitState(contentSelector); //start spinner
23956                    _this.doQuery($this, channel, contentSelector);
23957                    if (history.pushState) {
23958                        url = document.URL.split("?")[0];
23959                        suffixIndex = url.lastIndexOf('.html/');
23960                        baseURL = document.URL.split("?")[0];
23961                        if (suffixIndex !== -1) {
23962                            baseURL = url.substr(0, suffixIndex + 5);
23963                        }
23964                        var newURL = baseURL + "?" + channel;
23965                        history.pushState('data', '', newURL);
23966                    }
23967                } else {
23968                    if (history.pushState) {
23969                        url = document.URL.split("?")[0];
23970                        suffixIndex = url.lastIndexOf('.html/');
23971                        baseURL = document.URL.split("?")[0];
23972                        if (suffixIndex !== -1) {
23973                            baseURL = url.substr(0, suffixIndex + 5);
23974                        }
23975                        history.pushState('data', '', baseURL);
23976                    }
23977                    var $tabContainer = $this.closest('.stanford-now-tabs-nav').siblings('.stanford-now-tabs-content-container');
23978                    tabLink = $this.attr('href');
23979                    $this.closest('.stanford-now-tabs-nav').find('.search-nav-more-container').fadeOut('fast');
23980                    $this.closest('.stanford-now-tabs-nav').not($('.search-nav-more-container')).find('.active').removeClass('active');
23981                    $tabContainer.find('.stanford-now-tabs-content').not(tabLink).fadeOut('fast');
23982                    $tabContainer.find(tabLink).fadeIn('fast');
23983                }
23984            }
23985            if (tabLink !== '#more') {
23986                $this.parent().addClass('active');
23987            }
23988            _this.endWaitState(); //hide spinner
23989            _this.setActiveTab();
23990        };
23991
23992        var reorderTabs = function() {
23993            var windowSize = SHC.ui.screenMode;
23994            var tabs = $('.stanford-now-tabs-nav');
23995            var moreTabs = tabs.find('.search-nav-more-container');
23996
23997            //move all channels out of more section and remove 'more' class
23998            tabs.children().last().before(moreTabs.children().not(".arrow").removeClass("more"));
23999
24000            //put them back in as needed
24001            //mobile
24002            var lastTab;
24003            if (windowSize === 'small') {
24004                while (tabs.children().length > 3) {
24005                    lastTab = tabs.children().last().prev();
24006                    lastTab.addClass("more");
24007                    moreTabs.prepend(lastTab);
24008                }
24009            }
24010            //tablet
24011            else if (windowSize === 'medium') {
24012                while (tabs.children().length > 5) {
24013                    lastTab = tabs.children().last().prev();
24014                    lastTab.addClass("more");
24015                    moreTabs.prepend(lastTab);
24016                }
24017            }
24018            //desktop
24019            else {
24020                while (tabs.children().length > 6) {
24021                    lastTab = tabs.children().last().prev();
24022                    lastTab.addClass("more");
24023                    moreTabs.prepend(lastTab);
24024                }
24025            }
24026
24027            if (moreTabs.children().not('.arrow').length < 1) {
24028                moreTabs.parent().hide();
24029            } else {
24030                moreTabs.parent().show();
24031            }
24032        };
24033        var handleChannelLinks = function(event) {
24034            event.preventDefault();
24035            var $this = jQuery(this);
24036            var channelName = $this.attr('data-channel-name');
24037            jQuery('*[data-channel="' + channelName + '"]')[0].click();
24038        };
24039        _this.parent.each(function() {
24040            var $this = $(this);
24041            $this.find('ul').on('click', 'a', handleTabs);
24042        });
24043
24044        _this.parent.find('.stanford-now-tabs-content .channel-link').each(function() {
24045            jQuery(this).on('click', handleChannelLinks);
24046        });
24047        $(window).on('resizeEnd', reorderTabs);
24048        $('.stanford-now-tabs-nav').children().first().after(_this.activeTab);
24049        reorderTabs();
24050    },
24051    doQuery: function($this, channel, contentSelector) {
24052        var that = this;
24053        var _this = this;
24054        var isValleycare = document.location.pathname.indexOf("tri-valley") > 0 ? true : false;
24055        var urlString = "/bin/api/v1/content/articles.json/" + channel + ".json";
24056        if(isValleycare) { // add a selector to separate the request for valleycare so it does not use the cached response
24057            urlString = "/bin/api/v1/content/articles.valleycare.json/" + channel + ".json";
24058        }
24059        var request = jQuery.ajax({
24060            url: urlString,
24061            async: true,
24062            contentType: "application/json"
24063        }).done(function(data) {
24064            var $tabContainer = $this.closest('.stanford-now-tabs-nav').siblings('.stanford-now-tabs-content-container'),
24065                    tabLink = $this.attr('href');
24066            _this.loadTemplate(contentSelector, data, JST["handlebars/article-handlebars.hbs"]);
24067            $this.closest('.stanford-now-tabs-nav').find('.search-nav-more-container').fadeOut('fast');
24068            $this.closest('.stanford-now-tabs-nav').not($('.search-nav-more-container')).find('.active').removeClass('active');
24069            $tabContainer.find('.stanford-now-tabs-content').not(tabLink).fadeOut('fast');
24070            $tabContainer.find(tabLink).fadeIn('fast');
24071            // reinitialize presentation mode
24072            var presentationModeItems = $tabContainer.find(tabLink).find('.presentation');
24073            var presentationMode = new SHC.ui.PresentationMode(presentationModeItems, false);
24074            that.setActiveTab();
24075        }).fail(function(xhr, status, error) {
24076            console.log("listing results error:", xhr, status, error);
24077        });
24078    },
24079    loadTemplate: function(targetSelector, incomingData, template) {
24080        jQuery(targetSelector).html(template(incomingData));
24081    },
24082    getSuffix: function() {
24083        var _this = this;
24084        var url = document.URL;
24085        var urlQueryParams = url.split("?");
24086        var channelSelector = "";
24087        if(urlQueryParams.length > 1){
24088            var queryParams = urlQueryParams[1].split("&");
24089            for(var i=0; i < queryParams.length; i ++){
24090                if(queryParams[i].indexOf("=") === -1){
24091                    channelSelector = queryParams[i]
24092                }
24093            }
24094        }
24095        var suffixIndex = url.lastIndexOf('.html?');
24096        if (suffixIndex !== -1 && url.indexOf("presentation-mode") === -1 && channelSelector !== "") {
24097            var contentSelector = "#" + channelSelector;
24098            var $this = jQuery('*[data-channel="' + channelSelector + '"]');
24099            _this.doQuery($this, channelSelector, contentSelector);
24100            $this.parent().addClass('active');
24101            _this.activeTab = $this.parent(); //used to move active tab next to 'latest'
24102            _this.tabToSetActive = $this;
24103        } else {
24104            _this.tabToSetActive = jQuery("#latest");
24105        }
24106    },
24107    setActiveTab: function() {
24108        var that = this;
24109        that.tabToSetActive.parent().addClass('active');
24110    },
24111    startWaitState: function() {
24112        var that = this;
24113        jQuery("body").css("cursor", "wait");
24114        jQuery(".stanford-now-tabs-content").fadeOut('fast');
24115        var spinner;
24116        if (window.requestAnimationFrame) {
24117            spinner = '<div class="spinner-container">' +
24118                '<div class="floatingBarsG">' +
24119                '<div class="blockG rotateG_01"></div>' +
24120                '<div class="blockG rotateG_02"></div>' +
24121                '<div class="blockG rotateG_03"></div>' +
24122                '<div class="blockG rotateG_04"></div>' +
24123                '<div class="blockG rotateG_05"></div>' +
24124                '<div class="blockG rotateG_06"></div>' +
24125                '<div class="blockG rotateG_07"></div>' +
24126                '<div class="blockG rotateG_08"></div>' +
24127                '</div>' +
24128                '</div>';
24129            jQuery(that.ajaxedContentSpace).html(spinner).fadeIn('fast');
24130        } else {
24131            spinner = '<div class="spinner-container-ie9">' +
24132                '<div class="floatingBarsG">' +
24133                '<div class="blockG" id="rotateG_01"></div>' +
24134                '<div class="blockG" id="rotateG_02"></div>' +
24135                '<div class="blockG" id="rotateG_03"></div>' +
24136                '<div class="blockG" id="rotateG_04"></div>' +
24137                '<div class="blockG" id="rotateG_05"></div>' +
24138                '<div class="blockG" id="rotateG_06"></div>' +
24139                '<div class="blockG" id="rotateG_07"></div>' +
24140                '<div class="blockG" id="rotateG_08"></div>' +
24141                '</div>' +
24142                '</div>';
24143            jQuery(that.ajaxedContentSpace).html(spinner).fadeIn('fast', function(){
24144                $('.spinner-container-ie9').simpleSpinner();
24145            });
24146        }
24147
24148    },
24149    endWaitState: function() {
24150        jQuery("body").css("cursor", "default");
24151    }
24152});
24153
24154SHC.Namespace(SHC, "SHC.ui.Listing.Results");
24155SHC.ui.Listing.Results = new SHC.Class();
24156
24157SHC.ui.Listing.Results.include({
24158    init: function (parent) {
24159        this.parent = $(parent);
24160
24161        this.paginationString = "";
24162        this.pagePath = document.URL;
24163    },
24164
24165    activate: function() {
24166        var _this = this;
24167        _this.filterToggle = _this.parent.find(".filter-toggle");
24168        _this.filter = _this.parent.find(".filter");
24169        _this.dropdowns = _this.filter.find(".dropdown");
24170        _this.toggles = _this.filter.find(".toggle");
24171        _this.animateSpeed = 250;
24172
24173        var handleFilterToggle = function (e) {
24174            _this.filterToggle.toggleClass("open");
24175            _this.filter.slideToggle(_this.animateSpeed);
24176        };
24177
24178        // event: handle dropdown toggles
24179        var handleDropdownToggle = function (e) {
24180            e.preventDefault();
24181
24182            var clicked = $(this);
24183            var openToggles = _this.filter.find(".toggle.open").not(this);
24184
24185            if (openToggles.length > 0) {
24186                // close currently open dropdowns
24187                openToggles.removeClass("open").siblings("ul").slideUp(_this.animateSpeed, function () {
24188
24189                    // on complete, open/close this dropdown
24190                    clicked.toggleClass("open").siblings("ul").slideToggle(_this.animateSpeed);
24191                });
24192            } else {
24193                // open/close this dropdown
24194                clicked.toggleClass("open").siblings("ul").slideToggle(_this.animateSpeed);
24195            }
24196        };
24197
24198        // event: handle filter item selection
24199        var handleItemClick = function (e) {
24200            e.preventDefault();
24201
24202            // setup active classes
24203            var text = $(this).text();
24204            $(this).addClass("active").parent().siblings().find("a").removeClass("active").closest(".dropdown").find(".text").addClass("active").text(text);
24205
24206            // close open dropdowns
24207            _this.dropdowns.find(".toggle.open").removeClass("open").siblings("ul").slideUp(_this.animateSpeed);
24208            var Q = _this.buildQ();
24209            _this.filterSearch(Q);
24210        };
24211
24212        // setup event listeners
24213        _this.filterToggle.find("a").on("click", handleFilterToggle);
24214        _this.toggles.on("click", handleDropdownToggle);
24215        _this.dropdowns.find("ul li a").on("click", handleItemClick);
24216    },
24217
24218    renderFilters: function (data) {
24219        if (jQuery('#filter-target').children().length === 0) {
24220            this.loadTemplate('#filter-target', data, JST["handlebars/listing-filters-template.hbs"]);
24221            this.activate();
24222        }
24223    },
24224
24225    /**
24226     * Fixes up the query term and sends it to getJSON
24227     * This is for a search that wipes the page and does not do filters or pagination
24228     */
24229    startSearch: function (doer, onSuccessCallback) {
24230        var that = this;
24231        var Q = "?do=" + doer;
24232        var type;
24233        var pagePath = document.URL;
24234        type = "&x10=sp_type&q10=" + encodeURIComponent(jQuery('#listing-page').attr('data-sp-type'));
24235        Q = Q + type;
24236        // doesn't actually return JSON, just fetches it from S&P
24237        that.getJSON(doer, Q, false, onSuccessCallback);
24238    },
24239
24240    /**
24241     * A search that appends results to the page. The Q is the query string from S&P
24242     */
24243    paginate: function (Q) {
24244        //get doer from Q
24245        if (Q) {
24246            var firstSplit = Q.split("do=");
24247            var secondSplit = firstSplit[1].split(";");
24248            var doer = secondSplit[0];
24249            this.getJSON(doer, Q, true);
24250        }
24251    },
24252
24253    /**
24254     * A search that wipes the page, but stays on the same tab. The Q comes from S&P
24255     */
24256    filterSearch: function (Q) {
24257        //get doer from Q
24258        if (Q) {
24259            var firstSplit = Q.split("do=");
24260            var secondSplit = firstSplit[1].split("&");
24261            var doer = secondSplit[0];
24262            this.getJSON(doer, Q, false);
24263        }
24264    },
24265
24266    // doesn't return JSON, just fetches it from S&P, does search stuff and runs the callback if it has one
24267    getJSON: function (doer, Q, isPaginating, onSuccessCallback) {
24268        jQuery('.view-more-results-btn').hide();
24269        var that = this;
24270        Q += "&sp_c=6";
24271        var searchVer = document.querySelector(metaName).content || "v1";
24272        var urlRaw = "/bin/api/"+searchVer+"/search.json" + Q;
24273        var url = urlRaw.replace(";", "&");
24274        that.startWaitState(isPaginating);
24275        var request = jQuery.ajax({
24276            url: url,
24277            dataType: "jsonp",
24278            jsonp: 'callback',
24279            contentType: "application/json",
24280            success: function (data) {
24281                that.endWaitState();
24282                if (!data) {
24283                    return null;
24284                }
24285                if (!isPaginating) {
24286                    jQuery("#handlebars-target").empty();
24287                }
24288                that.renderFilters(data);
24289                that.parseListing(data, isPaginating);
24290
24291                // Pass the data back to interested listeners.
24292                if (onSuccessCallback &&
24293                    typeof onSuccessCallback === 'function') {
24294                    onSuccessCallback(data);
24295                }
24296
24297                // Suppress display of PresentationMode when paginating.
24298                var presentationMode = null;
24299                if (isPaginating) {
24300                    presentationMode = new SHC.ui.PresentationMode(".presentation", false, true);
24301                } else {
24302                    presentationMode = new SHC.ui.PresentationMode(".presentation", false);
24303                }
24304            },
24305            error: function (xhr, status, error) {
24306                console.log("listing results error:", xhr, status, error);
24307                that.endWaitState();
24308            }
24309
24310        });
24311    },
24312
24313    /**
24314     * The click for the view more button on the filter pages
24315     */
24316    bindViewMoreClick: function () {
24317        var that = this;
24318        jQuery(".view-more-results-btn")
24319            .off().show()
24320            .on("click", function (e) {
24321                e.preventDefault();
24322                SHC.util.setCookie('activeView', SHC.ui.Search.DirectoryUtil.getSelectedView(), 1, '/');
24323                that.paginate(that.paginationString);
24324            });
24325
24326        if(SHC.util.isIE()) {
24327            jQuery(window).trigger('resize');
24328        }
24329    },
24330
24331    parseListing: function (data, isPaginating) {
24332        var that = this;
24333        if (isPaginating) {
24334            this.loadTemplate("#listing-target", data, JST["handlebars/listing-paginating-template.hbs"]);
24335        } else {
24336            if (this.pagePath.indexOf("press") !== -1) {
24337                this.loadTemplate("#listing-target", data, JST["handlebars/listing-template.hbs"]);
24338            } else {
24339                this.loadTemplate("#listing-target", data, JST["handlebars/media-listing-template.hbs"]);
24340            }
24341        }
24342        //update paginationString
24343        that.paginationString = data['pagination']['next'];
24344        if (that.paginationString !== "") {
24345            that.bindViewMoreClick();
24346        }
24347    },
24348
24349    /*
24350     * Compiles and appends handlebar templates to the search results area
24351     */
24352    loadTemplate: function (targetSelector, incomingdata, template) {
24353        jQuery(targetSelector).append(template(incomingdata));
24354    },
24355
24356    buildQ: function() {
24357        var activeTopic = this.dropdowns.parent().find('#topics-filter a.active').text();
24358        var activeCondition = this.dropdowns.parent().find('#conditions-filter a.active').text();
24359        var activeDate = this.dropdowns.parent().find('#date-filter a.active').text();
24360        var type;
24361        if (this.pagePath.indexOf("press") !== -1) { // is press release
24362            type = "&x10=sp_type&q10=press_release";
24363        } else {
24364            type = "&x10=sp_type&q10=more_media";
24365        }
24366        var Q = "?do=organic_newsroom" + type;
24367        if (activeTopic !== "" && activeTopic !== "All Topics") {
24368            Q += "&x11=sp_topics&q11=" + encodeURIComponent(encodeURIComponent(activeTopic).replace(/\%20/g, '+'));
24369        }
24370        if (activeCondition !== "" && activeCondition !== "All Conditions") {
24371            Q += "&x12=sp_category&q12=" + activeCondition;
24372        }
24373        if (activeDate !== "" && activeDate !== "All Dates") {
24374            Q += "&x13=sp_date&q13=" + activeDate;
24375        }
24376        return Q;
24377    },
24378
24379    startWaitState: function (isPaginating) {
24380        jQuery("body").css("cursor", "wait");
24381        jQuery("#spinner-container").show();
24382        if (!isPaginating) {
24383            jQuery("#listing-target").empty();
24384        }
24385    },
24386
24387    endWaitState: function () {
24388        jQuery("body").css("cursor", "default");
24389        jQuery("#spinner-container").hide();
24390    }
24391});
24392SHC.Namespace(SHC, "SHC.ui.PhyscianProfile");
24393SHC.ui.PhyscianProfile = new SHC.Class();
24394SHC.ui.PhyscianProfile.include({
24395    /**
24396     * constructor
24397     * @param parent
24398     */
24399     init: function(parent) {
24400        this.parent = parent;
24401        this.setupReadMore();
24402        this.$drProfile = jQuery('.doctor-profile');
24403        this.$drWhyVideoLink = jQuery('.inline-video').find('.dr-why-link');
24404        this.$drPicture = this.$drProfile.find('.thumb');
24405        this.$drVitals = this.$drProfile.find('.vitals');
24406        this.$drBio = this.$drProfile.find('#biography');
24407        this.$readMoreButton = this.$drProfile.find('#read-more');
24408        this.$closeButton = jQuery('.inline-video').find('.close-button.physician-page');
24409        this.readMoreShouldStillBeVisible = false;
24410        // this.setupReadMorePublications();
24411        this.setupReadMoreComments();
24412        this.locations = $('#overview').find('.location');
24413        this.setupLocations();
24414        this.hideLifeConnectionLocation();
24415        this.displayRatingSummary();
24416        this.setupTabs();
24417        this.setupViewAll("#viewAllPracticeAreas", ".conditions");
24418        this.setupViewAll("#viewAllSpecialInterests", ".special-interests");
24419        this.setupViewAllProfessionalEducation();
24420        this.setupViewAllHonorsAndAwards();
24421        this.setupViewAllCommunityInternationalWork();
24422        this.setupViewAllAdministrativeAppointments();
24423        this.setupViewAllPublications();
24424        this.setupInlineVideoClicks();
24425        this.spacingForLastSection();
24426        this.scrollTo();
24427     },
24428
24429    hideLifeConnectionLocation: function() {
24430        var queryParam = window.location.search,
24431            queryValue = queryParam.replace('?', '').split('=')[1];
24432        if (queryValue !== 'cisco') {
24433            // hide any life connections locations
24434            jQuery("h4:contains('LifeConnections')").parents('.location').hide();
24435        }
24436        jQuery('.location-wrapper').removeClass('start-hidden');
24437    },
24438
24439     setupReadMore: function() {
24440        var readMoreLink = $(this.parent),
24441            bio = $('#biography'),
24442            readMoreContainer = $('#read-more'),
24443            bioContainerHeight = parseInt($("#biography-container").outerHeight(), 10);
24444
24445        // if bio is short enough hide read more link.
24446        if ( bioContainerHeight < 200 ) {
24447            readMoreContainer.hide();
24448            bio.css({height: 'auto'});
24449        } else {
24450            readMoreLink.on('click', function(event){
24451                event.preventDefault();
24452                var link = $(this),
24453                    bio = $('#biography'),
24454                    bioHeight = parseInt($("#biography-container").outerHeight(), 10);
24455                link.hide();
24456                bio.animate({
24457                    height: bioHeight
24458                }, 400, function() {
24459                    bio.css({height: 'auto'});
24460                });
24461            });
24462        }
24463     },
24464
24465     setupInlineVideoClicks: function(){
24466        var that = this;
24467        var openComponentLinkPhysicianPage = function(e) {
24468            e.preventDefault();
24469            // hide other stuff in doctor-profile to show video
24470            that.$drPicture.hide();
24471            that.$drVitals.hide();
24472            that.$drBio.hide();
24473            if(that.$readMoreButton.is(':visible')){
24474                that.$readMoreButton.hide();
24475                that.readMoreShouldStillBeVisible = true;
24476            } else {
24477                that.readMoreShouldStillBeVisible = false;
24478            }
24479            that.$drProfile.addClass('video-open');
24480            that.$drProfile.find('.video-row').addClass('video-open');
24481        };
24482        var closeComponentPhysicianPage = function(e) {
24483            e.preventDefault();
24484            // show other stuff in doctor-profile after hiding video
24485            that.$drPicture.show();
24486            that.$drVitals.show();
24487            that.$drBio.show();
24488            if (that.readMoreShouldStillBeVisible) {
24489                that.$readMoreButton.show();
24490            }
24491            that.$drProfile.removeClass('video-open');
24492            that.$drProfile.find('.video-row').addClass('video-open');
24493        };
24494        that.$drWhyVideoLink.on('click.inline-video', openComponentLinkPhysicianPage);
24495        that.$closeButton.on('click.inline-video', closeComponentPhysicianPage);
24496     },
24497
24498    setupReadMoreComments: function() {
24499        var comment = $('#comments'),
24500            readMoreComments = $('#read-more-comments'),
24501            remainder = $(".remaining-comments");
24502            remainder.hide();
24503            readMoreComments.on('click', function (event) {
24504            event.preventDefault();
24505            var link = $(this);
24506            link.hide();
24507            remainder.show({
24508                "duration": 400
24509            });
24510        });
24511    },
24512     setupLocations: function() {
24513
24514        var that = this,
24515            locations = that.locations;
24516
24517        locations.each(function(){
24518            var location = $(this),
24519                handle = location.find('.handle a'),
24520                gmapthumbnail = location.find('.details img.map-location');
24521
24522                if (location.hasClass('open')) {
24523                  gmapthumbnail.attr('src', gmapthumbnail.attr('data-src'));
24524                }
24525
24526                handle.on('click', function(event) {
24527                event.preventDefault();
24528                var _this = $(this),
24529                    location = _this.closest('.location'),
24530                    details = location.find('.details');
24531
24532                if ( location.hasClass('open') ) {
24533                    details.slideUp(300, function(){
24534                        location.removeClass('open');
24535                    });
24536                } else {
24537                    locations.filter('.open').find('.details').slide
24537Up(300, function(){
24538                        $(this).closest('.location').removeClass('open');
24539                    });
24540                    details.slideDown(300, function(){
24541                        gmapthumbnail.attr('src', gmapthumbnail.attr('data-src'));
24542                        location.addClass('open');
24543                    });
24544                }
24545            });
24546        });
24547        if (locations.length && locations.length < 2) {
24548            jQuery(".location .toggle").hide();
24549        }
24550     },
24551    displayRatingSummary:function(){
24552        if($('.numericRatings').attr('value')){
24553            var rating = parseFloat($('.numericRatings').attr('value'));
24554            var width = ((parseFloat(rating)/5)*100) +'%';
24555            $('.press_ganey_ratings').find('.rating_bar_big').find('div').css('width', width);
24556            $('.press_ganey_ratings').find('.rating_bar').find('div').css('width', width);
24557        }else{
24558            $('.press_ganey_ratings').find('.rating_bar_big').find('div').css('width', '0%');
24559            $('.press_ganey_ratings').find('.rating_bar').find('div').css('width', '0%');
24560        }
24561        $('.goto-rating').on('click tap',function(){
24562            $('[class*=dr-profile-content-]').css('position','absolute')
24563                                             .css('top','-200000px')
24564                                             .css('left','-200000px');
24565            $('.profile-content-tabs .active').removeClass('active');
24566            $('.profile-content-tabs .reviews-tab').addClass('active');
24567            $('.dr-profile-content-reviews').css('position','relative')
24568                                            .css('top','0')
24569                                            .css('left','auto');
24570            window.location.hash = 'reviews-content';
24571
24572            var tab = $('.reviews-tab');
24573
24574            if (SHC.ui.screenMode !== 'small') {
24575                $.scrollTo(tab[0],0,{axis:'y', offset: {top: -125, left: 0}});
24576            } else {
24577                $.scrollTo(tab[1],0,{axis:'y', offset: {top: -30, left: 0}});
24578            }
24579        });
24580        $('.goto-comment').on('click tap',function(){
24581            $('[class*=dr-profile-content-]').css('position','absolute')
24582                                             .css('top','-200000px')
24583                                             .css('left','-200000px');
24584            $('.profile-content-tabs .active').removeClass('active');
24585            $('.profile-content-tabs .reviews-tab').addClass('active');
24586            $('.dr-profile-content-reviews').css('position','relative')
24587                                            .css('top','0')
24588                                            .css('left','auto');
24589            window.location.hash = 'reviews-content';
24590            $.scrollTo('#comments-new',300,{axis:'y',offset: {top: 0, left:0}});
24591        });
24592
24593
24594
24595    },
24596    setupTabs: function(){
24597
24598        var tabs_container = $('.profile-content-tabs'),
24599            tabs = tabs_container.children('[class*=-tab]'),
24600            tabs_names = [],
24601            match_exp = /([A-Za-z]+-){1,}/,
24602            trinary_exp = /[^A-Za-z\-]/g,
24603            hash = ((window.location.hash.substr(1) === false) ||
24604                    (Array.isArray(window.location.hash.substr(1).match(trinary_exp)))) ? 'summary' : window.location.hash.substr(1);
24605            tab_state = '';
24606
24607        if (tabs.filter(':visible').length > 0) {
24608            tabs.filter(':hidden').css('display','inline-block');
24609        } else {
24610            tabs_container.hide();
24611            $('.dr-profile-content-summary').show()
24612                                            .css('margin-top','23px');
24613        }
24614
24615        if ($('.profile-content-tabs li:visible').length === 0) {
24616            $('.profile-content-tabs').remove();
24617            $('#overview.doctor_profile_container').addClass('no-tabs');
24618        }
24619
24620        tabs.each(function(){
24621            var attr = $(this).attr("class").match(match_exp)[0];
24622
24623            tabs_names.push(attr.substr(0,(attr.length-1)));
24624        });
24625
24626        hash = hash.replace('-content','');
24627
24628        if ($.inArray(hash,tabs_names) !== -1) {
24629
24630            $('[class*=dr-profile-content-]').css('position','absolute')
24631                                             .css('top','-200000px')
24632                                             .css('left','-200000px');
24633            $('.profile-content-tabs .active').removeClass('active');
24634            $('.profile-content-tabs .'+hash+'-tab').addClass('active');
24635            $('.dr-profile-content-'+hash).css('position','relative')
24636                                          .css('top','0')
24637                                          .css('left','auto');
24638        } else {
24639
24640            $('[class*=dr-profile-content-]').css('position','absolute')
24641                                             .css('top','-200000px')
24642                                             .css('left','-200000px');
24643            $('.profile-content-tabs .active').removeClass('active');
24644            $('.profile-content-tabs .summary-tab').addClass('active');
24645            $('.dr-profile-content-summary').css('position','relative')
24646                                          .css('top','0')
24647                                          .css('left','auto');
24648        }
24649
24650        tabs.each(function(){
24651            $(this).on('click tap',function(){
24652
24653                tabs.removeClass('active');
24654                $(this).addClass('active');
24655                $('[class*=dr-profile-content-]').css('position','absolute')
24656                                                 .css('top','-200000px')
24657                                                 .css('left','-200000px');
24658                $('.dr-profile-content-'+$(this).attr('class').match(match_exp)[0].replace(/-$/,'')).css('position','relative')
24659                                                                                                    .css('top','0')
24660                                                                                                    .css('left','auto');
24661            });
24662        });
24663
24664        $('.quick-nav-bar a').each(function() {
24665            $(this).on('click tap',function() {
24666                var tabdata = $(this).attr('data-tabname').replace('-content',''),
24667                    le_tab = $('.'+tabdata+'-tab');
24668                 $('.profile-content-tabs li.' + tabdata + '-tab a').click();
24669                 $.scrollTo(le_tab[1],300,{axis:'y',offset:{top: -50, left: 0}});
24670            });
24671        });
24672        $(window).on('resizeEnd', function(){
24673            if(jQuery('.profile-content-tabs .active').length > 0){
24674                var tab_state = $('.profile-content-tabs .active').attr('class').match(match_exp)[0];
24675
24676                $('.profile-content-tabs .active').removeClass('active');
24677                $('.profile-content-tabs .'+tab_state+'tab').addClass('active');
24678            }
24679        });
24680
24681    },
24682    setupViewAll: function(viewAllSelector, listSelector){
24683
24684        var conditions_div = $('.link_list ' + listSelector),
24685            list_items_parent = $('.link_list ' + listSelector + ' ul'),
24686            list_items = list_items_parent.find('li'),
24687            list_items_count = list_items.length,
24688            view_all_practice_areas = $(viewAllSelector),
24689            view_all_text = view_all_practice_areas.children('a').text(),
24690            list_items_hidden = [],
24691            hash = window.location.hash.substr(1);
24692
24693        if (list_items_count > 4) {
24694            var a_len = '';
24695            list_items_parent.each(function(){
24696                if ($(this).find('div').length === 0){
24697                    list_items_hidden.push($(this).find('li:nth-child(n+3)').detach());
24698                    a_len = list_items_hidden.length;
24699                    $(this).append($('<div></div>'));
24700                    $($(this).find('div')).append(list_items_hidden[a_len-1]);
24701                    $(this).find('div li:first-child').css('margin-top','0');
24702                }
24703                if (hash !== 'summary-practices') {
24704                    $(this).find('div').hide();
24705                } else {
24706                    view_all_practice_areas.children('a').text('Show Less');
24707                }
24708            });
24709        } else {
24710            view_all_practice_areas.hide();
24711            $('.dr-profile-content-summary .link_list').addClass('no-view-all-practices');
24712        }
24713
24714        conditions_div.show();
24715
24716        view_all_practice_areas.children('a').off('click.viewall').on('click.viewall', function(e){
24717            e.preventDefault();
24718
24719            list_items_parent.find('div').slideToggle();
24720            // list_items_parent.find('li:nth-child(n+3)').slideToggle();
24721
24722            if ($(this).text() === view_all_text) {
24723                $(this).text('Show Less');
24724            } else {
24725                $(this).text(view_all_text);
24726            }
24727
24728        });
24729
24730    },
24731    setupViewAllProfessionalEducation: function(){
24732
24733        var list = $('#professional_education_list'),
24734            list_items = list.children('li'),
24735            list_items_count = list_items.length,
24736            view_all_professional_education = $('#viewAllProfessionalEducation'),
24737            view_all_text = view_all_professional_education.children('a').text(),
24738            list_items_hidden = [];
24739
24740        if (list_items_count > 3) {
24741            list_items_hidden = list.children('li:nth-child(n+4)').detach();
24742            list.append($('<div></div>'));
24743            list.find('div').append(list_items_hidden);
24744            list.find('div li:first-child').css('margin-top','0');
24745            list.find('div').hide();
24746        } else {
24747            view_all_professional_education.hide();
24748            list.addClass('no-view-all');
24749        }
24750
24751        view_all_professional_education.children('a').click(function(e){
24752            e.preventDefault();
24753
24754            list.find('div').slideToggle();
24755
24756            if ($(this).text() === view_all_text) {
24757                $(this).text('Show Less');
24758            } else {
24759                $(this).text(view_all_text);
24760            }
24761        });
24762    },
24763    setupViewAllHonorsAndAwards: function(){
24764
24765        var list = $('#honors_and_awards_list'),
24766            list_items = $('#honors_and_awards_list').children('li'),
24767            view_all_honors_and_awards = $('#viewAllHonorsAndAwards'),
24768            view_all_text = view_all_honors_and_awards.children('a').text(),
24769            list_items_hidden = [];
24770
24771        if (list_items.length > 3) {
24772            // list.children('li:nth-child(n+4)').hide();
24773            list_items_hidden = list.children('li:nth-child(n+4)').detach();
24774            list.append('<div></div>');
24775            list.find('div').append(list_items_hidden);
24776            list.find('div li:first-child').css('margin-top','0');
24777            list.find('div').hide();
24778        } else {
24779            view_all_honors_and_awards.hide();
24780                    list.addClass('no-view-all');
24781        }
24782
24783        view_all_honors_and_awards.children('a').click(function(e){
24784            e.preventDefault();
24785
24786            list.find('div').slideToggle();
24787
24788            if ($(this).text() === view_all_text) {
24789                $(this).text('Show Less');
24790            } else {
24791                $(this).text(view_all_text);
24792            }
24793        });
24794    },
24795    setupViewAllCommunityInternationalWork: function(){
24796        var list = $('#dr-profile-community-international-work-list'),
24797            list_items = list.children('li'),
24798            view_all_community_international_work = $('#viewAllCommunityInternationalWork'),
24799            view_all_text = view_all_community_international_work.children('a').text(),
24800            list_items_hidden = [];
24801
24802        if (list_items.length > 3) {
24803            list_items_hidden = list.children('li:nth-child(n+4)').detach();
24804            list.append('<div></div>');
24805            list.find('div').append(list_items_hidden);
24806            list.find('div li:first-child').css('margin-top','0');
24807            list.find('div').hide();
24808        } else {
24809            view_all_community_international_work.hide();
24810            list.addClass('no-view-all');
24811        }
24812
24813        view_all_community_international_work.children('a').click(function(e){
24814            e.preventDefault();
24815
24816            list.find('div').slideToggle();
24817
24818            if ($(this).text() === view_all_text){
24819                $(this).text('Show Less');
24820            } else {
24821                $(this).text(view_all_text);
24822            }
24823
24824        });
24825    },
24826    setupViewAllAdministrativeAppointments: function(){
24827        var list = $('#dr-profile-administrative-appointments-list'),
24828            list_items = list.children('li'),
24829            view_all_administrative_appointments = $('#viewAllAdministrativeAppointments'),
24830            view_all_text = view_all_administrative_appointments.children('a').text(),
24831            list_items_hidden = [];
24832
24833        if (list_items.length > 3) {
24834            list_items_hidden = list.children('li:nth-child(n+4)').detach();
24835            list.append('<div></div>');
24836            list.find('div').append(list_items_hidden);
24837            list.find('div li:first-child').css('margin-top','0');
24838            list.find('div').hide();
24839        } else {
24840            view_all_administrative_appointments.hide();
24841            list.addClass('no-view-all');
24842        }
24843
24844        view_all_administrative_appointments.children('a').click(function(e){
24845            e.preventDefault();
24846
24847            list.find('div').slideToggle();
24848
24849            if ($(this).text() === view_all_text){
24850                $(this).text('Show Less');
24851            } else {
24852                $(this).text(view_all_text);
24853            }
24854
24855        });
24856    },
24857    setupViewAllPublications: function() {
24858        var list = $('#dr-profile-publications-list'),
24859            list_items = list.children('li'),
24860            view_all_publications = $('#viewAllPublications'),
24861            view_all_text = view_all_publications.children('a').text(),
24862            list_items_hidden = [];
24863
24864        if (list_items.length > 3) {
24865            // list.children('li:nth-child(n+4)').hide();
24866            list_items_hidden = list.children('li:nth-child(n+4)').detach();
24867            list.append('<div></div>');
24868            list.find('div').append(list_items_hidden);
24869            // list.find('div li:first-child').css('margin-top','0');
24870            list.find('div').hide();
24871        } else {
24872            view_all_publications.hide();
24873            list.addClass('no-view-all');
24874        }
24875
24876        view_all_publications.children('a').click(function(e){
24877            e.preventDefault();
24878
24879            list.find('div').slideToggle();
24880
24881            if ($(this).text() === view_all_text){
24882                $(this).text('Show Less');
24883            } else {
24884                $(this).text(view_all_text);
24885            }
24886        });
24887    },
24888    spacingForLastSection: function(){
24889        var lastSection = jQuery('.dr-profile-content-summary .summary-section').last();
24890        //if the last section does not have view all button/hr then change the spacing
24891        if(lastSection.find('hr').length === 0){
24892            lastSection.addClass('last-summary-section');
24893        }
24894
24895    },
24896
24897    scrollTo: function(){
24898        var navHeight = $('#search-inpagenav-wrapper').height();
24899        if(window.location.hash === '#summary' ||window.location.hash === '#summary-content' ||window.location.hash === '#summary-practices' ||window.location.hash === '#reviews-content'){
24900            setTimeout(function(){
24901
24902                $.scrollTo($('.profile-content-tabs'),{
24903                    "duration": 300,
24904                    "axis": "y",
24905                    "offset": {top: -navHeight}
24906                });
24907
24908            }, 2000);
24909        }
24910    }
24911});
24912
24913SHC.Namespace(SHC, "SHC.ui.ProfileTile");
24914SHC.ui.ProfileTile = new SHC.Class(SHC.ui.Tile);
24915
24916// JS lookup table of failed image request for ProfileTiles.
24917SHC.ui.ProfileTile.FAILED_IMAGES = {};
24918
24919SHC.ui.ProfileTile.include({
24920    /**
24921     *
24922     * @param parent
24923     * @param elementAttributes
24924     * @returns {*}
24925     */
24926    init: function (parent, elementAttributes) {
24927        "use strict";
24928
24929        this.fallbackImage = "/etc/clientlibs/shc/main/img/shc-logo-profiledeck.jpg";
24930        this.svgLogo = "/etc/clientlibs/shc/main/svg/shc-logo-profiledeck.svg";
24931        this.vignette = "/etc/clientlibs/shc/main/img/vignette.png";
24932        this.px = "/etc/clientlibs/shc/main/img/px.gif";
24933        /**
24934         * RSW-8379
24935         * We are updating sp_imageUrl to only serve the base image URL
24936         * so that we can independently trigger specific NamedImageTransforms
24937         * on it. Here for example, we are rasterizing the transparent areas
24938         * of the original image with grey pixels #f7f7f7 with "280x280-gray"
24939         * and specifically using the original image rendition instead of
24940         * DAM thumbnails for image quality.
24941         *
24942         */
24943        if (SHC.ui.screenMode === 'small') {
24944            this.sitewideTransform = "/jcr:content/renditions/original.transform/280x280-q76/image.jpg";
24945        } else {
24946            this.sitewideTransform = "/jcr:content/renditions/original.transform/220x220-q76/image.jpg";
24947        }
24948        SHC.ui.Tile.prototype.init.apply(this, arguments);
24949        return this;
24950    },
24951    /**
24952     *
24953     * @param attr
24954     */
24955    transition: function (attr) {
24956        SHC.ui.Tile.prototype.transition.apply(this, arguments);
24957    },
24958    /**
24959     *
24960     * @param attr
24961     */
24962    setHeight: function () {
24963        SHC.ui.Tile.prototype.setHeight.apply(this, arguments);
24964    },
24965    /**
24966     *
24967     * @param size
24968     * @returns {string}
24969     */
24970    getVignetteImage: function (size) {
24971        // no vignette for 8 and below.
24972        var msieVersion = SHC.util.msieVersion();
24973        if (msieVersion <= 8) {
24974            return $("<img>").attr({
24975                "class": "vignette lazyload",
24976                "data-src": this.px,
24977                "width": size + "px",
24978                "height": size + "px"
24979            });
24980        }
24981        return $("<img>").attr({
24982            "class": "vignette lazyload",
24983            "data-src": this.vignette,
24984            "width": size + "px",
24985            "height": size + "px"
24986        });
24987    },
24988    /**
24989     *
24990     * @param size
24991     * @returns {string}
24992     */
24993    getPlaceholderImage: function (size) {
24994        if(SHC.ui.Search.DirectoryUtil.isDirectoryPage()) {
24995            size = 235;
24996        }
24997        $('.tile-detail').addClass("profile-has-no-image");
24998        return $("<div class='no-img-available'><svg width='" + size + "' height='" + size + "'>" +
24999            "<image xlink:href='" + this.svgLogo + "' src='" + this.fallbackImage + "' " +
25000            "width='" + size + "' height='" + size + "'/></svg></div>");
25001    },
25002    /**
25003     *
25004     * @param photos
25005     * @param size
25006     * @returns {*}
25007     */
25008    getSquarePhoto: function (photos, size) {
25009        for (var i = 0, n = photos.length; i < n; i++) {
25010            if (photos[i].type === "square" && photos[i].url) {
25011                return this.getProfileImage(photos[i].url, size, photos[i].altText);
25012            }
25013        }
25014        return "";
25015    },
25016    /**
25017     *
25018     * @param photo
25019     * @param size
25020     * @returns {string}
25021     */
25022    getProfileImage: function (photo, size, altText) {
25023        var that = this;
25024        if(SHC.ui.Search.DirectoryUtil.isDirectoryPage) {
25025            size = SHC.ui.ProfileDeck.TILE_SIZES[SHC.ui.screenMode];
25026        }
25027        if (photo) {
25028            var onImageError = function () {
25029                $(this).attr("src", that.fallbackImage);
25030                this.width = size;
25031                this.height = size;
25032                SHC.ui.ProfileTile.FAILED_IMAGES[photo] = true;
25033            };
25034            var img = $("<img>").attr({
25035                "class": "profile-image lazyload",
25036                "width": size+"px",
25037                "height": size+"px"
25038            });
25039            img.css({            //css is done to fix ie8 error
25040                width: size+'px',
25041                height: size+'px'
25042            });
25043            if (altText !== "undefined" && altText.length > 0){
25044                img.attr("alt", altText);
25045            }
25046            img.on("error", onImageError);
25047
25048            // transitional bit.
25049            // we won't need this replace() call once RSW-8379 is released.
25050            photo = photo.replace("/jcr:content/renditions/cq5dam.thumbnail.319.319.png","");
25051            img.attr("data-src", photo+this.sitewideTransform);
25052            return img;
25053        } else {
25054            return this.getPlaceholderImage(size);
25055        }
25056    },
25057    /**
25058     *
25059     * @param size
25060     * @returns {string}
25061     */
25062    getPhysicianTileContent: function (size) {
25063        var p = this.jq.data("details");
25064        var vignette = "";
25065        var fullName = p.displayName.replace(/\uFFFD/g, ' '); //regex to remove non utf-8 characters
25066        var title = SHC.util.ellipsis(p.title, 50);
25067        var image = "";
25068        if (p.profile_photos && p.profile_photos.length) {
25069            vignette = this.getVignetteImage(size);
25070            image = this.getSquarePhoto(p.profile_photos, size);
25071        } else {
25072            image = this.getPlaceholderImage(size);
25073        }
25074        return this.wrapImage(vignette, image, fullName, title);
25075    },
25076    /**
25077     *
25078     * @param size
25079     * @returns {string}
25080     */
25081    getStaffTileContent: function (size) {
25082        var p = this.jq.data("details");
25083        var vignette = "";
25084        var fullName = p["jcr:title"];
25085        var altText = "";
25086        if (p.profile_photos && p.profile_photos.length) {
25087            altText = p.profile_photos[0].altText;
25088        }
25089        var image = this.getProfileImage(p["fileReference"], size, altText);
25090        if (!p["fileReference"]) {
25091            image = this.getPlaceholderImage(size);
25092        } else {
25093            vignette = this.getVignetteImage(size);
25094        }
25095        var shortTitle = (p["jobTitle"]) ? p["jobTitle"] : "";
25096        return this.wrapImage(vignette, image, fullName, shortTitle);
25097    },
25098    /**
25099     *
25100     * @param size
25101     * @returns {string}
25102     */
25103    getPhysicianSearchTileContent: function (size) {
25104        var p = this.jq.data("details");
25105        var vignette = "";
25106        var fullName = "";
25107        var shortTitle = "";
25108        var image = "";
25109        var path = p.url;
25110        var primaryAcademicTitle = "";
25111        if (p) {
25112            fullName = (p.displayName) ? p.displayName : "";
25113            primaryAcademicTitle = p.primaryAcademicTitle;
25114            if (p.groupsToTitles) {
25115                shortTitle = SHC.util.setPhysicianShortTitle(p.groupsToTitles);
25116            } else if (p.title) {
25117                shortTitle = p.title;
25118            }
25119            if (this.imageFailed(p.imageUrl)) {
25120                image = this.getPlaceholderImage(size);
25121            } else if (p.imageUrl) {
25122                vignette = this.getVignetteImage(size);
25123                image = this.getProfileImage(p.imageUrl, size, "");
25124            } else {
25125                image = this.getPlaceholderImage(size);
25126            }
25127            if (p.primaryAcademicTitle) {
25128                if(p.primaryAcademicTitle.indexOf("-") > -1){
25129                    primaryAcademicTitle = p.primaryAcademicTitle.replace(/-(.*)\w+/g, "");
25130                } else if(p.primaryAcademicTitle.indexOf("(") > -1) {
25131                    primaryAcademicTitle = p.primaryAcademicTitle.replace(/\s\(.*?\)/g, "");
25132                } else if(p.primaryAcademicTitle === "Dean of the Stanford University School of Medicine") {
25133                    primaryAcademicTitle = "Professor, Dean";
25134                } else if(p.primaryAcademicTitle === "Former Dean of the Stanford University School of Medicine") {
25135                    primaryAcademicTitle = "Professor, Former Dean";
25136                } else {
25137                    primaryAcademicTitle = p.primaryAcademicTitle;
25138                }
25139            }
25140        } else {
25141            fullName = "Doctor Profile Not Found";
25142            shortTitle = "Doctor Title Not Found";
25143        }
25144        var isStanfordDr = this.isStanfordPhysician(path, primaryAcademicTitle);
25145        return this.wrapImage(vignette, image, fullName, shortTitle, isStanfordDr, primaryAcademicTitle);
25146    },
25147
25148    isStanfordPhysician: function (path, primaryAcademicTitle) {
25149        var p = this.jq.data("details");
25150        if((p.primaryAcademicTitle && p.primaryAcademicTitle.length)) {
25151            return true;
25152        }
25153        else {
25154            return false;
25155        }
25156    },
25157    /**
25158     * Construct a full jQuery Object instead of static HTML.
25159     * @param vignette
25160     * @param image
25161     * @param name
25162     * @param title
25163     * @returns {*|jQuery|HTMLElement}
25164     */
25165    wrapImage: function (vignette, image, name, title, isStanfordDr, primaryAcademicTitle) {
25166        name = SHC.util.formatNameText(name);
25167        var altName = name.replace('&nbsp;', ' ');
25168        image.attr("alt", altName);
25169        var imageDiv = $("<div class='tile-image-container'/>").prepend(image);
25170        var result = $("<span></span>");
25171        var tileDetail = "";
25172            if(isStanfordDr){
25173                tileDetail = $("<div class='tile-detail'><span class='name'>" +
25174                    name + "</span><br/>" + "<span class='title'>" + title + "</span>" +
25175                    "<span class='academic-title'>" + primaryAcademicTitle + "</span></div>");
25176            } else {
25177                tileDetail = $("<div class='tile-detail'><span class='name'>" +
25178                    name + "</span><br/>" + "<span class='title'>" + title + "</span></div>");
25179            }
25180
25181        // check if vignette is turned off
25182        // before appending to it
25183        if (vignette) {
25184            result.replaceWith(vignette);
25185        }
25186
25187        // if the doctor has a clinic and there's a distance from the zip code they just searched, add mileage marker
25188        // also, check if we're on primary care toggle, only want to show it for that, for now.
25189        if(this.jq.data("details").contactInfo && this.jq.data("details").contactInfo[0] && SHC.ui.Search.DirectoryUtil.isPrimaryCareToggleActive()) {
25190            var distance = this.jq.data("details").contactInfo[0].distance;
25191            if(typeof distance !== 'undefined' && distance !== "") {
25192                var mileageMarker = "<div class='mileage-text'>"+ SHC.util.formatDistance(distance) +" mi</div><div class='mileage-background'></div>";
25193                return result.append(imageDiv).append(tileDetail).append(mileageMarker);
25194            }
25195        }
25196
25197        return result.append(imageDiv).append(tileDetail);
25198
25199    },
25200    /**
25201     * Check lookup table.
25202     * @returns {boolean}
25203     */
25204    imageFailed: function(imageUrl) {
25205        return (!imageUrl || SHC.ui.ProfileTile.FAILED_IMAGES[imageUrl] === true);
25206    },
25207    /**
25208     * Preloading of image sources should really happen
25209     * independently from the show() method call.
25210     */
25211    preload: function() {
25212        var size = SHC.ui.ProfileDeck.TILE_SIZES[SHC.ui.screenMode];
25213        var deckType = this.jq.data("deckType");
25214        if (deckType === "staff") {
25215            this.jq.append(this.getStaffTileContent(size));
25216        } else if (deckType === "physicians" || deckType === "primaryCare" || deckType === "specialist" || deckType === "appdoctors") {
25217            this.jq.append(this.getPhysicianTileContent(size));
25218        } else {
25219            this.jq.append(this.getPhysicianSearchTileContent(size));
25220        }
25221        SHC.ui.Tile.prototype.preload.apply(this, arguments);
25222    },
25223    /**
25224     *
25225     */
25226    show: function () {
25227        SHC.ui.Tile.prototype.show.apply(this, arguments);
25228    }
25229});
25230SHC.Namespace(SHC, "SHC.ui.ProfileDeck");
25231SHC.ui.ProfileDeck = new SHC.Class();
25232
25233// removed in RSW-11118 as part of cleanup.
25234SHC.ui.ProfileDeckSearch = { TYPE: null };
25235
25236// tile heights at different screenModes
25237SHC.ui.ProfileDeck.TILE_SIZES = {
25238    "small": 280,
25239    "medium": 220,
25240    "large": 220
25241};
25242
25243// number of profile tiles
25244SHC.ui.ProfileDeck.COUNT = {
25245    "small": 5,
25246    "medium": 5,
25247    "large": 7
25248};
25249
25250SHC.ui.ProfileDeck.TILES_PER_ROW = {
25251    "small": 5,
25252    "medium": 3,
25253    "large": 4
25254};
25255
25256SHC.ui.ProfileDeck.ORG_COUNT ={
25257    "shc_count": 4,
25258    "uha_count":3
25259};
25260SHC.ui.ProfileDeck.include({
25261    /**
25262     * constructor
25263     * @param parent
25264     */
25265    init: function (parent, componentID, deckType, mode , profileType) {
25266        "use strict";
25267        if (!parent) {
25268            return;
25269        }
25270        var that = this;
25271        this.parent = parent;
25272        this.tiles = [];
25273        this.data = [];
25274        this.globalDataCount = 0;
25275        this.selected = 0;
25276        this.componentID = componentID;
25277        this.deckType = (deckType) ? deckType : "physicians";
25278        this.profileType = (profileType) ? profileType : "default";
25279        this.componentDiv = $(this.parent);
25280        this.wrapperDiv = this.componentDiv.parent(".profiledeck");
25281        this.pointer = null;
25282        this.detailDiv = null;
25283        this.nextButton = null;
25284        this.previousButton = null;
25285        this.clickScreen = null;
25286        this.physicianSearchResults = SHC.ui.Search.DirectoryUtil.guidedDirectoryURL;
25287        this.summaryQuery = GLOBAL_SPURL_OBJECT + "/?do=organic_phys";
25288        var searchVer = document.querySelector('meta[name="shc-search-version"]').content || "v1";
25289        this.cachedSearchServletUrl = "/bin/api/"+searchVer+"/search.json?do=organic_phys";
25290        this.count = SHC.ui.ProfileDeck.COUNT[SHC.ui.screenMode];
25291        this.tileHeight = SHC.ui.ProfileDeck.TILE_SIZES[SHC.ui.screenMode];
25292        this.isIe = SHC.util.msieVersion();
25293        this.summaryCountData=0;
25294        this.summary = null;
25295        this.mode = mode;
25296        this.megaData =[];
25297        this.haveSummaryCount = false;
25298        this.masthead = $('#header .masthead');
25299        this.docCountsService = {
25300            primary: null,
25301            specialty: null,
25302            total: null
25303        };
25304
25305        // Handlebars templates
25306        this.staffProfileTemplate = JST["handlebars/profileStaffTemplate.hbs"];
25307        this.physicianProfileTemplate = JST["handlebars/profilePhysicianTemplate.hbs"];
25308        this.summaryTileTemplate = JST["handlebars/summaryTileTemplate.hbs"];
25309
25310        this.initArrowKeyNavigation();
25311        this.loadData();
25312        this.componentDiv.addClass(SHC.ui.screenMode);
25313        if(SHC.util.msieVersion() === 8){
25314            this.componentDiv.addClass('ie8');
25315        }
25316        this.show();
25317    },
25318
25319    /**
25320     * load physicians array.
25321     * @returns {*}
25322     */
25323    loadData: function () {
25324        var that = this,
25325            physiciansURL = "/bin/api/physicians/clinic.json" + this.componentDiv.attr("data-page-path") + ".json",
25326            staffURL = "/bin/api/staff.json" + this.componentDiv.attr("data-page-path") + ".json";
25327
25328        if(this.deckType === 'primaryCare' || this.deckType === 'specialist' || this.deckType === 'appdoctors'){
25329            physiciansURL += '?physicianType=' + this.deckType;
25330        }
25331
25332        var url = (this.deckType === "staff") ? staffURL : physiciansURL;
25333        $.ajax({
25334            dataType: "json",
25335            url: url,
25336            success: function (data) {
25337                that.setCounts(data, that.deckType);
25338                that.setData(data.results);
25339                that.show();
25340                that.activate();
25341            }
25342        });
25343    },
25344
25345    setCounts: function (data, deckType) {
25346        var combined = [];
25347        $.each(data.results, function(key, value) {
25348            combined = combined.concat(value);
25349        });
25350        var docsLength = combined.length;
25351        switch (deckType) {
25352            case "physicians":
25353                this.docCountsService.total = docsLength;
25354                break;
25355
25356            case "primaryCare":
25357                this.docCountsService.primary = docsLength;
25358                break;
25359
25360            case "specialist":
25361                this.docCountsService.specialty = docsLength;
25362                break;
25363
25364            case "appdoctors":
25365                this.docCountsService.total = docsLength;
25366                break;
25367        }
25368    },
25369
25370    /**
25371     *
25372     * @param data
25373     */
25374    setData: function (data) {
25375        var that = this;
25376        this.data = that.preProcessData(data);
25377        if(!this.data){
25378            this.dataCountCheck();
25379        }
25380        this.megaData = that.data;
25381    },
25382
25383    /**
25384     * Clear the whole ProfileDeck.
25385     */
25386    clear: function () {
25387        for (var i = 0, n = this.tiles.length; i < n; i++) {
25388            if (this.tiles[i].jq) {
25389                this.tiles[i].jq.remove();
25390            }
25391        }
25392        this.tiles = [];
25393        if (this.navigationButtons) {
25394            this.navigationButtons.remove();
25395        }
25396
25397    },
25398
25399    onKeydownHandler: function (evt) {
25400        switch (evt.which) {
25401            case 27:
25402                this.unfocus();
25403                break;
25404        }
25405    },
25406
25407    /**
25408     * render component
25409     */
25410    show: function (data) {
25411        var that = this;
25412        if(data){
25413            this.data = data;
25414        }
25415        if(this.data.length === 7 && SHC.ui.screenMode !== "large" ){
25416            this.data = that.arrayRemove(2,this.data);
25417        }
25418
25419        if(!this.data) {
25420            return;
25421        }
25422
25423        this.addRow();
25424        var profileContainer = "col-xl-3 col-lg-3 col-md-3 col-sm-6 col-xs-6 profile-tile";
25425        var summaryContainer = "col-xl-3 col-lg-3 col-md-3 col-sm-6 col-xs-6 summary-tile";
25426        var gotoLink = function () {
25427            var details = that.tiles[that.selected].jq.data("details");
25428            if (details && details.path) {
25429                window.location = details.path + ".html";
25430            }
25431        };
25432
25433        var onProfileClickHandler = function (e) {
25434            var jq = $(this);
25435            that.selected = jq.data("index");
25436            var currentID = '#profile-' + that.componentID + "-" + that.selected;
25437            var currentTile = $(currentID);
25438
25439            //Condition for not displaying detail for Mobile Version
25440            if (that.isSmallScreen()) {
25441                gotoLink();
25442            } else {
25443                that.scrollTo();
25444                if (currentTile.hasClass('selected')) {
25445                    gotoLink();
25446                } else {
25447                    // this needs to be specific to component
25448                    $('.profile-tile').removeClass('selected');
25449                    currentTile.addClass('selected');
25450                }
25451
25452            }
25453        };
25454
25455        var onSummaryClickHandler = function (e) {
25456            if (e) {
25457                e.stopPropagation();
25458            }
25459            that.unfocus();
25460            var clinicPath = window.location.pathname.replace("/content/shc/en", "");
25461            var pageTitle = encodeURIComponent(that.componentDiv.attr("data-page-header"));
25462            var url = that.physicianSearchResults + "/&sp_clinics%7C" + clinicPath + "%5E" + pageTitle;
25463
25464            if(that.deckType === 'primaryCare') {
25465                url += '#&x1=sp_prim_care_phy&q1=true&x2=sp_isapp&q2=false';
25466            } else if(that.deckType === 'specialist') {
25467                url += '#&x1=sp_spec_care_phy&q1=true&x2=sp_isapp&q2=false';
25468            } else if (that.deckType === 'appdoctors') {
25469                url += '#&x2=sp_isapp&q2=true';
25470            } else {
25471                url += '#&x2=sp_isapp&q2=false';
25472            }
25473
25474            SHC.util.setCookie("activeView", "list", 1, "/");
25475
25476            window.location = url;
25477        };
25478
25479        this.clear();
25480
25481        if ((this.count > this.data.length )) {
25482            this.count = this.data.length;
25483        }
25484        var rowNo = 1;
25485        var parent;
25486
25487        for (var i = 0; i < this.count; i++) {
25488            var id = "profile-" + this.componentID + "-" + i;
25489
25490            parent = this.parent;
25491            if (SHC.ui.screenMode === "large" || SHC.ui.screenMode === "medium") {
25492                parent = "div.row" + rowNo + "-" + this.componentID;
25493                if ((SHC.ui.screenMode === "large" && (i + 1) % SHC.ui.ProfileDeck.TILES_PER_ROW[SHC.ui.screenMode]) === 0
25494                    || (SHC.ui.screenMode === "medium" && (i + 1) % SHC.ui.ProfileDeck.TILES_PER_ROW[SHC.ui.screenMode]) === 0) {
25495
25496                    rowNo++;
25497                }
25498            }
25499            var tile = new SHC.ui.ProfileTile(parent, {
25500                "id": id,
25501                "class": profileContainer
25502            });
25503            tile.setHeight(this.tileHeight);
25504            tile.data("index", i);
25505            tile.data("details", this.data[i]);
25506            tile.data("deckType", this.deckType);
25507            tile.jq.on("click", onProfileClickHandler);
25508            if(SHC.ui.screenMode ==="small"){
25509                tile.jq.on("tap", onProfileClickHandler);
25510            }
25511            this.tiles.push(tile);
25512        }
25513
25514        if (this.data.length > this.count || this.globalDataCount > SHC.ui.ProfileDeck.COUNT[SHC.ui.screenMode]) {
25515            parent = this.parent;
25516
25517
25518            if (SHC.ui.screenMode === "large" || SHC.ui.screenMode === "medium") {
25519                parent = "div.row" + rowNo + "-" + this.componentID;
25520            }
25521            that.summary = new SHC.ui.Tile(parent, {
25522                "id": "summary-tile-" + this.componentID,
25523                "class": summaryContainer
25524            });
25525            that.summaryCount();
25526            that.summary.setHeight(this.tileHeight);
25527            /*  if (this.deckType === "staff") {
25528             summary.jq.append(this.getSummary("Staff"));
25529             } else {
25530             summary.jq.append(this.getSummary("Doctors"));
25531             }*/
25532
25533            that.summary.jq.on('tap click', onSummaryClickHandler);
25534            this.tiles.push(that.summary);
25535        }
25536
25537        // Resize Profile Detail Box
25538        var BOX_HEIGHT = 87;
25539        for (i = 0, n = this.tiles.length; i < n; i++) {
25540            this.tiles[i].preload();
25541            this.tiles[i].show();
25542            var detailBox = this.tiles[i].jq.find(".tile-detail").eq(0);
25543            var scrollHeight = (detailBox && detailBox.length) ? detailBox[0].scrollHeight : 0;
25544            if (scrollHeight) {
25545                detailBox.css('height', (scrollHeight > BOX_HEIGHT) ? scrollHeight + 5 : BOX_HEIGHT);
25546            }
25547        }
25548
25549        if (this.isSmallScreen()) {
25550            this.componentDiv.css('width', '' + ((this.tileHeight + 22) * (this.count + 1)) + 'px');
25551            this.wrapperDiv.css({"width": "100%"});
25552            this.appendMobileNavigation();
25553        }
25554    },
25555
25556    unfocus: function () {
25557        this.closeDetails();
25558        this.unFadeAllTiles();
25559    },
25560
25561    isSmallScreen: function () {
25562        return (SHC.ui.screenMode === "small");
25563    },
25564
25565    isLargeScreen: function () {
25566        return (SHC.ui.screenMode === "large");
25567    },
25568    /**
25569     * onTouchEvent handler
25570     * @param evt event object
25571     * @param dir direction
25572     * @param phase start,move,end
25573     * @param swipetype
25574     * @param distance
25575     */
25576    onTouchEvent: function (evt, dir, phase, swipetype, distance) {
25577        var scale = 1;
25578        // dragging
25579        if (phase === "move" && this.tiles) {
25580            if (dir === "left" || dir === "right") {
25581                var offset = (-1 * this.tileHeight * this.selected) + (distance * scale);
25582                var maxOffset = -1 * (this.tileHeight * (this.tiles.length - 1));
25583                if (offset < 0 && offset > maxOffset) {
25584                    this.componentDiv.css({x: offset});
25585                }
25586            } else if (dir === "up" || dir === "down") {
25587                var body = $("body"),
25588                    yOffset = body.scrollTop() + (-1 * distance * scale);
25589                body.scrollTop(yOffset);
25590                return;
25591            }
25592        }
25593        // end of swipe
25594        if (phase !== "end") {
25595            return;
25596        }
25597        switch (dir) {
25598            case "left":
25599                this.gotoNext();
25600                break;
25601            case "right":
25602                this.gotoPrevious();
25603                break;
25604            default:
25605                break;
25606        }
25607    },
25608
25609    getSummary: function (title) {
25610        var summary = {
25611            totalCount: this.summaryCountData,
25612            title: title,
25613            componentID: this.componentID
25614        };
25615        return this.summaryTileTemplate(summary);
25616    },
25617
25618    /**
25619     * Left and Right Arrow Key Navigation
25620     */
25621    initArrowKeyNavigation: function() {
25622        var that = this;
25623        that.closeDetails();
25624        that.detailDiv = $("<div class='detail col-md-12'></div>");
25625        $(document).keyup(function(e) {
25626            if(e.which === 37 && that.previousButton && that.previousButton.is(":visible")) {
25627                e.preventDefault();
25628                that.gotoPrevious();
25629                SHC.ui.ProfileDeck.PADDLE_FLAG=true;
25630            } else if(e.which === 39 && that.nextButton && that.nextButton.is(":visible"))  {
25631                e.preventDefault();
25632                that.gotoNext();
25633                SHC.ui.ProfileDeck.PADDLE_FLAG=true;
25634            }
25635            if(e.keyCode === 27) {
25636                that.unfocus();
25637                $('.profile-tile').css("z-index", "auto");
25638            }
25639        });
25640    },
25641
25642    /**
25643     * Append Navigation
25644     */
25645    appendNavigation: function () {
25646        var that = this;
25647        if (!this.nextButton) {
25648            this.nextButton = $("<a href='#' class='next'></a>");
25649            this.previousButton = $("<a href='#' class='previous'></a>");
25650            var detailHeight = $(this.detailDiv).height();
25651            if (detailHeight < 260){
25652                $(this.nextButton).css('top','-40px');
25653                $(this.previousButton).css('top','-40px');
25654            }
25655            this.previousButton.click(function (e) {
25656                e.preventDefault();
25657                that.gotoPrevious();
25658                SHC.ui.ProfileDeck.PADDLE_FLAG=true;
25659            });
25660            var detailDivWidth = $(this.detailDiv).width();
25661            var detailContentWidth = $(this.detailDiv).find('.container').width();
25662            var paddlePos = Math.round(((detailDivWidth-detailContentWidth)/2)-42); //42 is the margin thats required
25663            //if the width of the container cannot have the margin within we default to 15px (Needs to verify with razorfish)
25664            if(paddlePos <=10){
25665                paddlePos = 15;
25666            }
25667            this.nextButton.click(function (e) {
25668                e.preventDefault();
25669                that.gotoNext();
25670                SHC.ui.ProfileDeck.PADDLE_FLAG=true;
25671            });
25672
25673            if (this.detailDiv) {
25674                if (this.summaryTile || parseInt(this.selected) + 1 !== this.count) {
25675                    this.detailDiv.find('.paddle').append(this.nextButton);
25676                    //$(this.nextButton).css('right',paddlePos+'px');
25677                }
25678                if (this.selected !== "0") {
25679                    this.detailDiv.find('.paddle').append(this.previousButton);
25680                    //$(this.previousButton).css('left',paddlePos+'px');
25681                }
25682
25683                //place paddle buttons inside the correct div when only 1 column of details
25684                var $detailContent = this.detailDiv.find('.detail-content.clearboth');
25685                if($detailContent.find('.paddle').length === 0){
25686                    $detailContent.append(this.detailDiv.find('.paddle'));
25687                }
25688            }
25689        }
25690    },
25691
25692    /**
25693     *Append Mobile Navigation
25694     */
25695    appendMobileNavigation: function () {
25696        var that = this,
25697            i;
25698        this.navigationButtons = $("<ul class='navigationButtons'></ul>");
25699        //this.wrapperDiv.append(this.navigationButtons);
25700        $('#pd-' + this.componentID).closest('.profiledeck').append(this.navigationButtons);
25701        if(this.data.length > this.count){
25702            for (i = 0; i <= this.count; i++) {
25703                this.navigationButtons.append('<li index="' + i + '"></li>');
25704            }
25705        }
25706        else if(this.data.length <= this.count){
25707            for (i = 0; i <this.count; i++) {
25708                this.navigationButtons.append('<li index="' + i + '"></li>');
25709            }
25710        }
25711        this.mobileNavButtonCheck();
25712        var listItems = this.navigationButtons.find('li');
25713        // select first element.
25714        this.selected = 0;
25715        listItems.eq(0).addClass("selected");
25716
25717        var onNavButtonClick = function () {
25718            var index = $(this).attr("index");
25719            listItems.removeClass("selected");
25720            listItems.eq(that.selected).addClass("selected");
25721            that.selected = index;
25722            that.slide();
25723        };
25724        listItems.click(onNavButtonClick);
25725
25726        if(this.data.length === 1){
25727            $('.profiledeck').addClass('only-one-doctor');
25728        } else {
25729            $('.profiledeck').removeClass('only-one-doctor');
25730        }
25731
25732    },
25733
25734    onResizeHandler: function () {
25735        var that= this;
25736        var mode = SHC.ui.screenMode;
25737        this.tileHeight = SHC.ui.ProfileDeck.TILE_SIZES[mode];
25738        this.count = SHC.ui.ProfileDeck.COUNT[mode];
25739        that.summaryCount();
25740        if(this.isSmallScreen()){
25741            if(this.data && this.data.length === 1){
25742                $('.profiledeck').addClass('only-one-doctor');
25743            }
25744        } else {
25745            $('.profiledeck').removeClass('only-one-doctor');
25746        }
25747        if (this.isSmallScreen() && !$('html').hasClass('touch') ) {
25748            // Apply swipe listeners for small screens.
25749            this.touchSurface = new SHC.ui.TouchSurface(this.componentDiv[0],
25750                function (evt, dir, phase, swipetype, distance) {
25751                    that.onTouchEvent(evt, dir, phase, swipetype, distance);
25752                });
25753            this.componentDiv.css({"width": "100%", "overflow": "hidden"});
25754            this.wrapperDiv.css({"width": "265px", "overflow": "hidden"});
25755        } else {
25756            // unbind swap listeners.
25757            if (this.touchSurface) {
25758                this.touchSurface.removeEventListeners();
25759            }
25760            this.componentDiv.removeAttr("style");
25761            this.wrapperDiv.css({"width": "auto", "overflow": "visible"});
25762        }
25763        this.componentDiv
25764            .removeClass("small")
25765            .removeClass("medium")
25766            .removeClass("large")
25767            .addClass(mode);
25768        if (SHC.util.msieVersion() === 8) {
25769            this.unFadeAllTiles();
25770        } else {
25771            this.unfocus();
25772            this.show(this.megaData);
25773        }
25774
25775    },
25776
25777    /**
25778     * Setup event handlers reside here.
25779     */
25780    activate: function () {
25781        var that = this;
25782        // Resize Events
25783        var onResizeHandler = function () {
25784            that.onResizeHandler();
25785        };
25786        var onKeydownHandler = function (evt) {
25787            that.onKeydownHandler(evt);
25788        };
25789        var onTouchEventHandler = function (evt, dir, phase, swipetype, distance) {
25790            that.onTouchEvent(evt, dir, phase, swipetype, distance);
25791        };
25792
25793        var onBodyClickHandler = function(e) {
25794
25795            if (!e) {
25796                e = window.event;
25797            }
25798            if(((e.target || e.srcElement).id) === "pd-"+that.componentID){
25799
25800                SHC.ui.ProfileDeck.PADDLE_FLAG = false;
25801            }
25802            if(!SHC.ui.ProfileDeck.PADDLE_FLAG){
25803                that.unfocus();
25804            }
25805            $("#pd-"+that.componentID).find('.profile-tile').removeClass('selected');
25806            $('.profile-tile').css("z-index", "auto");
25807
25808        };
25809        var $window = $(window);
25810        $window.off("resizeEnd", onResizeHandler)
25811            .on("resizeEnd", onResizeHandler)
25812            .off("keydown", onKeydownHandler)
25813            .on("keydown", onKeydownHandler);
25814        // only listen to swipe events
25815        // in small screenmode
25816        if (SHC.ui.screenMode === "small") {
25817            this.touchSurface = new SHC.ui.TouchSurface(this.componentDiv[0],
25818                onTouchEventHandler);
25819        } else {
25820            $("body").on("click", onBodyClickHandler);
25821        }
25822        // trigger refresh on activate()
25823        this.componentDiv.trigger("resizeEnd");
25824    },
25825
25826    showDetails: function () {
25827        var that = this;
25828        var getXPos = function (ix) {
25829            return that.tiles[ix].jq.position().left;
25830        };
25831        var findInsertIndex = function () {
25832            var selected = that.selected;
25833            var selectedXPos = getXPos(selected);
25834            var length = that.tiles.length;
25835            if (selected < length - 1) {
25836                var i = selected + 1;
25837                while (i < length && selectedXPos < getXPos(i)) {
25838                    i++;
25839                }
25840                return i - 1;
25841            } else {
25842                return length - 1;
25843            }
25844        };
25845        var insertDiv = function () {
25846            var index = findInsertIndex();
25847            that.closeDetails();
25848            that.detailDiv = $("<div class='detail col-md-12'></div>");
25849            if (that.deckType === "staff") {
25850                that.detailDiv.html(that.getStaffDetails());
25851            } else {
25852                that.detailDiv.html(that.getPhysicianDetails());
25853            }
25854            that.detailDiv.on("click", ".close", function () {
25855                that.unfocus();
25856            });
25857            that.tiles[index].jq.closest('div.tileRow').after(that.detailDiv);
25858            that.detailDiv.on('click',function(){
25859
25860                SHC.ui.ProfileDeck.PADDLE_FLAG = true;
25861            });
25862            that.masthead.hide();
25863        };
25864        if (that.tiles[that.selected] instanceof SHC.ui.ProfileTile) {
25865            insertDiv();
25866            if (this.isLargeScreen()) {
25867                this.appendNavigation();
25868                this.setViewAllButtonContainer();
25869            }
25870        }
25871    },
25872
25873    closeDetails: function () {
25874        if (this.pointer) {
25875            this.pointer.remove();
25876        }
25877        if (this.detailDiv) {
25878            if (this.nextButton) {
25879                this.nextButton.remove();
25880                delete this.nextButton;
25881            }
25882            if (this.previousButton) {
25883                this.previousButton.remove();
25884                delete this.previousButton;
25885            }
25886            this.detailDiv.remove();
25887        }
25888        this.masthead.show();
25889    },
25890
25891    getStaffDetails: function () {
25892        var staff = this.tiles[this.selected].jq.data("details");
25893        var staffObject = {
25894            name: staff["jcr:title"],
25895            bio: (staff.bio) ? staff.bio : "",
25896            jobTitle: (staff.jobTitle) ? staff.jobTitle : "",
25897            path: staff.path
25898        };
25899        return this.staffProfileTemplate(staffObject);
25900    },
25901
25902    getPhysicianDetails: function () {
25903        var physician = this.tiles[this.selected].jq.data("details");
25904        var edu = (physician.education) ? physician.education : [];
25905        // instantiate object to pass to Handlebars.
25906        var physObject = {};
25907
25908        // only show education entries that match these two patterns:
25909        var regexArray = [];
25910        regexArray.push(new RegExp("Board Certification"));
25911        regexArray.push(new RegExp("Board Recertification"));
25912        // reduce list
25913        edu = SHC.util.filterListMulti(edu, regexArray, "text");
25914        if (edu && edu.length) {
25915            physObject.certifications = [];
25916            for (i = 0, n = edu.length; i < n; i++) {
25917                var cert = edu[i].text;
25918                // cleanup text
25919                cert = cert.replace("Board Certification:", "");
25920                cert = cert.replace("Board Certification,", "");
25921                cert = cert.replace("Board Recertification,", "");
25922                cert = cert.replace("Board Recertification:", "");
25923                physObject.certifications.push(cert);
25924            }
25925        }
25926        physObject.clinicLocations = (physician.clinical_contacts &&
25927        physician.clinical_contacts.length) ? physician.clinical_contacts : [];
25928
25929        var checkConditionsCount = 0;
25930        physObject.conditionsTreated = [];
25931        physObject.specialInterests = [];
25932        if(physician.conditions){
25933            if(physician.conditions.length){
25934                checkConditionsCount += physician.conditions.length;
25935                physObject.conditionsTreated = physObject.conditionsTreated.concat(physician.conditions);
25936            }
25937        }
25938        if(physician.treatments){
25939            if(physician.treatments.length){
25940                checkConditionsCount += physician.treatments.length;
25941                physObject.conditionsTreated = physObject.conditionsTreated.concat(physician.treatments);
25942            }
25943        }
25944        if(physician.medical_tests){
25945            if(physician.medical_tests.length){
25946                checkConditionsCount += physician.medical_tests.length;
25947                physObject.conditionsTreated = physObject.conditionsTreated.concat(physician.medical_tests);
25948            }
25949        }
25950        if(physician.special_interests){
25951            if(physician.special_interests.length){
25952                physObject.specialInterests = physician.special_interests;
25953            }
25954        }
25955        physObject.hideRating = (physician.hideRating) ? "true" : "false";
25956        physObject.conditions_count = checkConditionsCount;
25957        physObject.path = physician.path;
25958        physObject.group = physician.group;
25959        physObject.title = physician.title;
25960        physObject.clinicCounts = physician.num_of_clinical_contacts;
25961        physObject.avg_rating = physician.avg_rating;
25962        physObject.percentage=(physician.avg_rating/5)*100;
25963        physObject.name = physician.displayName.replace(/\uFFFD/g, ' ').replace(/&nbsp;/gi,' ').replace(/&ntilde;/g, '\u00f1');
25964        physObject.isPrimaryCareDeck = this.deckType === "primaryCare";
25965        physObject.isSpecialistDeck = this.deckType === "specialist" || this.deckType === "physicians" || this.deckType === 'appdoctors';
25966        physObject.isAPPDeck = this.deckType === 'appdoctors';
25967        return this.physicianProfileTemplate(physObject);
25968    },
25969
25970    gotoNext: function () {
25971        if (this.selected < this.tiles.length - 1) {
25972            this.selected++;
25973            if (this.previousButton) {
25974                this.previousButton.show();
25975            }
25976        }
25977        if (this.isSmallScreen()) {
25978            this.slide();
25979        } else {
25980            this.scrollTo();
25981        }
25982    },
25983
25984    gotoPrevious: function () {
25985        if (this.selected > 0) {
25986            this.selected--;
25987        } else {
25988            this.selected = 0;
25989            if (this.previousButton) {
25990                this.previousButton.hide();
25991            }
25992        }
25993        if (this.isSmallScreen()) {
25994            this.slide();
25995        } else {
25996            this.scrollTo();
25997        }
25998    },
25999
26000    slide: function () {
26001        var li = this.navigationButtons.find('li');
26002        var gutter = 2;
26003        var position = -1 * this.selected * (this.tileHeight + gutter);
26004        this.componentDiv.transition({x: position}, 500, 'linear');
26005        li.removeClass("selected");
26006        li.eq(this.selected).addClass("selected");
26007    },
26008
26009    selectTile: function () {
26010        var tileSelected = this.tiles[this.selected].jq;
26011        // It's either a Summary Tile
26012        if (tileSelected.hasClass("summary-tile")) {
26013            this.unfocus();
26014            // ... or a Profile Tile.
26015        } else {
26016            this.fadeAllTiles();
26017            tileSelected.removeClass("fade");
26018            tileSelected.find(".tile-detail").hide();
26019            tileSelected.css('z-index', '3000');
26020        }
26021        if (this.pointer) {
26022            this.pointer.remove();
26023        }
26024        this.pointer = $('<div class="pointer"></div>');
26025        tileSelected.append(this.pointer);
26026    },
26027
26028    fadeAllTiles: function () {
26029        var that = this;
26030        if (!this.clickScreen) {
26031            this.clickScreen = $('<div id="pd-click-screen" class="modal-backdrop fade in"></div>');
26032            this.clickScreen.on("click", function () {
26033                that.unfocus();
26034            });
26035            if($(that.parent).parents('.search-results-page')) {
26036                if (SHC.ui.ProfileDeckSearch.TYPE === "View All") {
26037                    this.clickScreen.appendTo(document.body);
26038                }
26039            }
26040        }
26041        this.componentDiv.css({"zIndex": "3000"});
26042        for (var i = 0, n = this.tiles.length; i < n; i++) {
26043            var tile = this.tiles[i].jq;
26044            tile.addClass("fade");
26045            tile.find(".tile-detail").show();
26046        }
26047    },
26048
26049    unFadeAllTiles: function () {
26050        if (this.clickScreen) {
26051            this.clickScreen.remove();
26052            this.clickScreen = null;
26053        }
26054        delete this.clickScreen;
26055        this.componentDiv.css({"zIndex": "auto"});
26056        for (var i = 0, n = this.tiles.length; i < n; i++) {
26057            var tile = this.tiles[i].jq;
26058            tile.removeClass("fade");
26059            tile.find(".tile-detail").show();
26060        }
26061    },
26062
26063    scrollTo: function () {
26064        var that = this;
26065        if (((this.selected) % 4 === 0 && SHC.ui.screenMode === "large")) {
26066            if (that.detailDiv) {
26067                that.detailDiv.hide();
26068                if ($('div.pointer').length) {
26069                    $('div.pointer').remove();
26070                }
26071            }
26072        }
26073        var target = $('#profile-' + this.componentID + "-" + this.selected);
26074
26075        $.scrollTo(target, {
26076                "duration": 300,
26077                "axis": "y",
26078                "offset": {top: -(target.height())},
26079                "onAfter": function () {
26080                    that.showDetails();
26081                    that.selectTile();
26082                    if (that.detailDiv) {
26083                        if ((this.selected + 1) % 4 !== 0) {
26084                            that.detailDiv.hide();
26085                        }
26086                        that.detailDiv.show();
26087                    }
26088                }
26089            }
26090        );
26091    },
26092
26093    addRow: function () {
26094        var that = this,
26095            i;
26096        if(SHC.ui.ProfileDeckSearch.TYPE !== "View All"){
26097            $('.tileRow.deckID' + this.componentID).remove();
26098        }
26099        var rowCount = null;
26100        if(SHC.ui.ProfileDeckSearch.TYPE ==="View All"){
26101            rowCount = Math.ceil((parseInt(SHC.ui.Search.ResultsBinder.profileTileCount) + 1) / parseInt(SHC.ui.ProfileDeck.TILES_PER_ROW[SHC.ui.screenMode]));
26102            for (i = 1; i <= rowCount; i++) {
26103                $(this.parent).append('<div view-all-counter="'+SHC.ui.Search.ResultsBinder.counter+'" class="tileRow  row' + i + '-'+SHC.ui.Search.ResultsBinder.counter+'-' + that.componentID + ' deckID' + this.componentID + '"></div>');
26104
26105            }
26106        }else{
26107            rowCount = Math.ceil((parseInt(this.count) + 1) / parseInt(SHC.ui.ProfileDeck.TILES_PER_ROW[SHC.ui.screenMode]));
26108            for (i = $('.tileRow .deckID' + this.componentID).length; i <= rowCount; i++) {
26109                $(this.parent).append('<div class="tileRow row' + i + '-' + that.componentID + ' deckID' + that.componentID + '"></div>');
26110
26111            }
26112        }
26113    },
26114
26115    summaryCount: function () {
26116        var that = this;
26117        if (!this.summary) {
26118            return; // sanity check.
26119        }
26120        if (this.deckType === "staff") {
26121            that.summary.jq.append(that.getSummary("Staff"));
26122        } else if (this.deckType === "appdoctors") {
26123            that.summary.jq.append(that.getSummary("Advanced Practice Providers"));
26124        } else {
26125            that.summary.jq.append(that.getSummary("Doctors"));
26126        }
26127        var selector = '.profiledeck .summary-content .totalCount.' + that.componentID;
26128        switch(that.deckType){
26129            case 'primaryCare':
26130                this.getSummaryCountFromSP(selector, 'primaryCare');
26131                break;
26132            case 'specialist':
26133                this.getSummaryCountFromSP(selector, 'specialist');
26134                break;
26135            case 'appdoctors':
26136                this.getSummaryCountFromSP(selector, 'appdoctors');
26137                break;
26138            default:
26139                this.getSummaryCountFromSP(selector, 'physicians');
26140                break;
26141        }
26142    },
26143
26144    getSummaryCountFromSP: function(selector, doctorType){
26145        var encodedClinicName = encodeURIComponent(this.componentDiv.attr("data-page-header"));
26146        var url = this.cachedSearchServletUrl + '&x22=sp_clinics&q22=' + encodedClinicName;
26147
26148        if(doctorType === 'primaryCare'){
26149            url += '&x1=sp_prim_care_phy&q1=true&x2=sp_isapp&q2=false';
26150        }else if(doctorType === 'specialist'){
26151            url += '&x1=sp_spec_care_phy&q1=true&x2=sp_isapp&q2=false';
26152        } else if (doctorType === 'appdoctors') {
26153            url += '&x2=sp_isapp&q2=true';
26154        } else {
26155            url += '&x2=sp_isapp&q2=false';
26156        }
26157        url += '&sp_c=0'; //no payload needed
26158
26159        SHC.searchRequest = jQuery.ajax({
26160            url: url,
26161            dataType: "jsonp",
26162            jsonp: 'callback',
26163            contentType: "application/json",
26164            success: function (data) {
26165                if(doctorType === 'primaryCare'){
26166                    jQuery(selector).html(data.general['total-primary-care-physicians']);
26167                }else if(doctorType === 'specialist'){
26168                    jQuery(selector).html(data.general['total-specialty-care-physicians']);
26169                }else if(doctorType === 'appdoctors') {
26170                    if (data.general && data.general.total) {
26171                        jQuery(selector).html(data.general.total);
26172                    } else {
26173                        jQuery(selector).html(0);
26174                    }
26175                }else{
26176                    jQuery(selector).html(data.general['total']);
26177                }
26178            }
26179        });
26180    },
26181
26182    dataCountCheck : function(){
26183        var header = $('#pd-' + this.componentID).closest('.profiledeck').find('h2#doctors');
26184        if(this.mode ==="EDIT"){
26185            if(this.deckType ==="staff"){
26186                header.text("No staff currently associated with this clinic.");
26187            }
26188            else{
26189                header.text("No doctors currently associated with this clinic.");
26190            }
26191
26192        }
26193        else{
26194            header.empty();
26195        }
26196
26197    },
26198
26199    preProcessData: function(data){
26200        var that = this;
26201        var combinedData = [];
26202        $.each(data, function(key, value) {
26203            combinedData = combinedData.concat(value);
26204        });
26205        // de-dupe the data with unique npi values
26206        var dedupedData = SHC.util.dedupeArrayOfObj(combinedData, 'npi');
26207        var processedData = {'shc': [], 'uha': []};
26208        for(var i = 0; i < dedupedData.length; i++) {
26209            if(dedupedData[i].orgName === "shc"){
26210                processedData.shc.push(dedupedData[i]);
26211            }
26212            else if(dedupedData[i].orgName === "uha"){
26213                processedData.uha.push(dedupedData[i]);
26214            }
26215        }
26216        var shc_data =[], uha_data=[];
26217        var data_count_shc = 0;
26218        var data_count_uha = 0;
26219        that.setOrgCount(processedData);
26220
26221        if(this.profileType === 'uha'){
26222            if(processedData.uha){
26223                uha_data = SHC.util.shuffle(processedData.uha);
26224                data_count_uha = uha_data.length;
26225            }
26226        }else if(this.profileType === 'shc'){
26227            if(processedData.shc){
26228                shc_data = SHC.util.shuffle(processedData.shc);
26229                data_count_shc = shc_data.length;
26230
26231            }
26232        }
26233        else {
26234            if((processedData.shc && processedData.uha) && (processedData.shc.length + processedData.uha.length === 8) && SHC.ui.screenMode === 'large'){
26235                shc_data = SHC.util.shuffle(processedData.shc);
26236                data_count_shc = shc_data.length;
26237
26238                uha_data = SHC.util.shuffle(processedData.uha);
26239                data_count_uha = uha_data.length;
26240
26241
26242                shc_data = shc_data.slice(0, shc_data.length);
26243                uha_data = uha_data.slice(0, uha_data.length);
26244            } else{
26245                if(processedData.shc){
26246                    shc_data = SHC.util.shuffle(processedData.shc);
26247                    data_count_shc = shc_data.length;
26248                    if (shc_data.length === 8 && !processedData.uha && SHC.ui.screenMode === 'large')  {
26249                        SHC.ui.ProfileDeck.ORG_COUNT.shc_count = 8;
26250                        SHC.ui.ProfileDeck.COUNT[SHC.ui.screenMode] = 8;
26251                        this.count = 8;
26252                        shc_data = shc_data.slice(0, 8);
26253                    } else {
26254                        shc_data = shc_data.slice(0, SHC.ui.ProfileDeck.ORG_COUNT.shc_count);
26255                    }
26256                }
26257
26258                if(processedData.uha){
26259                    uha_data = SHC.util.shuffle(processedData.uha);
26260                    data_count_uha = uha_data.length;
26261                    if(uha_data.length === 8 && !processedData.shc && SHC.ui.screenMode === 'large') {
26262                        SHC.ui.ProfileDeck.ORG_COUNT.uha_count = 8;
26263                        SHC.ui.ProfileDeck.COUNT[SHC.ui.screenMode] = 8;
26264                        this.count = 8;
26265                        uha_data = uha_data.slice(0, 8);
26266                    } else {
26267                        uha_data = uha_data.slice(0 , SHC.ui.ProfileDeck.ORG_COUNT.uha_count);
26268                    }
26269                }
26270            }
26271        }
26272        this.globalDataCount = data_count_shc + data_count_uha;
26273        var final_data = shc_data.concat(uha_data);
26274        return final_data;
26275    },
26276    setOrgCount: function(data){
26277        if(SHC.ui.screenMode !== 'large'){
26278            SHC.ui.ProfileDeck.ORG_COUNT.shc_count = 4;
26279            SHC.ui.ProfileDeck.ORG_COUNT.uha_count = 3;
26280        }
26281        if(data.shc) {
26282            if (data.shc.length < SHC.ui.ProfileDeck.ORG_COUNT.shc_count) {
26283                SHC.ui.ProfileDeck.ORG_COUNT.shc_count = data.shc.length;
26284                SHC.ui.ProfileDeck.ORG_COUNT.uha_count = SHC.ui.ProfileDeck.COUNT[SHC.ui.screenMode] - SHC.ui.ProfileDeck.ORG_COUNT.shc_count;
26285            }
26286        }else{
26287            SHC.ui.ProfileDeck.ORG_COUNT.uha_count = 7;
26288        }
26289        if(data.uha) {
26290            if (data.uha.length < SHC.ui.ProfileDeck.ORG_COUNT.uha_count) {
26291                SHC.ui.ProfileDeck.ORG_COUNT.uha_count = data.uha.length;
26292                SHC.ui.ProfileDeck.ORG_COUNT.shc_count = SHC.ui.ProfileDeck.COUNT[SHC.ui.screenMode] - SHC.ui.ProfileDeck.ORG_COUNT.uha_count;
26293            }
26294        }
26295        else{
26296            SHC.ui.ProfileDeck.ORG_COUNT.shc_count = 7;
26297        }
26298
26299    },
26300
26301    arrayRemove:function(idx , data){
26302        var dataCopy =[];
26303        for(var i =0; i<data.length; i++){
26304            if(i !== idx+1){
26305                dataCopy.push(data[i]);
26306            }
26307        }
26308        return dataCopy;
26309    },
26310    mobileNavButtonCheck:function(){
26311        var tileParent = '#pd-' + this.componentID + '.row.pd-component.clearboth.small ';
26312        var tileSelector = '.col-xl-3.col-lg-3.col-md-3.col-sm-6.col-xs-6';
26313        var navButtonsParent = $('#pd-' + this.componentID + '.row.pd-component.clearboth.small ').parent().find('.navigationButtons');
26314
26315        var navCount = navButtonsParent.find('li').length;
26316        var tileCount = $(tileParent).find(tileSelector).length;
26317
26318        if (navCount < tileCount){
26319            var startIndex = navCount;
26320            for(var i=0; i < (tileCount - navCount); i++){
26321                navButtonsParent.append('<li index="' + startIndex + '"></li>');
26322                startIndex++;
26323            }
26324        }
26325    },
26326    setViewAllButtonContainer:function(){
26327        var $viewProfileButton = this.detailDiv.find('a.btn:contains("View Full Profile")');
26328        if($viewProfileButton.length > 0) {
26329            this.detailDiv.find('.container').append($viewProfileButton);
26330        }
26331    }
26332});
26333
26334SHC.Namespace(SHC, "SHC.ui.Search.DirectoryParser");
26335SHC.ui.Search.DirectoryParser = new SHC.Class();
26336
26337SHC.ui.Search.DirectoryParser.include({
26338    init: function() { 
26339        var match,
26340            pl     = /\+/g,  // Regex for replacing addition symbol with a space
26341            search = /([^&=]+)=?([^&]*)/g,
26342            decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); },
26343            query  = window.location.search.substring(1);
26344
26345        this.urlParams = {};
26346        while (match = search.exec(query)) {
26347           this.urlParams[decode(match[1])] = decode(match[2]);
26348        }
26349        this.condition = this.urlParams.condition;
26350        this.clinic = this.urlParams.clinic;
26351        this.stub = this.urlParams.stub;
26352        
26353    },
26354
26355    getParams: function() {
26356        var that = this;
26357        var paramObj = {
26358            condition: that.condition,
26359            clinic: that.clinic,
26360            stub: that.stub
26361        };
26362        return paramObj;
26363        
26364    }
26365
26366});
26367SHC.Namespace(SHC, "SHC.ui.Search.ResultsBinder");
26368SHC.ui.Search.ResultsBinder = new SHC.Class();
26369SHC.ui.Search.ResultsBinder.counter = 0;
26370SHC.ui.Search.ResultsBinder.profileTileCount = 0;
26371//ONLY for unit tests, Jasmine and PhantomJS cant set the browser object set on the correct context, see forceReloadForSafari function
26372SHC.ui.Search.ResultsBinder.unitTestRun = false;
26373SHC.ui.Search.ResultsBinder.include({
26374    init: function (parent) {
26375        this.self = jQuery(parent);
26376        this.parent = parent;
26377        this.paginationString = "";
26378        this.checkSectionHeadings = "false";
26379        this.$handlebarsTarget = jQuery('#handlebars-target');
26380        this.newTermSuggestion = "";
26381        this.badTermCorrection = "";
26382        this.firstPage = "";
26383        this.LIST_VIEW = "list";
26384        this.MAP_VIEW = "map";
26385        this.CLINIC_MAP_URL_PREFIX = "/bin/api/v2/content/clinicmap?query=";
26386        this.controlTitle = $("#toggle-title");
26387        this.primaryCareDoctorTitles = ["Pediatrician", "Primary care doctor"];
26388        this.clinicPassThroughInfo = SHC.util.getClinicPassThroughInfo();
26389        this.locationPassThroughInfo = SHC.util.getLocationPassThroughInfo();
26390        this.expressCare = 'https://stanfordhealthcare.org/medical-clinics/express-care.html';
26391        this.emergencyServices = 'https://stanfordhealthcare.org/medical-clinics/emergency-department.html';
26392        var searchVer = document.querySelector('meta[name="shc-search-version"]').content || "v1";
26393        this.searchVer = searchVer;
26394        console.log('searchVer (results binder) '+searchVer);
26395        this.cachedSearchServletUrl = "/bin/api/"+searchVer+"/search.json";
26396        this.clinicalTrialsServletUrl = '/bin/api/v1/content/trialsbycondition.json';
26397        this.fromNoResults = false;
26398        this.noResultsZipCode = "";
26399        this.showTrialsInstructions = false;
26400        this.searchPageUrl = SHC.util.isValleycare() ? '/content/valleycare/en/search-results.html' : '/content/shc/en/search-results.html';
26401        this.safariShcaRedirectHashCheck();
26402        this.forceReloadForSafari();
26403        this.captureSearchResultClickEvent();
26404        this.captureSearchDirectoryFilter();
26405    },
26406    /*
26407     * Checks for Browser type Safari.
26408     * Forces reload on return to page using back button to trigger searchbar text population.
26409     */
26410    forceReloadForSafari: function() {
26411        if(SHC.ui.Search.ResultsBinder.unitTestRun === false) {
26412            if ($.browser.safari === true) {
26413                $(window).bind("pageshow", function (event) {
26414                    if (event.originalEvent.persisted) {
26415                        window.location.reload();
26416                    }
26417                });
26418            }
26419        }
26420    },
26421
26422    /*
26423     * Fixes up the query term and sends it to getJSON
26424     * This is for a search that wipes the page and does not do f
26424ilters or pagination
26425     */
26426    startSearch: function (doer, onSuccessCallback) {
26427        //create Q, add doer and pass to getJSON
26428        var searchterm = location.pathname.match(/\.html\/(.*)/);
26429        // check for suggestion in data attr
26430        var spellingSuggestion = jQuery('#search-results-page').attr('data-search-spelling-suggestion');
26431
26432        if (spellingSuggestion !== null && spellingSuggestion !== "" && typeof spellingSuggestion !== 'undefined') {
26433            searchterm[1] = spellingSuggestion; // Redefine query if there is a spelling suggestion
26434        }
26435        if (searchterm === null || (searchterm.length > 1 && searchterm[1] === "") || searchterm.indexOf("Browse") !== -1) {
26436            searchterm = "&sp_s=sp_displayName"; // sort by alpha
26437            if(GLOBAL_DIRECTORY_OBJECT === "organic_clinical_trials") {
26438                this.showTrialsInstructions = true;
26439                searchterm += "&x1=sp_status&q1=RECRUITING";
26440            }
26441            if (GLOBAL_DIRECTORY_OBJECT === "organic_phys") {
26442                if(GLOBAL_SEARCH_RESULTS_TEMPLATE && GLOBAL_SEARCH_RESULTS_TEMPLATE === "/apps/shca/templates/searchresults"){
26443                    if(GLOBAL_MICROSITE_SRC === 'intel') {
26444                        searchterm = "&sp_s=sp_accept_new_patien|sp_clinics_mapped|sp_random&x1=sp_prim_care_phy&q1=true&x35=sp_ob_gyn_only&q35=false";
26445                    } else {
26446                        searchterm = "&sp_s=sp_accept_new_patien|sp_clinics_mapped|sp_random&x1=sp_prim_care_phy&q1=true";
26447                    }
26448                } else {
26449                    searchterm = "&sp_s=sp_lastName&x1=sp_spec_care_phy&q1=true";
26450                }
26451            }
26452            if (GLOBAL_DIRECTORY_OBJECT === "organic_clinics") {
26453                searchterm = "&sp_s=sp_sortableName&x1=sp_spec_care_clinic&q1=true";
26454            }
26455            if (GLOBAL_DIRECTORY_OBJECT === "organic_newsroom") {
26456                searchterm = "&sp_s=sp_date";
26457            }
26458            if (SHC.ui.Search.DirectoryUtil.isNewsroomLandingPage()) {
26459                searchterm = "&sp_s=sp_date";
26460                searchterm += this.getNewsroomLandingType();
26461            }
26462            // if this isn't a directory page and we don't have a search term, show a message saying no results found
26463            if (typeof GLOBAL_DIRECTORY_OBJECT === "undefined" || GLOBAL_DIRECTORY_OBJECT === "") {
26464                jQuery("#search-results-page #null-results-container").show();
26465                jQuery("#search-results-page .view-more-results-btn").hide();
26466                return;
26467            }
26468        } else {
26469            // Check for the directory case
26470            if (typeof GLOBAL_DIRECTORY_OBJECT !== "undefined" && GLOBAL_DIRECTORY_OBJECT !== "") {
26471                $('.communityDoctors').remove();
26472                var defaultToggleFilter = "";
26473                var requestMapParam = "";
26474                var requestMap = [];
26475                var incomingSortPieces = searchterm[1].split("&");
26476                var lockedLabelString = incomingSortPieces[1];
26477                var trialStatusString = incomingSortPieces[2];
26478                if (trialStatusString && trialStatusString.indexOf('%7C') > -1) {
26479                    trialStatusString = trialStatusString.split('%7C')[0];
26480                } else if (trialStatusString && trialStatusString.indexOf('|') > -1) {
26481                    trialStatusString = trialStatusString.split('|')[0];
26482                }
26483                var sortAlpha = "&sp_s=sp_title";
26484                var realSearchTerm;
26485                if (searchterm && searchterm[1]) {
26486                    var splitSearchterm = decodeURIComponent(searchterm[1]).split('|');
26487                    if (splitSearchterm && splitSearchterm[3]) {
26488                        realSearchTerm = splitSearchterm[3];
26489                    } else {
26490                        realSearchTerm = searchterm[1];
26491                    }
26492                }
26493                if (GLOBAL_DIRECTORY_OBJECT === "organic_phys") {
26494                    sortAlpha = "&sp_s=sp_lastName";
26495                    if(SHC.util.primaryCareKeywords.indexOf(decodeURIComponent(realSearchTerm.toString().toLowerCase())) > -1){
26496                        requestMapParam = 'sp_prim_care_phy';
26497                        requestMap[requestMapParam] = true;
26498                        if (requestMap['sp_spec_care_phy']) {
26499                            delete requestMap['sp_spec_care_phy'];
26500                        }
26501                        this.filter(doer, requestMap);
26502                        return;
26503                    } else {
26504                        if (GLOBAL_SEARCH_RESULTS_TEMPLATE.indexOf('shca') > 0){
26505                            defaultToggleFilter = "&x1=sp_prim_care_phy&q1=true";
26506                        }else {
26507                            defaultToggleFilter = "&x1=sp_spec_care_phy&q1=true";
26508                        }
26509                    }
26510                }
26511                if (GLOBAL_DIRECTORY_OBJECT === "organic_clinics") {
26512                    sortAlpha = "&sp_s=sp_sortableName";
26513                    if(SHC.util.primaryCareKeywords.indexOf(decodeURIComponent(realSearchTerm.toString().toLowerCase())) > -1){
26514                        requestMapParam = 'sp_prim_care_clinic';
26515                        requestMap[requestMapParam] = true;
26516                        if (requestMap['sp_spec_care_clinic']) {
26517                            delete requestMap['sp_spec_care_clinic'];
26518                        }
26519                        if (requestMap['sp_other_service']) {
26520                            delete requestMap['sp_other_service'];
26521                        }
26522                        this.filter(doer, requestMap);
26523                        return;
26524                    } else {
26525                        defaultToggleFilter = "&x1=sp_spec_care_clinic&q1=true";
26526                    }
26527                }
26528                if (lockedLabelString) {
26529                    if (GLOBAL_DIRECTORY_OBJECT === "organic_clinical_trials" && incomingSortPieces && incomingSortPieces[2]) {
26530                        var passthrough = lockedLabelString + "&" + incomingSortPieces[2];
26531                        searchterm = this.dealWithLockedLabels(passthrough);
26532                    } else {
26533                        searchterm = this.dealWithLockedLabels(lockedLabelString);
26534                    }
26535                    var decodedSplit = decodeURIComponent(lockedLabelString).split('|');
26536                    if (decodedSplit.length < 4 || decodedSplit.length === 4 && decodedSplit[3] === "") { //verify there is no searchTerm in the passthrough
26537                        searchterm += sortAlpha;
26538                    }
26539                    if (trialStatusString) { // this assumes there will never be an incoming status without a lock
26540                        searchterm += "&x23=sp_status&q23=" + trialStatusString;
26541                    }
26542                } else if (GLOBAL_DIRECTORY_OBJECT === "organic_clinical_trials") {
26543                    //clinical trials exact match searchterm
26544                    searchterm = "&x1=sp_status&q1=RECRUITING&x13=sp_trialLocks&q13=" + searchterm[1];
26545                }
26546                else {
26547                    searchterm = "&q=" + searchterm[1];
26548                }
26549
26550                searchterm = searchterm + defaultToggleFilter;
26551            } else {
26552                searchterm = "&q=" + searchterm[1];
26553            }
26554        }
26555        if (typeof GLOBAL_DIRECTORY_OBJECT !== "undefined" && GLOBAL_DIRECTORY_OBJECT !== "") {
26556            doer = GLOBAL_DIRECTORY_OBJECT;
26557        } else if (!doer) {
26558            doer = "organic";
26559        }
26560        var filter = SHC.ui.Search.DirectoryUtil.getQueryVariable("doer");
26561        /** open more-dropdown, update directory-control title, and highlight more link if coming from a directory page
26562         * where a more filter was selected. **/
26563        if(filter && !(SHC.ui.Search.DirectoryUtil.processedFilter)) {
26564            doer = filter;
26565            if(doer === "organic_events" || doer === "vc_events") {
26566                $(".control-item.all").removeClass("active");
26567                $(".control-item.events").addClass("active");
26568                $(".more-container").show();
26569                $(".more-symbol.closed").removeClass("closed").addClass("open");
26570            }
26571            else if(doer === "organic_clinical_trials") {
26572                $(".control-item.all").removeClass("active");
26573                $(".control-item.trials").addClass("active");
26574                $(".more-container").show();
26575                $(".more-symbol.closed").removeClass("closed").addClass("open");
26576            }
26577            else if(doer === "organic_stories") {
26578                $(".control-item.all").removeClass("active");
26579                $(".control-item.stories").addClass("active");
26580                $(".more-container").show();
26581                $(".more-symbol.closed").removeClass("closed").addClass("open");
26582            }
26583            this.controlTitle.text(SHC.ui.Search.DirectoryUtil.getDirectoryControlTitleForDoer(doer));
26584        }
26585        // do directory page if this global is set, only include searchterm if there is one
26586        var Q;
26587        if(searchterm === null) {
26588            Q = "?do=" + doer;
26589        }
26590        else {
26591            Q = "?do=" + doer + searchterm;
26592        }
26593
26594        //This will add the handler of the microsites if we really need it.
26595        if(typeof GLOBAL_MICROSITE_SRC !== "undefined" && GLOBAL_MICROSITE_SRC !== "") {
26596            Q += '&src=' + GLOBAL_MICROSITE_SRC;
26597        }
26598        // doesn't actually return JSON, just fetches it from S&P
26599        this.getJSON(doer, Q, false, true, onSuccessCallback);
26600    },
26601    /**
26602     * A search that appends results to the page. The Q is the query string from S&P
26603     */
26604    paginate: function (Q) {
26605        //get doer from Q
26606        if ((SHC.ui.Search.DirectoryUtil.isClinicDirectoryPage() && this.getActiveView() !== this.MAP_VIEW)
26607                || SHC.ui.Search.DirectoryUtil.isNewsroomDirectoryPage() || SHC.ui.Search.DirectoryUtil.isNewsroomLandingPage()) {
26608
26609            //Q will be the desired page number
26610            if (SHC.ui.Search.savedClinicSearch) {
26611                SHC.ui.Search.savedClinicSearch = this.setFrontendPaginationPageNums(SHC.ui.Search.savedClinicSearch, parseInt(Q));
26612                this.searchSuccessCallback(SHC.ui.Search.savedClinicSearch, "organic_clinics", false, true, false, null, SHC.ui.Search.savedQ);
26613            } else if (SHC.ui.Search.savedNewsroomSearch) {
26614                SHC.ui.Search.savedNewsroomSearch = this.setFrontendPaginationPageNums(SHC.ui.Search.savedNewsroomSearch, parseInt(Q));
26615                this.searchSuccessCallback(SHC.ui.Search.savedNewsroomSearch, "organic_newsroom", false, true, false, null, SHC.ui.Search.savedQ);
26616            }
26617        } else {
26618            if (Q) {
26619                var firstSplit = Q.split("do=");
26620                var secondSplit = firstSplit[1].split("&");
26621                var doer = secondSplit[0];
26622                this.getJSON(doer, Q, true);
26623            }
26624        }
26625    },
26626    /**
26627     * A search that wipes the page, but stays on the same tab. The Q comes from S&P
26628     */
26629    filterAlpha: function (Q) {
26630        //get doer from Q
26631        if (Q) {
26632            var firstSplit = Q.split("do=");
26633            var secondSplit = firstSplit[1].split(";");
26634            var doer = secondSplit[0];
26635            this.getJSON(doer, Q, false);
26636        }
26637    },
26638    getSearchTerm: function() {
26639        var searchterm = location.pathname.match(/\.html\/(.*)/);
26640        if(searchterm !== null && searchterm.length > 1) {
26641            // remove trailing "&&" as this is not part of the search term
26642            if(searchterm[1].indexOf("&&") > -1) {
26643                return searchterm[1].substr(0, searchterm[1].indexOf("&&"));
26644            }
26645
26646            return searchterm[1];
26647        }
26648
26649        return null;
26650    },
26651    buildFilterString: function(map) {
26652        var filterString = "",
26653            pipeCount = 0,
26654            value;
26655
26656        if (typeof map === "string"){
26657            filterString = map;
26658        } else {
26659            var i = 1;
26660            // Iterate over the key/value map passed in and build the queries based
26661            // on their values. This loop handles 3 scenarios:
26662            // 1. If the item's value contains "pipe" characters then it is a query
26663            //    with multiple values and need to be encoded
26664            // 2. If the item is "sp_s" then it is a sort argument
26665            // 3. Otherwise, the item is a single value query
26666            for(var key in map) {
26667                if (map.hasOwnProperty(key)) {
26668                    value = map[key];
26669                    if(key === 'sp_s') {
26670                        filterString += "&sp_s=" + map['sp_s'];
26671                    }
26672                    else if(key === 'sp_q_location') {
26673                        filterString += "&sp_q_location_" + i + "=" + map['sp_q_location'];
26674
26675                    }
26676                    else if(key === 'sp_x') {
26677                        filterString += "&sp_x_" + i + "=" + map['sp_x'];
26678
26679                    }
26680                    else if(key === 'sp_q_max') {
26681                        filterString += "&sp_q_max_" + i + "=" + map['sp_q_max'];
26682                        // sp_q_location, xp_x, and sp_q_max need the same number, so only increment after max
26683                        i += 1;
26684                    }
26685                    else if(key === 'campaignFilter') {
26686                        filterString += "&campaignFilter=" + map['campaignFilter'];
26687                    }
26688                    else {
26689                        var query = value;
26690                        if(typeof value === 'string' && value.indexOf('|') > -1) {
26691                            var groupTitles = encodeURIComponent(jQuery('<textarea />').html(value).val()),
26692                                groupTitlesArray = [];
26693                            pipeCount = (groupTitles.match(/%7C/)) ? groupTitles.split('%7C').length : 0;
26694                            // truncate the list to only include up to 5 options
26695                            // this is done for two reasons:
26696                            // 1. S&P does not seem to like it when too many options are provideddoctorSpecialtiesLoaded
26697                            // 2. The URL can only be a limited length
26698                            if (pipeCount > 4) {
26699                                groupTitlesArray = groupTitles.split('%7C');
26700                                while (groupTitlesArray.length > 5) {
26701                                    groupTitlesArray.pop();
26702                                }
26703                                groupTitles = groupTitlesArray.join('%7C');
26704                            }
26705                            query = groupTitles;
26706                        }
26707
26708                        if(typeof value === 'object') {
26709                            var x = i;
26710                            for (x=0; x < value.length; x++) {
26711                                filterString += "&x" + i + "=" + key + "&q" + i + "=" + encodeURIComponent(value[x]);
26712                                i++;
26713                            }
26714                        } else{
26715                            filterString += "&x" + i + "=" + key + "&q" + i + "=" + encodeURIComponent(decodeURIComponent(query));
26716                            i++;
26717                        }
26718
26719                    }
26720                }
26721            }
26722        }
26723
26724        return filterString;
26725    },
26726    /**
26727     * A search that constructs a query string from the filter map, which is the object c
26727ontaining
26728     * all of the active/checked filters from the filter box
26729     */
26730    filter: function (doer, map, onSuccessCallback, params) {
26731
26732        var mobileFilter = false,
26733            applyFilter = false,
26734            toggleValueChanged = false,
26735            that = this,
26736            searchFromFilterRail = false;
26737        if (params) {
26738            toggleValueChanged = params.toggleValueChanged || false;
26739            mobileFilter = params.mobileFilter || false;
26740            applyFilter = params.applyFilter || false;
26741            searchFromFilterRail = params.searchFromFilterRail || false;
26742        }
26743
26744        //prepare Q and doer and feed to getJSON
26745        var searchterm = location.pathname.match(/\.html\/(.*)/);
26746        var incomingSortPieces;
26747        if(searchterm && searchterm[1])  {
26748            incomingSortPieces = searchterm[1].split("&");
26749        }
26750        if (searchterm && searchterm[1] && location.pathname.match(/&gclid=(.*)/)) {
26751            searchterm[1] = SHC.util.getURLSearchTerm(location.pathname);
26752        }
26753        var hasSortParam = map && map['sp_s'];
26754        var removeObGynParam = false;
26755
26756        // check for suggestion in data attr
26757        var spellingSuggestion = jQuery('#search-results-page').attr('data-search-spelling-suggestion');
26758        if (spellingSuggestion !== null && spellingSuggestion !== "" && typeof spellingSuggestion !== 'undefined') {
26759            searchterm[1] = spellingSuggestion; // Redefine query if there is a spelling suggestion
26760        }
26761        if (searchterm === null || (searchterm.length > 1 && searchterm[1] === "") || searchterm.indexOf("Browse") !== -1) {
26762            if(!hasSortParam){
26763                searchterm = "&sp_s=sp_displayName";
26764                if (GLOBAL_DIRECTORY_OBJECT === "organic_phys") {
26765                    if(SHC.ui.Search.DirectoryUtil.isPrimaryCareToggleActive() && SHC.ui.Search.DirectoryUtil.isMicrosite()) {
26766                        if(GLOBAL_MICROSITE_SRC === 'intel') {
26767                            searchterm = "&sp_s=sp_accept_new_patien|sp_clinics_mapped|sp_random&x35=sp_ob_gyn_only&q35=false";
26768                        } else {
26769                            searchterm = "&sp_s=sp_accept_new_patien|sp_clinics_mapped|sp_random";
26770                        }
26771                    } else {
26772                        searchterm = "&sp_s=sp_lastName";
26773                    }
26774                }
26775                if (GLOBAL_DIRECTORY_OBJECT === "organic_clinics") {
26776                    searchterm = "&sp_s=sp_sortableName";
26777                }
26778                if (GLOBAL_DIRECTORY_OBJECT === "organic_newsroom") {
26779                    searchterm = "&sp_s=sp_date";
26780                }
26781                if (SHC.ui.Search.DirectoryUtil.isNewsroomLandingPage()) {
26782                    searchterm = "&sp_s=sp_date";
26783                    searchterm += this.getNewsroomLandingType();
26784                }
26785            }
26786            if(GLOBAL_DIRECTORY_OBJECT === "organic_clinical_trials") {
26787                if (typeof map === 'object') {
26788                    if (Object.keys(map).length === 0 || Object.keys(map).length === 1 && map.sp_status) { //OR case is default filter upon clicking "reset filters"
26789                        this.showTrialsInstructions = true;
26790                    }
26791                } else { //special case for copy-pasting URL in IE
26792                    if ((map && map.match(/sp_/g).length == 1 && map.indexOf("sp_status") !== -1) || map === "") {
26793                        this.showTrialsInstructions = true;
26794                    }
26795                }
26796            }
26797        } else {
26798            if (typeof GLOBAL_DIRECTORY_OBJECT !== "undefined" && GLOBAL_DIRECTORY_OBJECT !== "") {
26799                var lockedLabelString = searchterm[1].split("&")[1];
26800                if (lockedLabelString) {
26801                    if (GLOBAL_DIRECTORY_OBJECT === "organic_clinical_trials" && incomingSortPieces && incomingSortPieces[2]) {
26802                        var passthrough = lockedLabelString + "&" + incomingSortPieces[2];
26803                        searchterm = this.dealWithLockedLabels(passthrough);
26804                    } else {
26805                        searchterm = this.dealWithLockedLabels(lockedLabelString);
26806                    }
26807                    if(GLOBAL_DIRECTORY_OBJECT === "organic_clinical_trials" && incomingSortPieces && incomingSortPieces[2]) {
26808                        var trialStatusString = incomingSortPieces[2];
26809                        if (trialStatusString && trialStatusString.indexOf('%7C') > -1) {
26810                            trialStatusString = trialStatusString.split('%7C')[0];
26811                        } else if (trialStatusString && trialStatusString.indexOf('|') > -1) {
26812                            trialStatusString = trialStatusString.split('|')[0];
26813                        }
26814                        if (trialStatusString) { // this assumes there will never be an incoming status without a lock
26815                            if((typeof map === 'string' && map.indexOf("sp_status") === -1) ||
26816                                (typeof map === 'object' && !map.sp_status)) {
26817                                searchterm += "&x23=sp_status&q23=" + trialStatusString;
26818                            }
26819                        }
26820                    }
26821                    var sortAlpha = "&sp_s=sp_title";
26822                    if (GLOBAL_DIRECTORY_OBJECT === "organic_phys"){
26823                        sortAlpha = "&sp_s=sp_lastName";
26824                    } else if (GLOBAL_DIRECTORY_OBJECT === "organic_clinics") {
26825                        sortAlpha = "&sp_s=sp_sortableName";
26826                    }
26827                    var decodedSplit = decodeURIComponent(lockedLabelString).split('|');
26828                    if (decodedSplit.length < 4 || decodedSplit.length === 4 && decodedSplit[3] === "") { //verify there is no searchTerm in the passthrough
26829                        searchterm += sortAlpha;
26830                    }
26831                } else {
26832                    if (GLOBAL_DIRECTORY_OBJECT === "organic_clinical_trials" && !SHC.nonExactMatchSearch) {
26833                        searchterm = "&x13=sp_trialLocks&q13=" + searchterm[1];
26834                    } else {
26835                        searchterm = "&q=" + searchterm[1];
26836                    }
26837                }
26838
26839                if(GLOBAL_DIRECTORY_OBJECT === "organic_phys" && SHC.ui.Search.DirectoryUtil.isPrimaryCareToggleActive()
26840                    && SHC.ui.Search.DirectoryUtil.isMicrosite()) {
26841                    if(GLOBAL_MICROSITE_SRC === 'intel') {
26842                        searchterm += "&sp_s=sp_accept_new_patien&x35=sp_ob_gyn_only&q35=false";
26843                        removeObGynParam = true;
26844                    } else {
26845                        searchterm += "&sp_s=sp_accept_new_patien";
26846                    }
26847                }
26848            } else {
26849                searchterm = "&q=" + searchterm[1];
26850            }
26851        }
26852
26853        var filterString = this.buildFilterString(map);
26854
26855        var urlHash,
26856            urlString;
26857        urlHash = location.hash;
26858        if (urlHash) { //filterString
26859            urlString = location.origin + location.pathname + location.search;
26860        } else {
26861            urlString = location.href;
26862        }
26863
26864        urlString = urlString.replace("#", ""); // prevent double #
26865        urlString += '#' + filterString;
26866        if(params && params.doctorDistanceQuery) {
26867            params.urlString = urlString;
26868        }
26869
26870        if (filterString) {
26871            urlString += this.addPredictiveParameter(urlString);
26872            history.replaceState({filterState: filterString}, 'filtered', urlString);
26873        } else {
26874            // remove the entire old hash (including the hash symbol)
26875            history.replaceState("", "", location.pathname + location.search);
26876        }
26877
26878        var Q;
26879        if(searchterm === null) {
26880            Q = "?do=" + doer;
26881            //This will add the handler of the microsites if we really need it.
26882            if(SHC.ui.Search.DirectoryUtil.isMicrosite()) {
26883                Q += '&' + GLOBAL_MICROSITE_SRC;
26884            }
26885            Q += filterString;
26886        }
26887        else {
26888            Q = "?do=" + doer + searchterm;
26889            //This will add the handler of the microsites if we really need it.
26890            if(SHC.ui.Search.DirectoryUtil.isMicrosite()) {
26891                Q += '&src=' + GLOBAL_MICROSITE_SRC;
26892            }
26893            Q += filterString;
26894        }
26895
26896        if (removeObGynParam) {
26897            if (Q.indexOf('x1=sp_spec_care_phy') > -1) {
26898                Q = Q.replace('&x35=sp_ob_gyn_only&q35=false', '');
26899                removeObGynParam = false;
26900            }
26901        }
26902
26903        // force a non-exact S&P Q when only status is checked on clinical trials filter rail
26904        if (doer === "organic_clinical_trials"){
26905            var pathArr = location.pathname.match(/\.html\/(.*)/);
26906            var searchTerm = pathArr ? pathArr[1] : "";
26907
26908            var sp_conditions = typeof map === 'object' ? map.sp_conditions : map.indexOf("sp_conditions") > -1;
26909            var sp_trial_id = typeof map === 'object' ? map.sp_trial_id : map.indexOf("sp_trial_id") > -1;
26910            var sp_status = typeof map === 'object' ? map.sp_status : map.indexOf("sp_status") > -1;
26911
26912            if (searchTerm.indexOf("sp_trialLocks") < 0){
26913                if (!sp_conditions && !sp_trial_id){
26914                    if (sp_status){
26915                        if(sp_status === "RECRUITING|NOT_RECRUITING" || map.indexOf("RECRUITING%7CNOT_RECRUITING") > -1) {
26916                            Q = "?do=organic_clinical_trials&x13=sp_trialLocks&q13=" + searchTerm + "&x14=sp_status&q14=RECRUITING|NOT_RECRUITING";
26917                        }else if(sp_status === "NOT_RECRUITING" || map.indexOf("NOT_RECRUITING") > -1){
26918                            Q = "?do=organic_clinical_trials&x13=sp_trialLocks&q13=" + searchTerm + "&x14=sp_status&q14=NOT_RECRUITING";
26919                        }else{
26920                            Q = "?do=organic_clinical_trials&x13=sp_trialLocks&q13=" + searchTerm + "&x14=sp_status&q14=RECRUITING";
26921                        }
26922                    }
26923                    else{
26924                        Q = "?do=organic_clinical_trials&x13=sp_trialLocks&q13=" + searchTerm + "&x14=sp_status&q14=RECRUITING";
26925                    }
26926                }
26927            }
26928            Q += that.addPredictiveParameter(Q);
26929        }
26930        if (params && params.doctorDistanceQuery){
26931            map['sp_q_location'] = params.zip;
26932            map['sp_q_max'] = params.radius;
26933        }
26934        this.saveFilter(map);
26935        this.getJSON(doer, Q, false, false, onSuccessCallback, params);
26936    },
26937    saveFilter: function (obj) {
26938        if (typeof obj !== 'object') {
26939            obj = SHC.util.getMapFromHash(obj)
26940        }
26941        if (typeof obj === 'object') {
26942
26943            //save the current searchterm
26944            var searchTerm = SHC.util.getURLSearchTerm(location.pathname);
26945            if (!SHC.savedSearch){
26946                SHC.savedSearch = {};
26947            }
26948            SHC.savedSearch.searchTerm = searchTerm;
26949
26950            //grab the current toggle
26951            var toggle = $('.filter-toggle .active').closest('.filter-toggle').attr('id');
26952            if (!toggle){
26953                toggle = SHC.savedSearch.toggle;
26954            }
26955
26956            if (toggle) {
26957                if (toggle === "clinics-filter-toggle-specialty-care") {
26958                    delete obj["sp_prim_care_clinic"];
26959                    delete obj["sp_other_service"];
26960                } else if (toggle === "clinics-filter-toggle-primary-care") {
26961                    delete obj["sp_spec_care_clinic"];
26962                    delete obj["sp_other_service"];
26963                } else if (toggle === "clinics-filter-toggle-other-service") {
26964                    delete obj["sp_spec_care_clinic"];
26965                    delete obj["sp_prim_care_clinic"];
26966                } else if (toggle === "doctors-filter-toggle-specialist") {
26967                    delete obj["sp_prim_care_clinic"];
26968                } else if (toggle === "doctors-filter-toggle-primary-care") {
26969                    delete obj["sp_spec_care_phy"];
26970                }
26971                //save filters to the current toggle
26972                SHC.savedSearch[toggle] = obj;
26973            }
26974
26975            // see if filters work in other toggles
26976            SHC.util.saveSearch(obj);
26977
26978            //save off filters
26979            var map = {};
26980            for (var k in obj){
26981                if (obj.hasOwnProperty(k)){
26982                    map[k] = obj[k];
26983                }
26984            }
26985            sessionStorage.setItem('shcFilters', JSON.stringify(map));
26986        }
26987    },
26988    getClinicPassThroughContactInfo: function(clinicUrl, callback) {
26989        jQuery.ajax({
26990            url: '/bin/api/clinic-passthrough/contact-info.json' + clinicUrl,
26991            dataType: "json",
26992            jsonp: 'callback',
26993            contentType: "application/json",
26994            success: function (data) {
26995                callback(data);
26996            },
26997            error: function () {
26998                callback(null);
26999            }
27000        });
27001    },
27002    // doesn't return JSON, just fetches it from S&P, does search stuff and runs the callback if it has one
27003    getJSON: function (doer, Q, isPaginating, calledFromStartSearch, onSuccessCallback, params) {
27004        if (window.location.href.indexOf('tg=save') > 0){
27005            calledFromStartSearch = true;
27006        }
27007
27008        var campaignFilter = SHC.util.getNormalUrlParameter("campaignFilter");
27009        if (campaignFilter && campaignFilter !== "") {
27010            var regex = new RegExp("[?&]campaignFilter(=([^&#]*)|&|#|$)");
27011            Q = Q.replace(regex,"");
27012
27013            var campaignFilters = campaignFilter.split('|');
27014            for (var j = 0; j < campaignFilters.length; j++) {
27015                var currentFilter = campaignFilters[j];
27016                var filter;
27017                for (var i = 0; i < SEARCH_FILTER_GROUP_OBJECT.length; i++) {
27018                    if (SEARCH_FILTER_GROUP_OBJECT[i].name === currentFilter) {
27019                        filter = SEARCH_FILTER_GROUP_OBJECT[i];
27020                    }
27021                }
27022                if (filter) {
27023                    var filterStr = "&" + decodeURIComponent(filter.filter) + "=" + filter.param;
27024                    var zipIndex = Q.indexOf("&sp_q_location");
27025                    if (zipIndex > -1) {
27026                        Q = Q.substr(0, zipIndex) + filterStr + Q.substr(zipIndex);
27027                    } else {
27028                        Q += filterStr;
27029                    }
27030                }
27031            }
27032        }
27033
27034        var mobileFilter = false,
27035            applyFilter = false,
27036            searchFromFilterRail = false;
27037        if (params) {
27038            mobileFilter = params.mobileFilter || false;
27039            applyFilter = params.applyFilter || false;
27040            searchFromFilterRail = params.searchFromFilterRail || false;
27041        }
27042
27043        //optional function parameter
27044        calledFromStartSearch = calledFromStartSearch || false;
27045
27046        if (SHC.searchRequest && SHC.searchRequest.readyState !== 4) {
27047            SHC.searchRequest.abort();
27048        }
27049
27050        var selectedView = false;
27051
27052        if(!params || (!params.radius && !params.zip && !params.doctorDistanceQuery)) {
27053            var zip = SHC.util.getNumericalDistanceVarsFromURL("sp_q_location");
27054            var radius = SHC.util.getNumericalDistanceVarsFromURL("sp_q_max");
27055            var isDoctorDirectoryPage = SHC.ui.Search.DirectoryUtil.isDoctorDirectoryPage();
27056            selectedView = SHC.ui.Search.DirectoryUtil.getSelectedView();
27057            var isMapView = false;
27058
27059            if(selectedView) {
27060                isMapView = selectedView === this.MAP_VIEW;
27061            }
27062            else {
27063                isMapView = this.getActiveView() === this.MAP_VIEW;
27064            }
27065
27066            // if we're coming from a page reload, we need to do the stuff that makeFilterRequest usually does
27067            if(zip && radius && isDoctorDirectoryPage || isDoctorDirectoryPage && isMapView) {
27068                if(!params) {
27069                    params = {};
27070                }
27071                params.radius = radius;
27072                params.zip = zip;
27073                params.doctorDistanceQuery = true;
27074                if(isMapView) {
27075                    params.count = "5000";
27076                }
27077
27078                var indexOfZipVarsInQ = Q.indexOf("&sp_q_location");
27079                var indexOfZipVarsInHash = window.location.hash.indexOf("&sp_q_location");
27080                var openMobileFilters = false;
27081                if(SHC.util.getNormalUrlParameter("openMobileFilters") === "true") {
27082                    openMobileFilters = true;
27083                }
27084                // properly remove zip code vars from url
27085                // so we don't send them in our base query to the servlet
27086                // and not loose other parameters
27087                if(indexOfZipVarsInQ > -1) {
27088                    Q = SHC.util.removeParam("?", "sp_q_location", Q);
27089                    Q = SHC.util.removeParam("?", "sp_q_max", Q);
27090                    history.replaceState({filterState: ""}, "filtered", window.location.hash.substr(0, indexOfZipVarsInHash));
27091                }
27092
27093                if(isPaginating && indexOfZipVarsInHash > -1) {
27094                    history.replaceState({filterState: ""}, "filtered", window.location.hash.substr(0, indexOfZipVarsInHash));
27095                }
27096            }
27097        }
27098
27099        jQuery('.view-more-results-btn').hide();
27100        var that = this;
27101
27102        var url = Q.replace(";", "&");
27103        url = url.replace(/~2F/g, "%2F");
27104        if(doer === "organic_phys" && this.getActiveView() === this.LIST_VIEW){
27105            url += "&sp_c=20";
27106            if(params && params.doctorDistanceQuery && !isPaginating) {
27107                params.count = 20;
27108            }
27109        } else if(doer === "organic_clinics" && this.getActiveView() === this.LIST_VIEW){
27110            //do nothing, the servlet replaces sp_c anyway
27111        } else if(doer === "organic_clinical_trials"){
27112            url += "&sp_c=20";
27113        } else if(SHC.ui.Search.DirectoryUtil.isNewsroomLandingPage() && this.$handlebarsTarget.attr('data-content-type') === 'grid'){
27114            url += "&sp_c=18";
27115        } else if(doer === "organic_newsroom"){
27116            url += "&sp_c=10";
27117        } else if(this.getActiveView() === this.MAP_VIEW){
27118            url += "&sp_c=5000"; // no pagination for map view so need to get all results
27119        } else if (doer !== "organic" && !isPaginating) {
27120            url += "&sp_c=20";
27121        } else if(doer === "organic" && SHC.ui.screenMode === "small"){
27122            url += "&sp_c=10";
27123        }
27124
27125        // check if we came from predictive results
27126        if(window.location.href.indexOf('src=pred') > -1) {
27127            url += "&src=pred";
27128        }
27129
27130        // check if we are on the clinic map view. if so, we need to call a backend servlet, otherwise
27131        // just call search and promote directly
27132        if(SHC.ui.Search.DirectoryUtil.isClinicDirectoryPage() && this.getActiveView() === this.MAP_VIEW) {
27133            url = this.CLINIC_MAP_URL_PREFIX + encodeURIComponent(url);
27134        } else {
27135            url = this.cachedSearchServletUrl + url;
27136        }
27137
27138        // sanity check for v2
27139        if (doer=="organic" && SHC.util.isValleycare() && this.searchVer == "v2") {
27140            doer = "organic_vc";
27141            url = url.replace("do=organic&","do=organic_vc&");
27142        }
27143
27144        var whiteOverlay = $('.search-results-list-overlay');
27145        if (!mobileFilter || (mobileFilter && doer === 'organic_clinical_trials' && whiteOverlay)) {
27146            //when removing filters, want to remove the overlay below the filter panel
27147            if(SHC.ui.screenMode === 'small' && (whiteOverlay && whiteOverlay.hasClass('active')) ){
27148                jQuery('.search-results-list-overlay').removeClass('active');
27149                $body.css("overflow-x", "");
27150                jQuery("#spinner-container").show();
27151            }
27152            that.startWaitState(isPaginating);
27153        }
27154
27155        // if distance query is in params, we want to make a request to the post servlet
27156        if(params && params.doctorDistanceQuery) {
27157            selectedView = SHC.ui.Search.DirectoryUtil.getSelectedView() || this.getActiveView();
27158            // sensible defaults.
27159            var contentData = {
27160                baseQuery: ""+ Q,
27161                view: "",
27162                radius: "",
27163                zip: ""
27164            };
27165            var pred = location.search.indexOf('pred')>0 ? '&src=pred' : '';
27166            if (params.count) {
27167                contentData.baseQuery = Q+pred+'&sp_c='+params.count;
27168            }
27169            if (params.zip) {
27170                contentData.zip = "" + params.zip;
27171            }
27172            if (params.radius) {
27173                contentData.radius = "" + params.radius;
27174            }
27175            if (selectedView === this.MAP_VIEW) {
27176                contentData.view = "map";
27177            }
27178            var contentBody = JSON.stringify(contentData);
27179
27180
27181            SHC.searchRequest = jQuery.ajax({
27182                method: "POST",
27183                url: "/bin/api/v1/content/doctorsbyclinic",
27184                data: contentBody,
27185                dataType: "json",
27186                contentType: "application/json",
27187                success: function (data) {
27188                    var hash = window.location.hash;
27189                    if (params.zip) {
27190                        hash = hash + "&sp_q_location_9=" + params.zip + "&sp_q_max_9=" + params.radius;
27191                        if (openMobileFilters) {
27192                            hash = hash + "&openMobileFilters=true";
27193                        }
27194                    }
27195                    //on replace state in IE to push a hash also removes the search term, this forces the search term to remain
27196                    if(SHC.util.isIE()){
27197                        hash = location.pathname + hash;
27198                    }
27199                    history.replaceState({filterState: ""}, "filtered", hash);
27200                    SHC.util.appendSavedParams(); // run this after history manipulation
27201                    that.searchSuccessCallback(data, doer, calledFromStartSearch, isPaginating, mobileFilter, onSuccessCallback, contentBody);
27202                },
27203                error: function (xhr, status, error) {
27204                    if(status === 'abort') {
27205                        console.log("Ajax manually aborted");
27206                    } else {
27207                        console.log("results binder error:", xhr, status, error);
27208                    }
27209                    if (!that.isSpinnerMapText(status)){
27210                        that.endWaitState();
27211                    }
27212                }
27213            });
27214
27215        } else {
27216            if (calledFromStartSearch) {
27217                SHC.nonExactMatchSearch = false;
27218            }
27219            var executeNonExactMatch = false;
27220            var errorInRequest = false;
27221            SHC.searchRequest = $.ajax({
27222                url: url,
27223                dataType: "jsonp",
27224                jsonp: 'callback',
27225                contentType: "application/json",
27226                success: function (data) {
27227                    var hrefUrl = window.location.href;
27228                    var passthroughCount = 0;
27229                    if(hrefUrl.indexOf('sp_trialLocks') > -1){
27230                        passthroughCount = (hrefUrl.match(/%7C/g) || []).length;
27231                    }
27232
27233                    if(doer === 'organic_clinical_trials' && data.general.total && parseInt(data.general.total) === 0 &&
27234                        hrefUrl.indexOf('sp_trialLocks') === -1 && passthroughCount === 0){
27235                        executeNonExactMatch = true;
27236                    }else{
27237                        data.url = url;
27238                        data.searchFromFilterRail = searchFromFilterRail || false;
27239                        that.searchSuccessCallback(data, doer, calledFromStartSearch, isPaginating, mobileFilter, onSuccessCallback, Q);
27240                    }
27241                },
27242                error: function (xhr, status, error, data) {
27243                    errorInRequest = true;
27244                    if(status === 'abort') {
27245                        console.log("Ajax manually aborted");
27246                    } else {
27247                        console.log("results binder error:", xhr, status, error);
27248                    }
27249                    if (!that.isSpinnerMapText(status)){
27250                        that.endWaitState();
27251                    }
27252                },
27253                complete: function(){
27254                    //make sure the other request is completly done before calling a non exact match
27255                    if(executeNonExactMatch === true && errorInRequest === false){
27256                        SHC.nonExactMatchSearch = true;
27257                        that.clinicalTrialsNotExactMatchGetJSON(url, doer, calledFromStartSearch, isPaginating, mobileFilter, onSuccessCallback, Q, searchFromFilterRail);
27258                    }
27259                }
27260            });
27261        }
27262    },
27263    /**
27264     * Processes the data from a successful ajax call and loads appropriate hbs templates.
27265     * @param data
27266     */
27267    searchSuccessCallback: function(data, doer, calledFromStartSearch, isPaginating, mobileFilter, onSuccessCallback, Q) {
27268        var that = this;
27269
27270        // if no results from a distance query, query again with any radius to show user nearest results
27271        if(SHC.ui.Search.DirectoryUtil.isZipCodeQuery(Q) && this.getActiveView() !== this.MAP_VIEW) {
27272            if (data.general.total === "0" && !this.fromNoResults) {
27273                this.handleNoResultsForDistanceQuery(data, doer, calledFromStartSearch, isPaginating, mobileFilter, onSuccessCallback, Q);
27274                // don't complete the rest of this function as usual, it will be called again after the any distance search completes.
27275                return;
27276            }
27277        } else if (this.getActiveView() === this.MAP_VIEW && data.general.total === "0" && !this.fromNoResults) {
27278            this.handleNoResultsMapView(data, doer, calledFromStartSearch, isPaginating, mobileFilter, onSuccessCallback, Q);
27279            $(window).trigger('noResultsShowingMapView');
27280            return;
27281        }
27282        this.fireResultsFetched();
27283        this.endWaitState();
27284        var activeView = this.getActiveView();
27285        $('.communityDoctors').show();
27286        if (!data) {
27287            return null;
27288        }
27289
27290        // the doer dictates which parse function to use
27291        switch (doer) {
27292            case "organic":
27293            case "organic_vc":
27294                jQuery("#handlebars-target").empty();
27295                // stop here and search for the correctly spelled 
27295word instead if we have one
27296                if (this.handleSpellingSuggestion(data)) {
27297                    break;
27298                }
27299                this.parseOrganic(data, isPaginating);
27300                break;
27301            case "organic_phys":
27302                var requestMap = [];
27303                var exactTitle = '';
27304                var isCleanSearch = false;
27305                var windowHashMap = SHC.util.getMapFromHash(window.location.hash);
27306
27307                if (calledFromStartSearch || (!SHC.ui.Search.disableDrSpecAutofill && Object.keys(windowHashMap).length === 1 && windowHashMap['sp_spec_care_phy'] === 'true')) {
27308                    isCleanSearch = true;
27309                }
27310
27311                if (data.general.query != '' && window.location.hash.indexOf('sp_prim_care_phy') < 0){
27312                    for(var i = 0; i < data.facets.doctorTitles.length; i++){
27313                        if (data.facets.doctorTitles[i].value.toUpperCase() === data.general.query.toUpperCase()){
27314                            exactTitle = data.facets.doctorTitles[i].value;
27315                        }
27316                    }
27317                }
27318                // if specialty physicians comes with === 0 results and the primary care comes with > 0 results
27319                //    activate the primary care results
27320                if(calledFromStartSearch &&
27321                    parseInt(data.general['total-specialty-care-physicians']) === 0 &&
27322                    parseInt(data.general['total-primary-care-physicians']) > 0) {
27323
27324                    requestMap['sp_prim_care_phy'] = true;
27325                    this.filter(doer, requestMap);
27326                    break;
27327                }
27328
27329                // search page comes with primary care toggle active and there are no primary care results
27330                //    activate the specialty care results
27331                if((calledFromStartSearch && (
27332                    parseInt(data.general['total-specialty-care-physicians']) > 0 &&
27333                    parseInt(data.general['total-primary-care-physicians']) === 0)) ||
27334                    (exactTitle != '' && isCleanSearch)) {
27335
27336                   if(exactTitle != '') {
27337                       requestMap['sp_dr_title_groups'] = exactTitle;
27338                   }
27339                    requestMap['sp_spec_care_phy'] = true;
27340                    this.filter(doer, requestMap);
27341                    break;
27342                }
27343                data.selectedAlpha = SHC.util.getAttrValueFromURL('sp_alpha');
27344                data.selectedMedicalCategory = SHC.util.getAttrValueFromURL('sp_med_categories');
27345                data.selectedClinic = this.clinicPassThroughInfo;
27346                if(this.locationPassThroughInfo.address !== null) {
27347                    data.selectedLocation = this.locationPassThroughInfo.address;
27348                }
27349                data.selectedPrimaryCare = SHC.util.getAttrValueFromURL('sp_prim_care_types');
27350                data.selectedDoctorType = SHC.util.getAttrValueFromURL('sp_dr_titles');
27351                data.selectedGender = SHC.util.getAttrValueFromURL('sp_gender');
27352                data.selectedLanguage = SHC.util.getAttrValueFromURL('sp_language');
27353                data.selectedDistance = SHC.util.getNumericalDistanceVarsFromURL('sp_q_max');
27354                data.selectedZipCode = SHC.util.getNumericalDistanceVarsFromURL('sp_q_location');
27355                data.selectedSpecialty = SHC.util.getAttrValueFromURL('sp_dr_title_groups');
27356
27357                // If the user selected "Any Distance" then the value will be 10000
27358                if(data.selectedDistance === "10000") {
27359                    data.selectedDistance = "Any Distance";
27360                }
27361                else if(data.selectedZipCode && data.selectedDistance) {
27362                    // if there is a zip code and selected distance, add mi to the end for the hbs template
27363                    data.selectedDistance = data.selectedDistance + " mi";
27364                }
27365                if(this.clinicPassThroughInfo && this.clinicPassThroughInfo.clinicUrl) {
27366                    this.getClinicPassThroughContactInfo(this.clinicPassThroughInfo.clinicUrl,
27367                        function(clinicContactInfo) {
27368                            // clearing handlebars right before we load the new ones here
27369                            // because if they are cleared prior to fetching the clinic
27370                            // pass through contact info there is a short window where there
27371                            // is no search result content causing the page to flicker
27372
27373                            if(!mobileFilter) {
27374                                that.$handlebarsTarget.empty();
27375                                data.selectedClinic.contactInfo = clinicContactInfo;
27376                                that.parsePhys(data, isPaginating, activeView);
27377                                that.loadFilterHandlebars(data);
27378                            }
27379                        }
27380                    );
27381                } else {
27382                    if (!mobileFilter) {
27383                        this.$handlebarsTarget.empty();
27384                        $('.footer-margin').css('margin-top', '40px');
27385                        this.parsePhys(data, isPaginating, activeView);
27386                    }
27387                }
27388                break;
27389            case "organic_clinics":
27390                if (activeView !== that.MAP_VIEW && !data.isPaginated ) {
27391                    SHC.ui.Search.savedQ = Q;
27392                    data = that.paginateClinics(data);
27393                } else if (activeView === that.MAP_VIEW) {
27394                    SHC.ui.Search.savedQ = "refetch data";
27395                }
27396                data.selectedServiceType = SHC.util.getAttrValueFromURL('sp_other_servc_types');
27397                data.selectedAlpha = SHC.util.getAttrValueFromURL('sp_alpha');
27398                data.selectedMedicalCategory = SHC.util.getAttrValueFromURL('sp_med_categories');
27399                data.selectedClinicSpecialty = SHC.util.getAttrValueFromURL('sp_dr_title_groups');
27400                data.selectedDistance = SHC.util.getNumericalDistanceVarsFromURL('sp_q_max');
27401                data.selectedZipCode = SHC.util.getNumericalDistanceVarsFromURL('sp_q_location');
27402                // If the user selected "Any Distance" then the value will be 10000
27403                if(data.selectedDistance === "10000") {
27404                    data.selectedDistance = "Any Distance";
27405                }
27406                else if(data.selectedZipCode && data.selectedDistance) {
27407                    // if there is a zip code and selected distance, add mi to the end for the hbs template
27408                    data.selectedDistance = data.selectedDistance + " mi";
27409                }
27410                data.urgentLinks = {
27411                    expressCare: this.expressCare,
27412                    emergencyServices: this.emergencyServices
27413                };
27414                var primaryClinicCount = parseInt(data.general['total-primary-care-clinics']);
27415                var specClinicCount = parseInt(data.general['total-specialty-care-clinics']);
27416                var otherClinicCount = parseInt(data.general['total-other
27416-service-clinics']);
27417
27418                if(calledFromStartSearch) {
27419                    var requestMapParam = '';
27420                    var getNewResults = false;
27421                    var requestMapClinic = [];
27422                    var filterToggleInUrl = '';
27423
27424                    if (window.location.href.indexOf('&q1=') > window.location.href.indexOf('&x1=')) {
27425                        var extractToggle = window.location.href.split('&x1=');
27426                        extractToggle = extractToggle[1].split('&q1=');
27427                        filterToggleInUrl = extractToggle[0];
27428                    }
27429
27430                    if (activeView === that.LIST_VIEW) {
27431                        if (!mobileFilter) {
27432                            that.$handlebarsTarget.empty();
27433                            if (that.fromNoResults) {
27434                                data.noResultsZipCode = that.noResultsZipCode;
27435                                that.loadTemplate("#handlebars-target", data, JST["directory-handlebars/clinics-filtered-list-template.hbs"]);
27436                                that.adjustDomForMobile();
27437                                that.fromNoResults = false;
27438                                data.noResultsZipCode = "";
27439                            }
27440                            else {
27441                                that.loadTemplate("#handlebars-target", data, JST["directory-handlebars/clinics-filtered-list-template.hbs"]);
27442                                that.adjustDomForMobile();
27443                            }
27444                        }
27445                    }
27446
27447                    if ((filterToggleInUrl === '' || filterToggleInUrl === 'sp_spec_care_clinic') && specClinicCount === 0) {
27448                        if (primaryClinicCount > 0) {
27449                            getNewResults = true;
27450                            requestMapParam = 'sp_prim_care_clinic';
27451                        } else if (otherClinicCount > 0) {
27452                            getNewResults = true;
27453                            requestMapParam = 'sp_other_service';
27454                        }
27455                    } else if (filterToggleInUrl === 'sp_prim_care_clinic' && primaryClinicCount === 0) {
27456                        if (otherClinicCount > 0) {
27457                            getNewResults = true;
27458                            requestMapParam = 'sp_other_service';
27459                        } else if (specClinicCount > 0) {
27460                            getNewResults = true;
27461                            requestMapParam = 'sp_spec_care_clinic';
27462                        }
27463                    } else if (filterToggleInUrl === 'sp_other_service' && otherClinicCount === 0) {
27464                        if (primaryClinicCount > 0) {
27465                            getNewResults = true;
27466                            requestMapParam = 'sp_prim_care_clinic';
27467                        } else if (specClinicCount > 0) {
27468                            getNewResults = true;
27469                            requestMapParam = 'sp_spec_care_clinic';
27470                        }
27471                    }
27472
27473                    if (getNewResults) {
27474                        requestMapClinic[requestMapParam] = true;
27475                        this.filter(doer, requestMapClinic);
27476                        break;
27477                    }
27478                }
27479                if(activeView === this.LIST_VIEW) {
27480                    if (!mobileFilter) {
27481                        this.$handlebarsTarget.empty();
27482                        if(this.fromNoResults) {
27483                            data.noResultsZipCode = this.noResultsZipCode;
27484                            this.loadTemplate("#handlebars-target", data, JST["directory-handlebars/clinics-filtered-list-template.hbs"]);
27485                            that.adjustDomForMobile();
27486                            this.fromNoResults = false;
27487                            data.noResultsZipCode = "";
27488                        }
27489                        else {
27490                            this.loadTemplate("#handlebars-target", data, JST["directory-handlebars/clinics-filtered-list-template.hbs"]);
27491                            that.adjustDomForMobile();
27492                        }
27493                    }
27494                } else {
27495                    this.$handlebarsTarget.empty();
27496                    // no pagination for the map view
27497                    if (this.fromNoResults) {
27498                        data.fromNoResults = true;
27499                        this.fromNoResults = false;
27500                    }
27501                    this.loadTemplate("#handlebars-target", data, JST["directory-handlebars/clinics-filtered-map-template.hbs"]);
27502                    that.bindOrganicPagination();
27503                    new SHC.ui.Search.SearchResultsMap(data);
27504                }
27505
27506                // only show the option to load more results for grid and list view
27507                if(activeView !== this.MAP_VIEW) {
27508                    this.paginationString = data['pagination']['next'];
27509                    if (this.paginationString) {
27510                        // this.bindViewMoreClick();
27511                        that.bindOrganicPagination();
27512                    }
27513                }
27514
27515                SHC.ui.Search.savedClinicSearch = data; //save the data for frontend pagination
27516                that.bindViewAllClinics();
27517                that.bindOrganicPagination();
27518                new SHC.ui.Modal('.open-modal');
27519                break;
27520
27521            case "organic_programs":
27522                if (!isPaginating) {
27523                    this.$handlebarsTarget.empty();
27524                    this.loadSectionWithTemplate("#handlebars-target", JST["directory-handlebars/programs-filtered-template.hbs"], data);
27525                } else {
27526                    this.loadSectionWithTemplate("#programs-filtered-handlebar .card-collection", JST["directory-handlebars/programs-filtered-paged-template.hbs"], data);
27527                }
27528                break;
27529
27530            case "organic_conds_txs":
27531                if( calledFromStartSearch ){
27532                    var conditionsMap = [];
27533                    var newRequest = false;
27534                    var totalConditions = parseInt(data.general['total-count-conditions']);
27535                    var totalTreatments = parseInt(data.general['total-count-treatments']);
27536                    var totalMedicalTests = parseInt(data.general['total-count-medical-tests']);
27537
27538                    if(window.location.hash.indexOf('x1=sp_type&q1=condition') > 0 && totalConditions === 0){
27539                        if(totalTreatments > 0){
27540                            conditionsMap['sp_type'] = 'treatment';
27541                            newRequest = true;
27542                        }else if(totalMedicalTests > 0){
27543                            newRequest = true;
27544                        }
27545                    } else if(window.location.hash.indexOf('x1=sp_type&q1=treatment') > 0 && totalTreatments === 0){
27546                        if( (totalMedicalTests + totalConditions) > 0){
27547                            newRequest = true;
27548                        }
27549                    }
27550
27551                    if(newRequest){
27552                        this.filter(doer, conditionsMap);
27553                        break;
27554                    }
27555                }
27556
27557                data.selectedMedicalCategory = SHC.util.getAttrValueFromURL('sp_med_categories');
27558                data.selectedAlpha = SHC.util.getAttrValueFromURL('sp_alpha');
27559
27560
27561                if (!mobileFilter) {
27562                    this.$handlebarsTarget.empty();
27563                    this.parseConds(data, isPaginating, Q);
27564                }
27565                break;
27566
27567            case "organic_clinical_trials":
27568                var handlebarsCleared= false;
27569                var fromFilterRailOnly = !data.searchFromFilterRail;
27570                var fromFilterRailAndNonExact = data.searchFromFilterRail && SHC.clinicalTrialsFilter.nonExactClick;
27571
27572                if (fromFilterRailOnly || fromFilterRailAndNonExact ){
27573                    this.$handlebarsTarget.empty();
27574                    handlebarsCleared = true;
27575                    SHC.clinicalTrialsFilter.paginationClickCounter = 0;
27576                }
27577                this.parseTrials(data, calledFromStartSearch, handlebarsCleared);
27578                SHC.clinicalTrialsFilter.data = data;
27579                if (data.nonExactMatchSearch === true) {
27580                    that.trialsPageClick();
27581                }
27582                else
27583                {
27584                    that.bindOrganicPagination();
27585                }
27586                break;
27587
27588            case "organic_stories":
27589                if (!isPaginating) {
27590                    this.$handlebarsTarget.empty();
27591                    this.loadSectionWithTemplate("#handlebars-target", JST["directory-handlebars/stories-filtered-template.hbs"], data);
27592                } else {
27593                    this.loadSectionWithTemplate("#articles-handlebar .card-collection", JST["directory-handlebars/stories-results-paged-template.hbs"], data);
27594                }
27595                var tileTruncation = new  SHC.ui.TileTruncation();
27596                break;
27597
27598            case "organic_events":
27599            case "vc_events":
27600                if (!isPaginating && data && data.pagination && data.pagination.pages && data.pagination.pages.length > 0) {
27601                    this.firstPage = (data.pagination.pages[0].link) ? data.pagination.pages[0].link : "";
27602                }
27603                data.pagination.first = this.firstPage;
27604                this.$handlebarsTarget.empty();
27605                this.loadSectionWithTemplate("#handlebars-target", JST["directory-handlebars/events-filtered-template.hbs"], data);
27606                this.bindOrganicPagination();
27607                break;
27608            case "organic_newsroom":
27609                //only parse data if non-mobile (or mobile and uses apply-filters. Apply-filters request is seen as non-mobile currently)
27610                if (!mobileFilter || SHC.ui.Search.DirectoryUtil.isNewsroomLandingPage()) {
27611                    data.hideThumbnails = $("#search-results-page").attr("data-thumbnails-hidden");
27612                    this.$handlebarsTarget.empty();
27613                    this.parseNewsroom(data, Q);
27614                }
27615                break;
27616            default:
27617                break;
27618        }
27619
27620        this.loadFilterHandlebars(data);
27621
27622        // Pass the data back to interested listeners.
27623        if (onSuccessCallback &&
27624            typeof onSuccessCallback === 'function') {
27625            stanford.analytics.send(stanford.analytics.createSearchEvent(null, data.general.query, 'keyword', null, data.general.total))
27626            onSuccessCallback(data);
27627            SHC.util.appendSavedParams();
27628        }
27629        // If search term is not empty, append to page title for SEO
27630        if(data.searchterm) {
27631            this.prependSearchTermToPageTitle(data.searchterm);
27632        }
27633
27634        if (SHC.ui.screenMode === 'small') {
27635            if(SHC.util.getNormalUrlParameter("openMobileFilters") === "true") {
27636                var refineBox = $(".refine-box");
27637                if(refineBox.length) {
27638                    refineBox.click();
27639                }
27640            }
27641        }
27642        // test and target event hooks
27643        jQuery(window).trigger("refresh_"+doer);
27644        that.adjustDomForMobile();
27645    },
27646
27647    /**
27648     * Moves around a few DOM elements for tablet and mobile views
27649     * @returns {}
27650     */
27651    adjustDomForMobile: function() {
27652        if(SHC.ui.screenMode === "small" || SHC.ui.screenMode === "medium") {
27653            var handlebarsTarget = $('#handlebars-target'),
27654                clinicDescriptionWrappers = handlebarsTarget.find('.clinic-description-wrapper'),
27655                doctorProfileWrappers = handlebarsTarget.find('.doctor-profile-wrapper.has-make-appointment-btn'),
27656                i;
27657
27658            if(clinicDescriptionWrappers.length > 0) {
27659                for(i = 0; i < clinicDescriptionWrappers.length; i++) {
27660                    var $clinicDescriptionWrapper = $(clinicDescriptionWrappers[i]);
27661                    var $locationWrapper = $clinicDescriptionWrapper.siblings('.location-wrapper');
27662                    $locationWrapper.append($clinicDescriptionWrapper);
27663                }
27664            }
27665
27666            if(doctorProfileWrappers.length > 0) {
27667                var is_SHC_site = window.location.href.indexOf("search-results.doctors") > 0;
27668                for(i = 0; i < doctorProfileWrappers.length; i++) {
27669                    var $doctorProfileWrapper = $(doctorProfileWrappers[i]);
27670                    var $makeApptBtnWrapper = $doctorProfileWrapper.find('.make-appointment-btn-wrapper');
27671                    if(is_SHC_site) {
27672                        var $profileHeadWrapper = $doctorProfileWrapper.find('.profile-head-wrapper');
27673                        $profileHeadWrapper.append($makeApptBtnWrapper);
27674                    }
27675                    else {
27676                        $makeApptBtnWrapper.css('display','none')
27677                    }
27678                }
27679            }
27680        }
27681    },
27682
27683    /**
27684     * Cuts the locked labels out of the given string and returns the x/q pair
27685     * @param lockedLabelString
27686     * @returns {string}
27687     */
27688    dealWithLockedLabels: function(lockedLabelString) {
27689        var decodedLabelString = decodeURIComponent(lockedLabelString);
27690        var labelX, labelQ, labelSearchTerm;
27691        var xNum = "22", qNum = "22";
27692        var decodedSplit = decodedLabelString.split('|');
27693        labelX = decodedSplit[0];
27694        if (GLOBAL_DIRECTORY_OBJECT === "organic_clinical_trials") {
27695            labelQ = decodedSplit[1].split('&')[0];
27696        } else if (decodedSplit.length > 2 && decodedSplit[2] !== '') {
27697            labelQ = decodedSplit[2];
27698        } else {
27699            labelQ = decodedSplit[1];
27700        }
27701        if (decodedSplit.length === 4) {
27702            labelSearchTerm = decodedSplit[3];
27703        }
27704        if (GLOBAL_DIRECTORY_OBJECT === "organic_clinics" && (window.location.href.indexOf("%7C") > -1 || window.location.href.indexOf("|") > -1)){
27705            xNum = "22";
27706            qNum = "22";
27707            labelQ = labelQ.substring(labelQ.indexOf('|') + 1).trim();
27708        }else{
27709            if(labelX === 'sp_clinics' && this.clinicPassThroughInfo && this.clinicPassThroughInfo.clinicName) {
27710                labelQ = this.clinicPassThroughInfo.clinicName;
27711                xNum = "22";
27712                qNum = "22";
27713                // pass the strings through jquery to decode html and then encode url
27714                labelQ = encodeURIComponent(jQuery('<textarea />').html(labelQ.replace('_','/')).val());
27715                labelX = encodeURIComponent(jQuery('<textarea />').html(labelX).val());
27716            }
27717            else if(labelX === 'sp_clinicLocations' && this.locationPassThroughInfo && this.locationPassThroughInfo.location) {
27718                labelQ = this.locationPassThroughInfo.location;
27719                xNum = "29";
27720                qNum = "29";
27721            }
27722            else if(labelX === 'sp_conditions' || labelX === 'sp_treatments' ||
27723                labelX === 'sp_medical_tests' || labelX === 'sp_trialLocks') {
27724                xNum = "22";
27725                qNum = "22";
27726            }
27727        }
27728        var returnParams = "&x" + xNum + "=" + labelX + "&q" + qNum + "=" + labelQ;
27729        if (labelSearchTerm !== undefined && labelSearchTerm !== "") {
27730            returnParams += "&q=" + labelSearchTerm;
27731        }
27732        return returnParams;
27733    },
27734
27735    /**
27736     * If there is a spelling suggestion, this function picks it up, passes a new Q to the filter search,
27737     *  and adds the error message to the top of the results
27738     * @param data
27739     * @param Q
27740     * @returns {boolean}
27741     */
27742    handleSpellingSuggestion: function (data, Q) {
27743        var that = this;
27744        try {
27745            var suggestion;
27746            if(data.suggestions && data.suggestions.length > 0) {
27747                suggestion = data.suggestions[0];
27748            } else if(data.length > 1 && data[1].suggestions.length > 0) {
27749                suggestion = data[1].suggestions[0];
27750            }
27751            if (suggestion) {
27752                var badTerm = decodeURIComponent(location.pathname.match(/\.html\/(.*)/)[1]);
27753                if (badTerm.indexOf("&&") !== -1) {
27754                    return false;
27755                }
27756                var newTerm = suggestion.suggestion;
27757                // set data attr
27758                jQuery('#search-results-page').attr('data-search-spelling-suggestion', newTerm);
27759                that.filterAlpha(suggestion.link); // do the right one
27760                // change search bar
27761                jQuery('#search-input-wrapper #search-term').attr("placeholder", newTerm);
27762                this.newTermSuggestion = newTerm;
27763                this.badTermCorrection = badTerm;
27764                jQuery("#suggestion-target").addClass('container');
27765                return true;
27766            }
27767        } catch (e) {
27768        }
27769        return false;
27770    },
27771    /**
27772     * Attaches handlers for each sections View All button/tile
27773     */
27774    bindViewAllClicks: function () {
27775        this.bindAViewAllClick(".show-all-conditions-btn", ".conditions-filter-link", "organic_conds_txs");
27776        this.bindAViewAllClick(".profiledeck .summary-content a, .profiledeck .summary-content", ".doctors-filter-link", "organic_phys");
27777        this.bindAViewAllClick(".show-all-clinics-btn", ".clinics-filter-link", "organic_clinics");
27778        this.bindAViewAllClick(".show-all-programs-btn", ".programs-filter-link", "organic_programs");
27779        this.bindAViewAllClick(".show-all-trials-btn", ".trials-filter-link", "organic_clinical_trials");
27780        this.bindAViewAllClick(".show-all-stories-btn", ".stories-filter-link", "organic_stories");
27781        if (SHC.util.isValleycare()) {
27782            this.bindAViewAllClick(".show-all-results-btn", ".all-results-link", "organic_vc");
27783            this.bindAViewAllClick(".show-all-events-btn", ".events-filter-link", "vc_events");
27784        } else if (SHC.util.isStanfordlab()) {
27785            this.bindAViewAllClick(".show-all-results-btn", ".all-results-link", "slab");
27786        } else {
27787            this.bindAViewAllClick(".show-all-results-btn", ".all-results-link", "organic");
27788            this.bindAViewAllClick(".show-all-events-btn", ".events-filter-link", "organic_events");
27789        }
27790    },
27791    /**
27792     * Generic function to call onLinkClick to bind a search to a button
27793     */
27794    bindAViewAllClick: function (buttonSelector, tabSelector, doer) {
27795        var that = this;
27796        jQuery(buttonSelector)
27797            .off()
27798            .on("click", function (e) {
27799                e.preventDefault();
27800                window.scrollTo(0, 0);
27801                var searchNav = jQuery("#search-nav");
27802                searchNav.find("a").removeClass("active");
27803                searchNav.find(tabSelector).addClass("active");
27804                //if (tabSelector === ".programs-filter-link" || tabSelector === ".all-results-link") {
27805                that.startSearch(doer);
27806                //} else {
27807                // trigger a click on the tab
27808                //    searchNav.find(tabSelector).trigger("click");
27809                //}
27810            });
27811    },
27812    /**
27813     * Binds a paginate search to the view more button on the bottom of a filter page
27814     */
27815    bindViewMoreClick: function () {
27816        var that = this;
27817        jQuery(".view-more-results-btn")
27818            .off().show()
27819            .on("click", function (e) {
27820                e.preventDefault();
27821                SHC.util.setCookie('activeView', SHC.ui.Search.DirectoryUtil.getSelectedView(), 1, '/');
27822                that.paginate(that.paginationString);
27823                that.adjustDomForMobile();
27824            });
27825    },
27826    /**
27827     * Renders the plain organic handlebars and binds the pagination
27828     * @param data
27829     */
27830    parseOrganic: function (data, isPaginating) {
27831        var that = this;
27832        if (!isPaginating && data && data.pagination && data.pagination.pages && data.pagination.pages.length > 0) {
27833            this.firstPage = (data.pagination.pages[0].link) ? data.pagination.pages[0].link : "";
27834        }
27835        data.firstPage = this.firstPage;
27836        this.loadTemplate("#handlebars-target", data, JST["directory-handlebars/all-organic-results-template.hbs"]);
27837
27838        // if there are no deep-link descriptions then we want to shorten the height of the deep
27839        // link div so there is not so much white-space at the bottom
27840        if($('.top-result-container .deep-link-container .deep-link-text').length === 0) {
27841            $('.deep-link-container').css("min-height", "50px");
27842        }
27843
27844        if(this.newTermSuggestion !== '' && this.badTermCorrection !== ''){
27845            var badTermSearchAnyway =  ". <br class='result-mobile-break'/>Show me results <span class='result-desktop-only'>instead </span>for \"<a class='searchAlternateLink case-bold' href='" + this.searchPageUrl + "'/" 
27845+ escape(this.badTermCorrection) + "&&' class='bad-term'>" + encodeURI(this.badTermCorrection) + "</a>\".</div>";
27846            badTermSearchAnyway += "<div class='result-mobile-pagination-space'>";
27847            $('span#alternateSearchResult').html(badTermSearchAnyway);
27848        }
27849        // check how many pages we need and bind the pagination clicks
27850        that.bindOrganicPagination();
27851    },
27852    /**
27853     * Puts paginate searches on the conventional pagination on the plain organic search
27854     */
27855    bindOrganicPagination: function () {
27856        var that = this;
27857        jQuery('.search-pagination').find('a').each(function (idx, anchor) {
27858            var Q = jQuery(anchor).attr('data-request');
27859            jQuery(anchor).on("click", function (e) {
27860                e.preventDefault();
27861                that.paginate(Q);
27862                window.scrollTo(0, 0);
27863            });
27864        });
27865    },
27866    paginateClinics: function (data) {
27867        var MIN_RESULTS = 20;
27868        var paginatedData = [];
27869        var page = [];
27870        var resultCount = 0;
27871        var pageCount = 0;
27872
27873        for (var i = 0; i < data.results.data.length; i++) {
27874            var clinic = data.results.data[i];
27875            if (resultCount >= MIN_RESULTS) {
27876                paginatedData.push(page);
27877                page = [];
27878                resultCount = 0;
27879                pageCount++;
27880            }
27881            for (var j = 0; j < clinic.clinics.length; j++) {
27882                clinic.clinics[j] = JSON.parse(clinic.clinics[j]);
27883            }
27884            resultCount += clinic.clinics.length+1;
27885            page.push(clinic);
27886        }
27887        if (page.length > 0) {
27888            paginatedData.push(page);
27889        }
27890        data.results.data = paginatedData;
27891        data.results.currentPage = data.results.data[0];
27892
27893        this.setFrontendPaginationPageNums(data, 0);
27894        data.isPaginated = true;
27895
27896        return data;
27897    },
27898    setFrontendPaginationPageNums: function (data, pageNum) {
27899        data.pagination = {};
27900        data.pagination.pages = [];
27901        var totalPages = data.results.data.length;
27902        var startPage = 0;
27903
27904        if (pageNum - 4 < 0 || totalPages <= 10) {
27905            startPage = 0;
27906        } else if (pageNum + 5 >= totalPages) {
27907            startPage = totalPages - 10;
27908        } else {
27909            startPage = pageNum - 4;
27910        }
27911
27912        var isSelected = pageNum === 0 ? "true" : "false";
27913        data.pagination.pages.push({"page":1,"link":0,"selected":isSelected});
27914        for (var i = startPage + 1; i < totalPages && i < startPage + 10; i++) {
27915            isSelected = pageNum === i ? "true" : "false";
27916            data.pagination.pages.push({"page":i+1,"link":i,"selected":isSelected});
27917        }
27918
27919        if (pageNum === 0) {
27920            data.pagination.previous = "";
27921        } else {
27922            data.pagination.previous = pageNum-1;
27923        }
27924        if (pageNum === totalPages - 1) {
27925            data.pagination.next = "";
27926        } else {
27927            data.pagination.next = pageNum + 1;
27928        }
27929        data.results.currentPage = data.results.data[pageNum];
27930        data.pagination.first = 0;
27931        data.pagination.last = totalPages-1;
27932
27933        return data;
27934    },
27935    paginateNewsroom: function (data, resultsPerPage) {
27936        var paginatedData = [];
27937        var page = [];
27938        var resultCount = 0;
27939        var pageCount = 0;
27940
27941        for (var i = 0; i < data.results.data.length; i++) {
27942            var newsroom = data.results.data[i];
27943            if (resultCount >= resultsPerPage) {
27944                paginatedData.push(page);
27945                page = [];
27946                resultCount = 0;
27947                pageCount++;
27948            }
27949            if (newsroom.articles) {
27950                for (var j = 0; j < newsroom.articles.length; j++) {
27951                    newsroom.articles[j] = JSON.parse(newsroom.articles[j]);
27952                }
27953            }
27954            resultCount ++;
27955            page.push(newsroom);
27956        }
27957        if (page.length > 0) {
27958            paginatedData.push(page);
27959        }
27960        data.results.data = paginatedData;
27961        data.results.currentPage = data.results.data[0];
27962
27963        this.setFrontendPaginationPageNums(data, 0);
27964        data.isPaginated = true;
27965
27966        return data;
27967    },
27968    bindViewAllClinics: function () {
27969        jQuery('.view-all-locations').on('click', function() {
27970            var $this = $(this);
27971            var $carat = jQuery(this).find('span');
27972            $carat.toggleClass('open');
27973            $carat.closest('.clinic-location-wrapper').find('.child-clinics').slideToggle();
27974
27975            var $text = $this.find('.text');
27976            if ($carat.hasClass('open')) {
27977                $text.text('Hide All Locations');
27978            } else {
27979                var count = $this.siblings('.child-clinics').find('.location-wrapper').length;
27980                var viewText = 'View Location';
27981                if (count > 1) {
27982                    viewText = 'View All ' + count + ' Locations';
27983                }
27984                $text.text(viewText);
27985            }
27986        });
27987    },
27988    bindMediaCarousels: function () {
27989        var $mediaCarousels = $('.media-carousel');
27990
27991        $mediaCarousels.each(function() {
27992            var $carousel = $(this);
27993            $carousel.find('.paddle').on('click', function(){
27994                var $paddle = $(this);
27995                var isEnabled = !$paddle.hasClass('disabled');
27996                var $slides = $carousel.find('.slide');
27997                var $slideContainer = $carousel.find('.slides');
27998                var activeSlide = parseInt($slideContainer.attr('data-active-slide'));
27999                var slideCount = $slides.length;
28000                $slides.removeClass('active');
28001
28002                if (isEnabled && $paddle.hasClass('left') && activeSlide > 0) {
28003                    $($slides.get(activeSlide)).addClass('right');
28004                    activeSlide--;
28005                    $($slides.get(activeSlide)).removeClass('left');
28006                    if (activeSlide === 0) {
28007                        $paddle.addClass('disabled');
28008                    }
28009                    $carousel.find('.right.paddle').removeClass('disabled');
28010                } else if (isEnabled && $paddle.hasClass('right') && activeSlide < slideCount-1) {
28011                    $($slides.get(activeSlide)).addClass('left');
28012                    activeSlide++;
28013                    $($slides.get(activeSlide)).removeClass('right');
28014                    if (activeSlide === slideCount-1) {
28015                        $paddle.addClass('disabled');
28016                    }
28017                    $carousel.find('.left.paddle').removeClass('disabled');
28018                }
28019
28020                $slideContainer.attr('data-active-slide', activeSlide);
28021                $($slides.get(activeSlide)).addClass('active');
28022            });
28023        });
28024    },
28025    trialsPageClick: function(){
28026        var that = this;
28027        jQuery('.search-pagination').find('a').each(function (idx, anchor) {
28028            var Q = jQuery(anchor).attr('data-request');
28029            jQuery(anchor).on("click", function (e) {
28030                e.preventDefault();
28031
28032                var activePage = parseInt(this.text);
28033                var lastPage = parseInt($('.search-pagination li').not('.arrow').last().find('a').text());
28034                if ($(this).parent().hasClass('arrow')){
28035                    if ($(this).parent().hasClass('page-one')){
28036                        activePage = 1;
28037                        $('.search-pagination li').removeClass('selected');
28038                        $('.search-pagination > ul > li:not(.arrow)').first().addClass('selected')
28039                    }
28040                    else {
28041                        var currentPage = $('.search-pagination > ul > li.selected > a').text();
28042                        if ($(this).parent().hasClass('next')) {
28043                            activePage = parseInt(currentPage)+1;
28044                        }
28045                        else {
28046                            activePage = parseInt(currentPage)-1;
28047                        }
28048
28049                        $('.search-pagination li').removeClass('selected');
28050                        $('.search-pagination > ul > li:not(.arrow)').eq(activePage - 1).addClass('selected');
28051                    }
28052                }
28053                else {
28054                    $('.search-pagination li').removeClass('selected');
28055                    $(this).closest('li').addClass('selected');
28056                }
28057
28058                $('.cond-result').addClass('hidden');
28059                $('.condition-letter-header').addClass('hidden');
28060                $('.cond-result.ct_grp_' + (parseInt(activePage) - 1)).removeClass('hidden');
28061                $('.condition-letter-header.ct_grp_' + (parseInt(activePage)-1)).removeClass('hidden');
28062
28063                if (SHC.ui.screenMode === "small" && activePage > 2){
28064                    $('.search-pagination li.arrow.page-one').show();
28065                }
28066                else{
28067                    $('.search-pagination li.arrow.page-one').hide();
28068                }
28069
28070                if (activePage == 1){
28071                    $('.search-pagination li.arrow.prev-active').removeClass('prev-active').addClass('prev-inactive');
28072                }
28073                else{
28074                    $('.search-pagination li.arrow.prev-inactive').addClass('prev-active').removeClass('prev-inactive');
28075                }
28076
28077                if (activePage == lastPage){
28078                    $('.search-pagination li.arrow.next').hide();
28079                }
28080                else{
28081                    $('.search-pagination li.arrow.next').show();
28082                }
28083                window.scrollTo(0, 0);
28084            });
28085        });
28086    },
28087    bindDirectoryFilters: function () {
28088        this.bindAViewAllClick("#directories-links .doctor-filter", ".doctors-filter-link", "organic_phys");
28089        this.bindAViewAllClick("#directories-links .clinic-filter", ".clinics-filter-link", "organic_clinics");
28090        this.bindAViewAllClick("#directories-links .condition-filter", ".conditions-filter-link", "organic_conds_txs");
28091    },
28092    specialistFilterActive: function() {
28093        var  urlAfterHash = window.location.hash;
28094        return urlAfterHash.indexOf("sp_spec_care_phy") > -1 || $(".specialists-filter").hasClass("active");
28095    },
28096    primaryCareFilterActive: function() {
28097        var  urlAfterHash = window.location.hash;
28098        return urlAfterHash.indexOf("sp_prim_care_types") > -1 || $(".primary-care-filter").hasClass("active");
28099    },
28100    isPrimaryCareDoctorTitle: function(doctorTitle) {
28101        for(var i=0; i<this.primaryCareDoctorTitles.length; i++) {
28102            if(this.primaryCareDoctorTitles[i] === doctorTitle) {
28103                return true;
28104            }
28105        }
28106        return false;
28107    },
28108
28109    getSpecialtyData: function (data, doctorTitles, filterSpecialties) {
28110        // get the currently selected value for specialty/subspecialty
28111        var selectedSpecialty = SHC.util.getAttrValueFromURL('sp_dr_title_groups'),
28112            selectedSubspecialty = SHC.util.getAttrValueFromURL('sp_dr_titles'),
28113            selectedSpecialtyID,
28114            currentSpecialty = "",
28115            specialtyCount = 0,
28116            specialties = [],
28117            subSpecialties = [],
28118            specialtyTotal = 0,
28119            splitSpecialty,
28120            specialty,
28121            subspecialty;
28122        if(filterSpecialties) {
28123            for(var i = 0; i < filterSpecialties.length; i++) {
28124                splitSpecialty = filterSpecialties[i].value.split("_");
28125                specialty = splitSpecialty[0];
28126                subSpecialty = splitSpecialty[1];
28127                specialtyTotal = filterSpecialties[i].count;
28128
28129                if(specialty !== currentSpecialty) {
28130                    specialtyCount++;
28131                    currentSpecialty = specialty;
28132                    var matchingDoctorTitle = $.grep(doctorTitles, function (e) {
28133                        return e.value === currentSpecialty;
28134                    });
28135                    if (matchingDoctorTitle && matchingDoctorTitle[0] && parseInt(matchingDoctorTitle[0].count) > 0) {
28136                        specialties.push({
28137                            id: specialtyCount,
28138                            title: currentSpecialty,
28139                            count: matchingDoctorTitle[0].count
28140                        });
28141                    }
28142                }
28143
28144                if(selectedSpecialty === currentSpecialty) {
28145                    selectedSpecialtyID = specialtyCount;
28146                }
28147
28148                //Only add the sub-specialty to the list of sub-specialties if :
28149                //  1. There is no selectedSpecialty
28150                //  2. There is selectedSpecialty and it equals currentSpecialty.
28151                if((selectedSpecialty  && selectedSpecialty === currentSpecialty) || !selectedSpecialty) {
28152                    subSpecialties.push({
28153                        id: specialtyCount,
28154                        title: subSpecialty,
28155                        count: specialtyTotal
28156                    });
28157                }
28158            }
28159        }
28160
28161        var parsedData = {
28162            specialties: specialties,
28163            subSpecialties: subSpecialties,
28164            selectedSpecialty: selectedSpecialty,
28165            selectedClinicSpecialty: selectedSpecialty,
28166            selectedSpecialtyID: selectedSpecialtyID,
28167            selectedSubspecialty: selectedSubspecialty
28168        };
28169
28170        var hideSubSpecialty = 0;
28171        $.each(parsedData.subSpecialties, function(key, val){
28172            if (val.id === parsedData.selectedSpecialtyID){
28173                hideSubSpecialty++;
28174            }
28175        });
28176
28177        var callback = function(callbackArgs) {
28178            if ($('#subSpecialtyCount.subCount').length === 1) {
28179                $('#subSpecialtyCount.subCount').text(callbackArgs.hideSubSpecialty);
28180            }
28181            else {
28182                $('body').append('<div id="subSpecialtyCount" class="subCount" style="display:none">' + callbackArgs.hideSubSpecialty + '</div>');
28183            }
28184
28185            if($('.select-group.sub-specialty.unfiltered.pop-show.vis-on').length === 1 && callbackArgs.hideSubSpecialty < 2){
28186                $('.select-group.sub-specialty.unfiltered').removeClass('pop-show vis-on');
28187            }
28188        };
28189
28190        return {
28191            parsedData: parsedData,
28192            callback: callback,
28193            callbackArgs: {
28194                hideSubSpecialty: hideSubSpecialty
28195            }
28196        };
28197
28198    },
28199
28200    getPrimaryCareData: function (data, primaryCareTypes, primaryCareSpecialties) {
28201        // get the currently selected value for Primary Care/Doctor Type
28202        var selectedPrimaryCare = SHC.util.getAttrValueFromURL('sp_prim_care_types'),
28203            selectedDoctorType = SHC.util.getAttrValueFromURL('sp_dr_titles'),
28204            selectedPrimaryCareID,
28205            currentPrimaryCare = "",
28206            primaryCareCount = 0,
28207            primaryCares = [],
28208            doctorTypes = [],
28209            doctorTypeTotal = 0,
28210            splitPrimaryCare,
28211            primaryCare,
28212            doctorType;
28213        if(primaryCareSpecialties) {
28214            for(var i = 0; i < primaryCareSpecialties.length; i++) {
28215                splitPrimaryCare = primaryCareSpecialties[i].value.split("_");
28216                primaryCare = splitPrimaryCare[0];
28217                doctorType = splitPrimaryCare[1];
28218                doctorTypeTotal = primaryCareSpecialties[i].count;
28219
28220                if(primaryCare !== currentPrimaryCare) {
28221                    primaryCareCount++;
28222                    currentPrimaryCare = primaryCare;
28223                    var matchingPrimaryCareType = $.grep(primaryCareTypes, function (e) {
28224                        return e.value === currentPrimaryCare;
28225                    });
28226                    if (matchingPrimaryCareType && matchingPrimaryCareType[0] && parseInt(matchingPrimaryCareType[0].count) > 0) {
28227                        primaryCares.push({
28228                            id: primaryCareCount,
28229                            title: currentPrimaryCare,
28230                            count: matchingPrimaryCareType[0].count
28231                        });
28232                    }
28233                }
28234
28235                if(selectedPrimaryCare === currentPrimaryCare) {
28236                    selectedPrimaryCareID = primaryCareCount;
28237                }
28238
28239                //Only add the doctor type to the list of doctor types if :
28240                //  1. There is no selectedPrimaryCare
28241                //  2. There is a selectedPrimaryCare option and it equals currentPrimaryCare.
28242                if((selectedPrimaryCare  && selectedPrimaryCare === currentPrimaryCare) || !selectedPrimaryCare) {
28243                    doctorTypes.push({
28244                        id: primaryCareCount,
28245                        title: doctorType,
28246                        count: doctorTypeTotal
28247                    });
28248                }
28249            }
28250        }
28251
28252        var parsedData = {
28253            primaryCares: primaryCares,
28254            doctorTypes: doctorTypes,
28255            selectedPrimaryCare: selectedPrimaryCare,
28256            selectedPrimaryCareID: selectedPrimaryCareID,
28257            selectedDoctorType: selectedDoctorType
28258        };
28259
28260        var hideSubSpecialty = 0;
28261        $.each(parsedData.doctorTypes, function(key, val){
28262            if (val.id === parsedData.selectedPrimaryCareID){
28263                hideSubSpecialty++;
28264            }
28265        });
28266
28267        return {
28268            parsedData: parsedData
28269        };
28270
28271    },
28272
28273    profileTileHeights: function() {
28274        if ($('.tile-detail').length > 0) {
28275            var divGroups = [],
28276                divGroupIdx = -1;
28277            modMod = 3;
28278
28279            if (SHC.ui.screenMode === "medium") {
28280                modMod = 2;
28281            }
28282            $('.tile-detail').each(function(idx) {
28283                if (idx % modMod === 0) {
28284                    divGroupIdx++;
28285                    divGroups[divGroupIdx] = [];
28286                }
28287                divGroups[divGroupIdx].push(idx);
28288            });
28289            $.each(divGroups, function(idx, group) {
28290                var heightArr = [],
28291                    maxHeight;
28292                $.each(group, function(idx, item) {
28293                    heightArr.push($('.tile-detail').eq(item).outerHeight());
28294                });
28295                maxHeight = Math.max.apply(null, heightArr);
28296                maxHeight = maxHeight - 20;
28297                $.each(group, function(idx, item) {
28298                    $('.tile-detail').eq(item).height(maxHeight);
28299                });
28300            });
28301        }
28302    },
28303
28304    /**
28305     * Sets up the profile deck using the SHC.ui.ProfileDeckSearch class
28306     * @param data
28307     * @param isPaginating
28308     */
28309    parsePhys: function (data, isPaginating, activeView) {
28310        var that = this;
28311        var dataLength = [];
28312        var profileDeck = null;
28313
28314        if (data && data.results && data.results.data) {
28315            dataLength.push(data.results.data.length);
28316        } else {
28317            return;
28318        }
28319        data.activeView = activeView;
28320
28321        if (!isPaginating && data && data.pagination && data.pagination.pages && data.pagination.pages.length > 0) {
28322            this.firstPage = (data.pagination.pages[0].link) ? data.pagination.pages[0].link : "";
28323        }
28324        data.firstPage = this.firstPage;
28325
28326        // distance filter conditionally shows up on doctor specialist views so we need to know the selected specialty.
28327        data.selectedSpecialty = SHC.util.getAttrValueFromURL("sp_dr_title_groups");
28328        if(activeView === this.LIST_VIEW) {
28329            if(this.fromNoResults) {
28330                data.noResultsZipCode = this.noResultsZipCode;
28331                data = that.passthroughBackLinkOverride(data);
28332                this.loadTemplate("#handlebars-target", data, JST["directory-handlebars/doctors-filtered-list-template.hbs"]);
28333                this.adjustDomForMobile();
28334                this.fromNoResults = false;
28335                this.noResultsZipCode = "";
28336            }
28337            else {
28338                data = that.passthroughBackLinkOverride(data);
28339                this.loadTemplate("#handlebars-target", data, JST["directory-handlebars/doctors-filtered-list-template.hbs"]);
28340                this.adjustDomForMobile();
28341            }
28342
28343            new SHC.ui.DrMakeAnAppt();
28344        } else {
28345            // no pagination for the map view
28346            if (this.fromNoResults) {
28347                data.fromNoResults = true;
28348                this.fromNoResults = false;
28349            }
28350            data = that.passthroughBackLinkOverride(data);
28351            this.loadTemplate("#handlebars-target", data, JST["directory-handlebars/doctors-filtered-map-template.hbs"]);
28352            new SHC.ui.Search.SearchResultsMap(data);
28353        }
28354
28355        // only show the option to load more results for grid and list view
28356        if(activeView !== this.MAP_VIEW) {
28357            //update paginationString
28358            that.paginationString = data['pagination']['next'];
28359            if (that.paginationString) {
28360                that.bindViewMoreClick();
28361            }
28362
28363            var $communityDoctors = $('#search-results-page .container.directory .community-doctors-link');
28364            if( $communityDoctors.length === 1
28365                && $('input#search-term').val() === ''
28366                && window.location.href.indexOf('search-results.doctors.html') > 0
28367                && window.location.href.indexOf('%7C') === -1
28368                && (window.location.hash === ''
28369                    || window.location.hash === '#&x1=sp_spec_care_phy&q1=true'
28370                    || window.location.hash === '#x1=sp_spec_care_phy&q1=true'
28371                    || window.location.hash === '#') ){
28372
28373                $communityDoctors.find('a').attr('href', SHC.util.adjustPath($communityDoctors.find('a').attr('href')));
28374                $communityDoctors.removeClass('hidden');
28375            }
28376        }
28377        new SHC.ui.Modal('.search-results-filters .open-modal');
28378        that.bindOrganicPagination();
28379    },
28380
28381    getActiveView: function() {
28382        //Gets a cookie which is being used to remember what view should be shown when navigating between pages
28383        var activeItem = SHC.util.getCookie('activeView');
28384        if(activeItem){
28385            return activeItem;
28386        } else {
28387            activeItem = $(".grid-list-toggle .active");
28388            if(activeItem.length > -1 && activeItem.hasClass("map-view-icon")){
28389                return this.MAP_VIEW;
28390            } else {
28391                return this.LIST_VIEW;
28392            }
28393        }
28394    },
28395    /**
28396     * Passes the json to the conditions handlebars. It has to handle relevance vs alphabetized to get the right templates
28397     * @param data
28398     * @param isPaginating
28399     * @param Q
28400     */
28401
28402
28403    parseConds: function (data, isPaginating, Q) {
28404        var that = this;
28405        if (!isPaginating && data && data.pagination && data.pagination.pages && data.pagination.pages.length > 0) {
28406            this.firstPage = (data.pagination.pages[0].link) ? data.pagination.pages[0].link : "";
28407        }
28408        data.firstPage = this.firstPage;
28409        if (Q.indexOf('sp_s=sp_displayName') !== -1) { // if we are alpha sorting so we want alpha headers
28410            var resultsList = data['results']['data'];
28411            var firstLetter = "";
28412            if (resultsList.length) {
28413                firstLetter = data['results']['data'][0]['alpha'].toUpperCase();
28414            }
28415            var targetList = jQuery('.section-break:contains(' + firstLetter + ')');
28416            var appendToLastList = targetList.length;
28417
28418            if (appendToLastList) {
28419                var result;
28420                do {
28421                    result = resultsList.shift();
28422                    if (firstLetter === result['alpha'].toUpperCase()) {
28423                        targetList.parent().append('<li> <a href="' + result['url'] + '">' + result['title'] + '</a></li>');
28424                    }
28425                } while (firstLetter === result['alpha'].toUpperCase());
28426                resultsList.unshift(result);
28427            }
28428            this.loadTemplate("#handlebars-target", data, JST["directory-handlebars/conditions-alpha-filtered-template.hbs"]);
28429
28430            //update paginationString
28431            that.paginationString = data['pagination']['next'];
28432            if (that.paginationString !== "") {
28433                that.bindViewMoreClick();
28434            }
28435        } else {
28436            this.loadTemplate("#handlebars-target", data, JST["directory-handlebars/conditions-filtered-template.hbs"]);
28437
28438            //update paginationString
28439            that.paginationString = data['pagination']['next'];
28440            if (that.paginationString !== "") {
28441                that.bindViewMoreClick();
28442            }
28443        }
28444        new SHC.ui.Modal('.search-results-filters .open-modal');
28445        that.bindOrganicPagination();
28446    },
28447
28448    /**
28449     * Processes the trials for the new clinical trials directory
28450     * @param data
28451     * @param isPaginating
28452     */
28453
28454    parseTrials: function (data, calledFromStartSearch, handlebarsCleared) {
28455        SHC.paginationCount = undefined;
28456
28457        if (data && data.pagination && data.pagination.pages && data.pagination.pages.length > 0) {
28458            data.firstPage = (data.pagination.pages[0].link) ? data.pagination.pages[0].link : "";
28459        }
28460        data.conditionFilter = SHC.util.getAttrValueFromURL("sp_conditions");
28461        data.trialIdFilter = SHC.util.getAttrValueFromURL("sp_trial_id");
28462        var spStatus = SHC.util.getAttrValueFromURL("sp_status");
28463        if(!spStatus) {
28464            var pathName = decodeURIComponent(window.location.href);
28465            var searchChunk = pathName.match(/\.html\/(.*)/);
28466            var passthrough;
28467            if (searchChunk && searchChunk[1]) {
28468                passthrough = searchChunk[1].split("|");
28469            }
28470            if (passthrough && passthrough[1] && passthrough[1].indexOf("&") > -1) {
28471                spStatus = passthrough[1].split("&")[1];
28472            }
28473        }
28474        if((!spStatus || spStatus === "") && calledFromStartSearch) {
28475            spStatus = "RECRUITING";
28476        }
28477        data.recruitingFilter = (!spStatus || spStatus === "") ? "RECRUITING" : spStatus;
28478
28479        if (this.showTrialsInstructions === true && data.searchFromFilterRail === false) {
28480            this.loadTemplate("#handlebars-target", data, JST["directory-handlebars/trials-instructions-template.hbs"]);
28481        } else if (data.nonExactMatchSearch  === true && data.searchFromFilterRail === false) {
28482            data.pagination.pages = [];
28483            var conditionCount = data.facets.conditions ?  data.facets.conditions.length-1 : 0;
28484            for(var pageNumber = 1; pageNumber <= conditionCount/20 + 1; pageNumber++){
28485                var page = {page: pageNumber, selected: "false"};
28486                data.pagination.pages.push(page);
28487            }
28488            if (data.pagination.pages.length > 0)
28489                data.pagination.pages[0].selected = "true";
28490            this.loadTemplate("#handlebars-target", data, JST["directory-handlebars/trials-non-exact-match-template.hbs"]);
28491        } else if(data.searchFromFilterRail === false
28492                || (data.searchFromFilterRail === true && SHC.clinicalTrialsFilter.nonExactClick)
28493                || (SHC.clinicalTrialsFilter.clearXclick && SHC.clinicalTrialsFilter.recrutingBackToDefault)
28494                || SHC.clinicalTrialsFilter.recrutingBackToDefault === true){
28495            this.loadTemplate("#handlebars-target", data, JST["directory-handlebars/trials-exact-match-template.hbs"]);
28496        }
28497
28498        var filterRail = $('.search-results-filters.trials-filter-rail');
28499        var searchResultsList = $('.clinical-trials-directory .search-results-list');
28500        var overlay = $('.search-results-list-overlay');
28501
28502        if(!handlebarsCleared  && SHC.ui.screenMode === 'small' && !SHC.clinicalTrialsFilter.paginationClick){
28503            if(filterRail && !filterRail.hasClass('visible')){
28504                filterRail.addClass('visible');
28505            }
28506
28507            var totalHeight = 0;
28508            if(overlay && !overlay.hasClass('active')){
28509                if( $('.trials-by-condition.exact-match').length > 0 ){
28510                    totalHeight = SHC.util.clinicalTrialsMobileExactMatchOverlayHeight();
28511                }else if( $('.clinical-trials-directory.non-exact-match').length > 0 ){
28512                    totalHeight = SHC.util.clinicalTrialsMobileNonExactMatchOverlayHeight();
28513                }
28514                overlay.css( { "height": totalHeight });
28515                overlay.addClass('active');
28516            }
28517        }
28518
28519        if(handlebarsCleared){
28520            $('html,body').scrollTop(0);
28521        }
28522
28523        //reset all shc vars
28524        SHC.clinicalTrialsFilter.clearXclick = false;
28525        SHC.clinicalTrialsFilter.nonExactClick = false;
28526        SHC.clinicalTrialsFilter.paginationClick = false;
28527
28528        new SHC.ui.Modal('.search-results-filters .open-modal');
28529    },
28530
28531    getNewsroomLandingType: function() {
28532        collectionType = "";
28533        var newsroomLandingTag = $('#search-results-page').attr('data-newsroom-type');
28534        if (newsroomLandingTag && newsroomLandingTag !== '') {
28535            collectionType = "&x50=sp_tags&q50=" + newsroomLandingTag;
28536        }
28537        return collectionType;
28538    },
28539    /**
28540     * processes S&P results for newsroom directories
28541     * @param data
28542     */
28543    parseNewsroom: function(data, Q) {
28544        if (SHC.ui.Search.DirectoryUtil.isNewsroomDirectoryPage()) {
28545            if (!data.isPaginated ) {
28546                SHC.ui.Search.savedQ = Q;
28547                data = this.paginateNewsroom(data, 10);
28548            }
28549            this.loadTemplate("#handlebars-target", data, JST["directory-handlebars/newsroom-directory-list-template.hbs"]);
28550        } else if (SHC.ui.Search.DirectoryUtil.isNewsroomLandingPage()) {
28551            if (!data.isPaginated ) {
28552                SHC.ui.Search.savedQ = Q;
28553                data = this.paginateNewsroom(data, 12);
28554            }
28555            if (this.$handlebarsTarget.attr('data-content-type') === 'list') {
28556                if (!data.isPaginated ) {
28557                    SHC.ui.Search.savedQ = Q;
28558                    data = this.paginateNewsroom(data, 10);
28559                }
28560                this.loadTemplate("#handlebars-target", data, JST["directory-handlebars/newsroom-collection-list-template.hbs"], true);
28561            } else {
28562                if (!data.isPaginated ) {
28563                    SHC.ui.Search.savedQ = Q;
28564                    data = this.paginateNewsroom(data, 18);
28565                }
28566                SHC.newsroom = {};
28567                SHC.newsroom.template = 'collection-grid';
28568                this.loadTemplate("#handlebars-target", data, JST["directory-handlebars/newsroom-landing-grid-template.hbs"]);
28569            }
28570        }
28571        if (data && data.pagination && data.pagination.pages && data.pagination.pages.length > 0) {
28572            this.firstPage = (data.pagination.pages[0].link) ? data.pagination.pages[0].link : "";
28573        }
28574        data.firstPage = this.firstPage;
28575        SHC.ui.Search.savedNewsroomSearch = data;  //save the data for frontend pagination
28576        this.bindMediaCarousels();
28577        this.bindOrganicPagination();
28578        new SHC.ui.Modal('.search-results-filters .open-modal');
28579    },
28580
28581    /**
28582     * Loads filter Handlebar template into master template page and loads handlebar data.
28583     * @param data
28584     *
28585     ***  DEV NOTE: FUTURE NEW FILTERS ADDED MUST FOLLOW SPECIFIC CLASS STRUCTURE IN ORDER TO FUNCTION PROPERLY.
28586     ***  FILTER'S HANDLEBAR PAGE WILL BE NAMED [FILTERTYPE]-FILTER.HBS
28587     ***  FILTER'S TARGET DIV IN MAIN HANDLEBAR PAGE WILL BE NAMED [filename]-target (i.e. "new-filter.hbs" target ID Class = "new-filter-target"
28588     ***  WITHOUT THIS FORMATTING FILTER WILL NOT BE INSERTED CORRECTLY.
28589     */
28590    loadFilterHandlebars: function(data) {
28591        var that = this;
28592        var filterTargetDivs = $("div[id*='filter-target']");
28593        var filtersCount = filterTargetDivs.length;
28594
28595        var dataSrc = null;
28596        var callback = null;
28597        var callbackArgs = null;
28598
28599        filterTargetDivs.each(function(){
28600            currentFilterID = $(this).attr('id');
28601            currentFilterTarget = currentFilterID.substr(0,currentFilterID.lastIndexOf('-'))+".hbs";
28602
28603            // Special case for the specialties filters dataSrc because the data must be parsed first.
28604            dataSrc = data;
28605            if (currentFilterID === "doctors-specialties-filter-target" ||
28606                    currentFilterID === "clinic-specialties-filter-target"){
28607                var specialtyDataInfo = that.getSpecialtyData(data, data.facets.doctorTitles, data.facets.groupTitles);
28608                dataSrc = specialtyDataInfo.parsedData;
28609                callback = specialtyDataInfo.callback;
28610                callbackArgs = specialtyDataInfo.callbackArgs;
28611            } else if (currentFilterID === "doctor-types-filter-target"){
28612                var primaryCareDataInfo = that.getPrimaryCareData(data, data.facets.primaryCareTypes, data.facets.primary_care_subspecs); //primary_care_subspecs
28613                dataSrc = primaryCareDataInfo.parsedData;
28614                callback = primaryCareDataInfo.callback;
28615                callbackArgs = primaryCareDataInfo.callbackArgs;
28616            } else if (currentFilterID === "newsroom-year-filter-target"){
28617                if ($('#newsroom-year-filter-target').closest('.newsroom-landing').length != 0){
28618                    dataSrc.newsroomLanding = true;
28619                    dataSrc.filterTitle = "VIEW ARTICLES BY YEAR: ";
28620                    dataSrc.filterDefault = "ALL";
28621                }
28622                else {
28623                    dataSrc.newsroomLanding = false;
28624                    dataSrc.filterTitle = "FILTER BY YEAR";
28625                    dataSrc.filterDefault = "Show All";
28626                }
28627                if (SHC.util.getAttrValueFromURL('sp_year')) {
28628                    dataSrc.filterDefault = SHC.util.getAttrValueFromURL('sp_year')
28629                }
28630                if (dataSrc.facets && Array.isArray(dataSrc.facets.year)) {
28631                    dataSrc.facets.year.sort(function (a, b) {
28632                        return (b.value - a.value);
28633                    });
28634                }
28635            } else if (currentFilterID === "newsroom-category-filter-target"){
28636                dataSrc.filterTitle = "VIEW CATEGORIES: ";
28637                dataSrc.filterDefault = "ALL";
28638
28639                if (SHC.util.getAttrValueFromURL('sp_category')) {
28640                    dataSrc.filterDefault = SHC.util.getAttrValueFromURL('sp_category');
28641                }
28642            }
28643
28644            var tagMapJsonString = $('meta[name="tag-map"]').attr('value');
28645            dataSrc.tagMapJson = {};
28646            if (tagMapJsonString) {
28647                dataSrc.tagMapJson = JSON.parse(tagMapJsonString);
28648            }
28649
28650            jQuery('#'+currentFilterID).empty();
28651            jQuery('#'+currentFilterID).append(JST["directory-handlebars/" + currentFilterTarget](dataSrc));
28652        });
28653
28654        jQuery(window).trigger(jQuery.Event("filtersLoaded"));
28655
28656        if(callback) {
28657            callback(callbackArgs);
28658        }
28659
28660        $('.search-results #spinner-home.mobile-filter-active').css('height','');
28661        $('.search-results #spinner-home').removeClass('mobile-filter-active');
28662    },
28663
28664    /**
28665     * Binds searches to all of the condition blades in the trials directory
28666     */
28667    bindBlades: function () {
28668        var that = this;
28669        jQuery('.blade-content-wrapper').find('.condition-blade').each(function (idx, blade) {
28670            var Q = jQuery(blade).attr('data-query-string');
28671            jQuery(blade).off().on("click", function (e) {
28672                e.preventDefault();
28673                var jqBlade = jQuery(this);
28674                that.bladeSelector = "." + jqBlade.attr("data-target") + "-target";
28675                // don't do the query if we already have data
28676                if (jQuery(that.bladeSelector).children().length === 1) {
28677                    // move the spinner to our blade
28678                    jqBlade.parent().find('.spinner').html(jQuery('#spinner-container'));
28679                    that.paginate(Q);
28680                }
28681                var arrow = jqBlade.closest(".blade-box").find(".blade-arrow");
28682                if ($(arrow).html() === "-") {
28683                    $(arrow).html('+');
28684                } else {
28685                    $(arrow).html('-');
28686                }
28687                jqBlade.closest(".blade-box").find(".trial-list").slideToggle();
28688            });
28689        });
28690    },
28691    initWaitTimes: function (selector, usePedia) {
28692        var timer = jQuery(selector),
28693        getWaitTimeInMinutes = function(events) {
28694            for (var i=0, n=events.length; i<n; i++) {
28695                if (events[i].description === "Door-First MD") {
28696                    return events[i].waittimes[0].waitTimeInMinutes;
28697                }
28698            }
28699            return null;
28700        },
28701        convertToWaitTime = function(wt) {
28702            var hours = Math.floor(wt / 60);
28703            hours = ("0" + hours).slice(-2);
28704            var minutes = wt % 60;
28705            minutes = ("0" + minutes).slice(-2);
28706            return hours+":"+minutes;
28707        },
28708        ts = new Date().valueOf(),
28709        url = '/bin/connector/er.json?ts=' + ts;
28710
28711        if (usePedia) {
28712          url = '/bin/connector/er.json?source=ped&ts=' + ts;
28713        }
28714
28715        if (timer.length) {
28716            jQuery.ajax({
28717                "type": "GET",
28718                "url": url, // client to new MyHealth hosted service.
28719                "success": function(data) {
28720                    if (data && data.meta && data.meta.code === 200){
28721                        var waittime = null;
28722                        if (typeof data.events !== 'undefined') {
28723                            waittime = getWaitTimeInMinutes(data.events);
28724                        }
28725                        if (waittime !== null) {
28726                            var time = convertToWaitTime(waittime),
28727                                timeDom = time + '<div class="ed-time-timer-min">min</div>';
28728                            timer.html(timeDom);
28729                        } else {
28730                            errorMessage(error);
28731                        }
28732                    } else {
28733                        errorMessage(error);
28734                    }
28735                },
28736                "error": function(jqXHR, textStatus, errorThrown) {
28737                    errorMessage(error);
28738                }
28739            });
28740        }
28741    },
28742
28743    loadSectionWithTemplate: function (targetSelector, template, data) {
28744        var that = this;
28745        // update filter and alphabet bars
28746        this.loadTemplate(targetSelector, data, template);
28747        //update paginationString
28748        that.paginationString = data['pagination']['next'];
28749        if (that.paginationString !== "") {
28750            that.bindViewMoreClick();
28751        }
28752    },
28753    prependLoadTemplate: function(targetSelector, incomingdata, template) {
28754        jQuery(targetSelector).prepend(template(incomingdata));
28755    },
28756    /**
28757     * Compiles and appends handlebar templates to the search results area
28758     */
28759    loadTemplate: function (targetSelector, incomingdata, template, rebindPagination) {
28760        rebindPagination = rebindPagination || 0; //optional parameter
28761        incomingdata.searchterm = this.getSearchTerm();
28762        incomingdata.general.query = incomingdata.general.query.concat("**").replace(/[^a-z\s]+[*]/g, '');
28763        jQuery(targetSelector).append(template(incomingdata));
28764        var pediaED = '.ed-time-timer.pedia', adultED = '.ed-time-timer.adult';
28765        if (jQuery(pediaED).length>0) {
28766          this.initWaitTimes(pediaED, true);
28767        }
28768        if (jQuery(adultED).length>0) {
28769          this.initWaitTimes(adultED, false);
28770        }
28771        if(rebindPagination){
28772            this.bindOrganicPagination();
28773        }
28774    },
28775    /**
28776     * Shows the spinner
28777     * @param isPaginating
28778     */
28779    startWaitState: function (isPaginating) {
28780        if ( !($('#spinner-home').is(':visible') )){
28781            $body = jQuery('body');
28782            $body.css("cursor", "wait");
28783            jQuery("#spinner-home").addClass("active");
28784            //mobile overlay
28785            jQuery('.search-results-list-overlay').removeClass('active');
28786            $body.css("overflow-x", "");
28787            jQuery("#spinner-container").show();
28788        }
28789    },
28790    /**
28791     * Hides the spinner
28792     */
28793    endWaitState: function () {
28794        jQuery("body").css("cursor", "default");
28795        jQuery("#spinner-home").removeClass("active");
28796        jQuery("#spinner-container").hide();
28797        jQuery('#spinner-home').html(jQuery('#spinner-container')); // put it back in case I moved it
28798    },
28799    fireResultsFetched: function() {
28800        var e = jQuery.Event("shcResultsRetrieved");
28801        jQuery(window).trigger(e);
28802    },
28803    prependSearchTermToPageTitle: function(searchTerm) {
28804        var $title = jQuery("head title");
28805        var currentTitle = $title.text();
28806
28807        if(currentTitle.indexOf(searchTerm) === -1) {
28808            $title.text(searchTerm + " | " + currentTitle);
28809        }
28810    },
28811    isSpinnerMapText: function(status){
28812        /* when going from grid or list to map view, it will display the map text on the spinner. The user can still
28813         * click other filters, this aborts the current request and sends a new one, when this occurs we want to keep
28814         * the already on screen spinner if:
28815         *  - the 1st filter request was aborted
28816         *  - the spinner map text is already visible
28817         *  - the view toggle exists and it has the map view selected
28818         */
28819        var mapSpinnerTextInView = $('#spinner-text.map-wait-text').is(':visible');
28820        var selectedView = '';
28821        if ($('.grid-list-toggle').length === 1){
28822            selectedView = $('.grid-list-toggle .active').attr('class').replace('active','').trim();
28823        }
28824        if(status === 'abort' && selectedView === 'map-view-icon' && mapSpinnerTextInView){
28825            return true;
28826        }else{
28827            return false;
28828        }
28829    },
28830    /**
28831     * Modifies a clinic or doctor search query that involves zip code filter to do another search upon
28832     * no results and show the nearest results to the user. Accepts same paramaters as searchSuccessCallback
28833     * @param data
28834     * @param doer
28835     * @param calledFromStartSearch
28836     * @param isPaginating
28837     * @param mobileFilter
28838     * @param onSuccessCallback
28839     * @param Q
28840     */
28841    handleNoResultsForDistanceQuery: function(data, doer, calledFromStartSearch, isPaginating, mobileFilter, onSuccessCallback, Q) {
28842        var that = this;
28843
28844        if (SHC.ui.Search.DirectoryUtil.isDoctorDirectoryPage()) {
28845            var distanceQueryJSON = JSON.parse(Q);
28846            // if no results and it's a distance query, requery with "Any Distane" to show closest results
28847            distanceQueryJSON.radius = "10000";
28848            Q = JSON.stringify(distanceQueryJSON);
28849            that.fromNoResults = true;
28850            that.noResultsZipCode = distanceQueryJSON.zip;
28851            // might differ from data.selectedZipCode
28852            data.queriedZipCode = distanceQueryJSON.zip;
28853            SHC.searchRequest = jQuery.ajax({
28854                method: "POST",
28855                url: "/bin/api/v1/content/doctorsbyclinic",
28856                data: Q,
28857                dataType: "json",
28858                contentType: "application/json",
28859                success: function (data) {
28860                    that.searchSuccessCallback(data, doer, calledFromStartSearch, isPaginating, mobileFilter, onSuccessCallback, Q);
28861                    $(window).trigger("nearestDoctorResultsShowing");
28862                },
28863                error: function (xhr, status, error) {
28864                    if (status === 'abort') {
28865                        console.log("Ajax manually aborted");
28866                    } else {
28867                        console.log("results binder error:", xhr, status, error);
28868                    }
28869                    if (!that.isSpinnerMapText(status)) {
28870                        that.endWaitState();
28871                    }
28872                }
28873            });
28874        }
28875        else if (SHC.ui.Search.DirectoryUtil.isClinicDirectoryPage()) {
28876            // set these for the hbs template to be called later
28877            that.fromNoResults = true;
28878            that.noResultsZipCode = SHC.util.getZipCodeFromQuery(Q);
28879
28880            var limitedRadiusString = SHC.util.getZipCodeRadiusTerm(Q);
28881            var anyRadiusString = SHC.util.replaceRadiusWithAnyDistance(limitedRadiusString);
28882            var newQ = Q.replace(limitedRadiusString, anyRadiusString);
28883            data.url = data.url.replace(limitedRadiusString, anyRadiusString);
28884            SHC.searchRequest = jQuery.ajax({
28885                url: data.url,
28886                dataType: "jsonp",
28887                jsonp: 'callback',
28888                contentType: "application/json",
28889                success: function (data) {
28890                    that.searchSuccessCallback(data, doer, calledFromStartSearch, isPaginating, mobileFilter, onSuccessCallback, newQ);
28891                    $(window).trigger("nearestClinicResultsShowing");
28892                },
28893                error: function (xhr, status, error) {
28894                    if (status === 'abort') {
28895                        console.log("Ajax manually aborted");
28896                    } else {
28897                        console.log("results binder error:", xhr, status, error);
28898                    }
28899                    if (!that.isSpinnerMapText(status)) {
28900                        that.endWaitState();
28901                    }
28902                }
28903            });
28904        }
28905    },
28906    handleNoResultsMapView: function (data, doer, calledFromStartSearch, isPaginating, mobileFilter, onSuccessCallback, Q) {
28907
28908        var that = this;
28909        that.fromNoResults = true;
28910
28911        // set these for the hbs template to be called later
28912        that.fromNoResults = true;
28913        var filterToggleInUrl = '';
28914        var href = window.location.href;
28915        var suffix = '';
28916        href = href.replace('#x1=', '&x1=').replace('#q1=', '&q1=');
28917        if (href.indexOf('&q1=') > href.indexOf('&x1=')){
28918            var extractToggle = href.split('&x1=');
28919            extractToggle = extractToggle[1].split('&q1=');
28920            filterToggleInUrl = extractToggle[0];
28921        }
28922        suffix = filterToggleInUrl != '' ? ("&x1=" + filterToggleInUrl + "&q1=true") : '';
28923        if (SHC.ui.Search.DirectoryUtil.isDoctorDirectoryPage()) {
28924            suffix = suffix === '' ? "&x1=sp_spec_care_phy&q1=true" : suffix;
28925            var contentData = {
28926                baseQuery: "?do=organic_phys&sp_s=sp_lastName" + suffix + "&sp_c=5000",
28927                view: "map",
28928                radius: "",
28929                zip: ""
28930            };
28931            SHC.searchRequest = jQuery.ajax({
28932                method: "POST",
28933                url: "/bin/api/v1/content/doctorsbyclinic",
28934                data: JSON.stringify(contentData),
28935                dataType: "json",
28936                contentType: "application/json",
28937                success: function (data) {
28938                    that.searchSuccessCallback(data, doer, calledFromStartSearch, isPaginating, mobileFilter, onSuccessCallback, Q);
28939                },
28940                error: function (xhr, status, error) {
28941                    if (status === 'abort') {
28942                        console.log("Ajax manually aborted");
28943                    } else {
28944                        console.log("results binder error:", xhr, status, error);
28945                    }
28946                    if (!that.isSpinnerMapText(status)) {
28947                        that.endWaitState();
28948                    }
28949                }
28950            });
28951        } else if (SHC.ui.Search.DirectoryUtil.isClinicDirectoryPage()) {
28952            suffix = suffix === '' ? "&x1=sp_spec_care_clinic&q1=true" : suffix;
28953            data.url = that.CLINIC_MAP_URL_PREFIX + encodeURIComponent("?do=organic_clinics" + suffix + "&sp_c=5000");
28954            SHC.searchRequest = jQuery.ajax({
28955                url: data.url,
28956                dataType: "jsonp",
28957                jsonp: 'callback',
28958                contentType: "application/json",
28959                success: function (data) {
28960                    that.searchSuccessCallback(data, doer, calledFromStartSearch, isPaginating, mobileFilter, onSuccessCallback, Q);
28961                },
28962                error: function (xhr, status, error) {
28963                    if (status === 'abort') {
28964                        console.log("Ajax manually aborted");
28965                    } else {
28966                        console.log("results binder error:", xhr, status, error);
28967                    }
28968                    if (!that.isSpinnerMapText(status)) {
28969                        that.endWaitState();
28970                    }
28971                }
28972            });
28973        }
28974    },
28975    safariShcaRedirectHashCheck: function(){
28976        //all searches in SHCA have hashes, if it does not it means a 
28976safari removed it on the url redirect
28977        if(GLOBAL_SEARCH_RESULTS_TEMPLATE.indexOf('shca') > -1 && $.browser.safari === true){
28978            var cookieUrl = SHC.util.getCookieValueByName('shca-search-url-hash');
28979            //document.cookie = 'shca-search-url-hash=;path=/;domain=localhost;expires=Thu, 01 Jan 1970 00:00:01 GMT;';
28980            document.cookie = 'shca-search-url-hash=;path=/;domain=stanfordhealthcarealliance.org;expires=Thu, 01 Jan 1970 00:00:01 GMT;';
28981            document.cookie = 'shca-search-url-hash=;path=/;domain=stanfordhealthcare.org;expires=Thu, 01 Jan 1970 00:00:01 GMT;';
28982
28983            var currentUrl = window.location.href;
28984            //there is a hash in the cookie, current url has a search term but no hash (should have hash)
28985            if (cookieUrl !== null && currentUrl.indexOf('.html/' > 0) && currentUrl.indexOf('#') < 0){
28986                history.replaceState(null, null, cookieUrl);
28987            }
28988        }
28989    },
28990    clinicalTrialsNotExactMatchGetJSON: function(url, doer, calledFromStartSearch, isPaginating, mobileFilter, onSuccessCallback, Q, searchFromFilterRail){
28991        var that = this;
28992        var searchTerm = Q.split('q13=')[1];
28993        var newQueryUrl = url.split(doer)[0] + doer + '&q=' + searchTerm;
28994
28995        if(calledFromStartSearch){
28996            if(Q.indexOf('NOT_RECRUITING') > -1){
28997                newQueryUrl += '&x1=sp_status&q1=NOT_RECRUITING';
28998            }else if(Q.indexOf('RECRUITING') > -1){
28999                newQueryUrl += "&x1=sp_status&q1=RECRUITING";
29000            }
29001        }
29002        if (Q.indexOf("sp_conditions") === -1 && Q.indexOf("sp_trial_id") === -1) {
29003            newQueryUrl += "&payload=disabled" + that.addPredictiveParameter(newQueryUrl);
29004        } else { //in this case a filter has been pre-selected in the url, so we force the exact match template to load
29005            searchFromFilterRail = true;
29006            SHC.clinicalTrialsFilter.nonExactClick = true;
29007        }
29008
29009
29010        var parent = this;
29011        SHC.searchRequest = jQuery.ajax({
29012            url: newQueryUrl,
29013            dataType: "jsonp",
29014            jsonp: 'callback',
29015            contentType: "application/json",
29016            success: function (data) {
29017                data.nonExactMatchSearch = true;
29018                data.url = newQueryUrl;
29019                data.searchFromFilterRail = searchFromFilterRail || false;
29020                parent.searchSuccessCallback(data, doer, calledFromStartSearch, isPaginating, mobileFilter, onSuccessCallback, Q);
29021            },
29022            error: function (){
29023                parent.endWaitState();
29024            }
29025        });
29026    },
29027    passthroughBackLinkOverride: function(data){
29028        var clinicUrl = data.selectedClinic.clinicUrl;
29029        if(clinicUrl && clinicUrl.indexOf('/title-override/') > -1){
29030            var passthroughUrlParts = clinicUrl.split('/title-override/');
29031            if (passthroughUrlParts.length === 3){
29032                data.selectedClinic.clinicTitleOverride = passthroughUrlParts[1]; //title for back link
29033                data.selectedClinic.clinicUrl = passthroughUrlParts[2]; //url;
29034            }
29035        }
29036        return data;
29037    },
29038    addPredictiveParameter: function(checkThisString){
29039        if(window.location.href.indexOf('src=pred') > 0 && checkThisString.indexOf('src=pred') === -1){
29040            return '&src=pred';
29041        }else{
29042            return '';
29043        }
29044    },
29045    captureSearchResultClickEvent: function(){
29046        $(document).on("click", ".search-result-link > a", function (e) {
29047            var location = $(this).parent().index();
29048            var pageNumber = $('.search-pagination > ul > li.selected > a').text();
29049            var resultHref = $(this)[0].href;
29050            if(pageNumber === ""){ pageNumber = '1'};
29051            stanford.analytics.send(stanford.analytics.createComponentClickSearchResults(location+1, 'search result', 'general', pageNumber, resultHref));
29052        });
29053        $(document).on("click", '.top-result-title > a, .deep-link-title > a', function (e) {
29054            var pageNumber = $('.search-pagination > ul > li.selected > a').text();
29055            if(pageNumber === ""){ pageNumber = '1'};
29056            var resultHref = $(this)[0].href;
29057            stanford.analytics.send(stanford.analytics.createComponentClickSearchResults(1, 'search result', 'promoted', pageNumber, resultHref));
29058        });
29059    },
29060    captureSearchDirectoryFilter: function(){
29061        $(document).on("click", ".doctor-filter", function (e) {
29062            stanford.analytics.send(stanford.analytics.createComponentSearchDirectoryFilter('directory | doctors', 'refine'));
29063        });
29064        $(document).on("click", ".clinic-filter", function (e) {
29065            stanford.analytics.send(stanford.analytics.createComponentSearchDirectoryFilter('directory | clinics & locations', 'refine'));
29066        });
29067        $(document).on("click", ".condition-filter", function (e) {
29068            stanford.analytics.send(stanford.analytics.createComponentSearchDirectoryFilter('directory | conditions & treatments', 'refine'));
29069        });
29070        $(document).on("click", ".trials-filter", function (e) {
29071            stanford.analytics.send(stanford.analytics.createComponentSearchDirectoryFilter('directory | clinical trials', 'refine'));
29072        });
29073    }
29074});
29075
29076SHC.Namespace(SHC, "SHC.ui.PredictiveTracking");
29077SHC.ui.PredictiveTracking = new SHC.Class();
29078SHC.ui.PredictiveTracking.include({
29079
29080    init: function () {
29081    },
29082
29083    initializePredictiveTermsEvents: function (term) {
29084        const resultSections = document.querySelectorAll('#search-results .search-results-section');
29085        function initializeResultLinkEventListener(resultLink, resultHeading) {
29086            if (resultLink) {
29087                const selectedSuggestion = resultLink.textContent.replaceAll('\n', '');
29088                resultLink.addEventListener("click", function () {
29089                    stanford.analytics.send(
29090                        {
29091                            event: "Search",
29092                            search: {
29093                                info: {
29094                                    term: term,
29095                                    selectedSuggestion: selectedSuggestion
29096                                },
29097                                category: {
29098                                    primary: 'predictive',
29099                                    type: resultHeading
29100                                }
29101                            }
29102                        }
29103                    );
29104                });
29105            }
29106        }
29107
29108        function initializeResultSectionLinks(resultSection) {
29109            if (resultSection) {
29110                const resultsLinks = resultSection.querySelectorAll('.link-item a, .view-more a');
29111                const resultHeading = resultSection.querySelector('.search-result-heading').textContent;
29112                if (resultsLinks) {
29113                    resultsLinks.forEach(function (resultLink) {
29114                        initializeResultLinkEventListener(resultLink, resultHeading)
29115                    })
29116                }
29117            }
29118        }
29119
29120        if (resultSections) {
29121            resultSections.forEach(initializeResultSectionLinks);
29122        }
29123    },
29124
29125    initializePredictiveSuggestedLinkEvents: function (term) {
29126        const predictiveSuggestions = document.querySelectorAll('#search-results #search-suggestions');
29127
29128        function initializePredSuggestedLink (predictiveSuggestedLink, suggestedSearchHeading) {
29129            if (predictiveSuggestedLink) {
29130                const selectedSuggestion = predictiveSuggestedLink.textContent.replaceAll('\n', '');
29131                predictiveSuggestedLink.addEventListener("click", function () {
29132                    stanford.analytics.send(
29133                        {
29134                            event: "Search",
29135                            search: {
29136                                info: {
29137                                    term: term,
29138                                    selectedSuggestion: selectedSuggestion
29139                                },
29140                                category: {
29141                                    primary: 'suggested',
29142                                    type: suggestedSearchHeading
29143                                }
29144                            }
29145                        }
29146                    );
29147                });
29148            }
29149        }
29150
29151        function initializePredSuggestedLinks(predictiveSuggestion) {
29152            const suggestedSearchHeading = predictiveSuggestion.querySelector('.suggested-searches-heading').textContent.replaceAll('\n', '');
29153            const predictiveSuggestedLinks = predictiveSuggestion.querySelectorAll('.link-item a');
29154            if (predictiveSuggestedLinks) {
29155                predictiveSuggestedLinks.forEach(
29156                    function (predictiveSuggestedLink) {
29157                       initializePredSuggestedLink(predictiveSuggestedLink, suggestedSearchHeading)
29158                    }
29159                )
29160            }
29161        }
29162
29163        if (predictiveSuggestions) {
29164            predictiveSuggestions.forEach(initializePredSuggestedLinks);
29165        }
29166    }
29167});
29168
29169SHC.Namespace(SHC, "SHC.ui.Search.Dropdown.Filter");
29170SHC.ui.Search.Dropdown.Filter = new SHC.Class();
29171
29172SHC.ui.Search.Dropdown.Filter.include({
29173    init: function() {
29174        this.$filterArea = jQuery("#dropdown-filter");
29175        this.window = jQuery(window);
29176        this.dropdownUtil = new SHC.ui.Search.DropdownUtil();
29177
29178        this.filterToggleMap = [];
29179        this.filterToggleMap["doctors-filter-toggle-primary-care"] = {filter: "sp_prim_care_phy", value: "true"};
29180        this.filterToggleMap["doctors-filter-toggle-specialist"] = {filter: "sp_spec_care_phy", value: "true"};
29181        this.filterToggleMap["clinics-filter-toggle-specialty-care"] = {filter: "sp_spec_care_clinic", value: "true"};
29182        this.filterToggleMap["clinics-filter-toggle-primary-care"] = {filter: "sp_prim_care_clinic", value: "true"};
29183        this.filterToggleMap["clinics-filter-toggle-other-service"] = {filter: "sp_other_service", value: "true"};
29184        this.filterToggleMap["conditions-filter-toggle-all"] = {filter: null, value: null};
29185        this.filterToggleMap["conditions-filter-toggle-conditions"] 
29185= {filter: "sp_type", value: "condition"};
29186        this.filterToggleMap["conditions-filter-toggle-treatments"] = {filter: "sp_type", value: "treatment"};
29187
29188        this.alphabetFilter = null;
29189        this.medicalCategoryFilter = null;
29190
29191        this.specialtyFilter = null;
29192        this.subSpecialtyFilter = null;
29193        this.clinicSpecialtyFilter = null;
29194
29195        this.primaryCareFilter = null;
29196        this.doctorTypeFilter = null;
29197
29198        this.clinicFeaturesFilter = null;
29199        this.clinicCareForFilter = null;
29200        this.specialInterestsFilter = null;
29201
29202        this.sortByFilter = null;
29203        this.genderFilter = null;
29204        this.languageFilter = null;
29205        this.serviceTypeFilter = null;
29206        this.distanceFilter = null;
29207
29208        this.conditionFilter = null;
29209        this.trialIdFilter = null;
29210        this.recruitingFilter = null;
29211
29212        this.year = null;
29213        this.category = null;
29214        this.categorycb = null;
29215
29216        this.filtersPopd = false;                                                // Used to determine if any filters have been selected in order to turn off/on the reset and apply filters options.
29217
29218        //This is to maintain select state on Doctor Type filter
29219        this.doctorFilterState = false;
29220
29221        this.handlebarsTarget = $('#handlebars-target');
29222
29223        if(SHC.ui.Search.DirectoryUtil.isSearchResultsPage()) {
29224            this.bindToggleFilter();
29225            this.bindGridListToggle();
29226            this.bindSearchResultsFilterMenus();
29227            this.bindAutoCompleteSelectBoxes();
29228            this.bindToSpecialtiesLoadedEvent();
29229            this.bindSortByController();
29230            this.initDistanceFilter();
29231            this.initRadioBtnFilter();
29232            this.initYearFilter();
29233            this.keepCurrentViewOnSpecPrimToggle();
29234            this.keepCurrentViewSearchResultsClicks();
29235        }
29236
29237        var subSpecialtyOptions = null;
29238        var doctorTypeOptions = null;
29239        var subTypeOptions = null;
29240    },
29241
29242    /* Make Filter Request */
29243    makeFilterRequest: function(params) {
29244
29245        var toggleValueChanged = false,
29246            mobileFilter = false,
29247            applyFilter = false,
29248            callback = null,
29249            searchFromFilterRail = false;
29250        if (params) {
29251            toggleValueChanged = params.toggleValueChanged || false;
29252            mobileFilter = params.mobileFilter || false;
29253            applyFilter = params.mobileFilter || false;
29254            searchFromFilterRail = params.searchFromFilterRail || false;
29255            callback = params.callback || null;
29256        }
29257
29258        if (mobileFilter){
29259            this.setMobileFilterClickedOverlay();
29260        }
29261
29262        var requestMap = [];
29263        // get active toggle filter
29264        // IMPORTANT: Ensure the toggle value is always the first item in the map as S&P expects
29265        // it to be x1/q1 in the request URL
29266        if($('#directory-filter-toggles .filter-toggle a.active').length > 0) {
29267
29268            var selectedToggle = $('#directory-filter-toggles .filter-toggle a.active').parent().attr('id');
29269            if(selectedToggle) {
29270                var toggleVal = this.filterToggleMap[selectedToggle];
29271                if(toggleVal && toggleVal.filter && toggleVal.value) {
29272                    requestMap[toggleVal.filter] = toggleVal.value;
29273                }
29274            }
29275        }
29276
29277        // only use current filter values if the toggle value didn't change. If the toggle
29278        // value changed then we want to reset the other filter values
29279        if(!toggleValueChanged) {
29280            if(this.alphabetFilter) {
29281                requestMap['sp_alpha'] = this.alphabetFilter;
29282            }
29283
29284            if(this.medicalCategoryFilter) {
29285                requestMap['sp_med_categories'] = this.medicalCategoryFilter;
29286            }
29287
29288            if(this.specialtyFilter) {
29289                requestMap['sp_dr_title_groups'] = this.specialtyFilter;
29290            }
29291
29292            if(this.subSpecialtyFilter) {
29293                requestMap['sp_dr_titles'] = this.subSpecialtyFilter;
29294            }
29295
29296            if(this.clinicSpecialtyFilter) {
29297                requestMap['sp_dr_title_groups'] = this.clinicSpecialtyFilter;
29298            }
29299
29300            if(this.primaryCareFilter) {
29301                // strip out (OB/GYN) for the S&P request
29302                if (this.primaryCareFilter === 'Women Only (OB/GYN)') {
29303                    this.primaryCareFilter = 'Women Only';
29304                }
29305                requestMap['sp_prim_care_types'] = this.primaryCareFilter;
29306            }
29307
29308            if(this.doctorTypeFilter) {
29309                requestMap['sp_dr_titles'] = this.doctorTypeFilter;
29310            }
29311
29312            if(this.sortByFilter){
29313                requestMap['sp_s'] = this.sortByFilter;
29314            }
29315
29316            if(this.genderFilter) {
29317                requestMap['sp_gender'] = this.genderFilter;
29318            }
29319
29320            if(this.languageFilter) {
29321                requestMap['sp_languages'] = this.languageFilter;
29322            }
29323
29324            if(this.clinicFeaturesFilter) {
29325                requestMap['sp_clinic_features'] = this.clinicFeaturesFilter;
29326            }
29327
29328            if(this.clinicCareForFilter) {
29329                requestMap['sp_doctor_types'] = this.clinicCareForFilter;
29330            }
29331
29332            if(this.specialInterestsFilter) {
29333                requestMap['sp_special_interests'] = this.specialInterestsFilter;
29334            }
29335
29336            if(this.serviceTypeFilter) {
29337                requestMap['sp_other_servc_types'] = this.serviceTypeFilter;
29338            }
29339
29340            if(this.distanceFilter && this.distanceFilter.validZipCodeEntered) {
29341                var proximity = this.distanceFilter.getProximity();
29342                var zipCode = this.distanceFilter.getZipCode();
29343
29344                if(proximity && zipCode) {
29345
29346                    if(SHC.ui.Search.DirectoryUtil.isDoctorDirectoryPage()) {
29347                        if(!params) {
29348                            params = {};
29349                        }
29350                        params.doctorDistanceQuery = true;
29351                        params.radius = proximity;
29352                        params.zip = zipCode;
29353                        if(SHC.ui.Search.DirectoryUtil.getSelectedView() === "map") {
29354                            params.count = "5000";
29355                        }
29356                    }
29357                    else {
29358                        // zip
29359                        requestMap['sp_q_location'] = zipCode;
29360                        requestMap['sp_x'] = "sp_zip";
29361                        // proximity to zip in miles
29362                        requestMap['sp_q_max'] = proximity;
29363                        requestMap['sp_s'] = "sp_zip_proximity";
29364                    }
29365                }
29366            }
29367
29368            if(this.conditionFilter) {
29369                requestMap['sp_conditions'] = this.conditionFilter;
29370            }
29371
29372            if(this.trialIdFilter) {
29373                requestMap['sp_trial_id'] = this.trialIdFilter;
29374            }
29375
29376            if(this.year) {
29377                requestMap['sp_year'] = this.year;
29378            }
29379
29380            if(this.category) {
29381                requestMap['sp_category'] = this.category;
29382            }
29383
29384            if(this.categorycb) {
29385                requestMap['sp_tags'] = this.categorycb;
29386            }
29387
29388            if(SHC.ui.Search.DirectoryUtil.isTrialsDirectoryPage() && this.recruitingFilter) {
29389                requestMap['sp_status'] = this.recruitingFilter;
29390            }
29391
29392        } else {
29393            this.resetFilterValues(this);
29394            if (SHC.savedSearch) {
29395                var savedFilters = SHC.savedSearch[selectedToggle];
29396                if (savedFilters) {
29397                    requestMap = savedFilters;
29398                }
29399            }
29400        }
29401
29402        //we don't want these filters to ever get wiped out unless the user navigates away from the directories
29403        var campaignFilter = SHC.util.getNormalUrlParameter("campaignFilter");
29404        if(campaignFilter && campaignFilter !== "") {
29405            requestMap['campaignFilter'] = campaignFilter;
29406        }
29407        var participatingOrgFilter = SHC.util.getAttrValueFromURL("sp_participating_org");
29408        if (participatingOrgFilter && participatingOrgFilter !== "") {
29409            requestMap['sp_participating_org'] = participatingOrgFilter;
29410        }
29411
29412
29413        var searchResultsBinder = new SHC.ui.Search.ResultsBinder('#search-results-page');
29414
29415        this.setSpinnerOverMap();
29416
29417        searchResultsBinder.filter(GLOBAL_DIRECTORY_OBJECT, requestMap, function() {
29418            // TODO: Add any necessary callback logic
29419            if (callback !== null) {
29420                callback();
29421            }
29422        }, params);
29423    },
29424
29425    bindSortByController: function() {
29426        var that = this;
29427
29428        that.handlebarsTarget.on('click', '.sort-by-selected', function(event) {
29429            event.preventDefault();
29430            event.stopPropagation();
29431            var sortByToggle = $(this).find('.sort-carat');
29432
29433            if(sortByToggle.hasClass('active')){
29434                sortByToggle.removeClass('active');
29435                $('.sort-by-list').css('display', 'none');
29436            } else {
29437                sortByToggle.addClass('active');
29438                $('.sort-by-list').css('display', 'inline-block');
29439
29440                jQuery('body').on('click.closeMenu',function(e) {
29441                    var sortByToggle = $(this).find('.sort-by-selected');
29442
29443                    if ($('.sort-carat').hasClass("active")) {
29444                        if($(e.target).closest(sortByToggle).length === 0) {
29445                            $('.sort-carat').removeClass('active');
29446                            $('.sort-by-list').css('display', 'none');
29447                        }
29448                    }
29449                    jQuery('body').off('click.closeMenu');
29450                });
29451            }
29452        });
29453
29454        that.handlebarsTarget.on('click', '.sort-by-list .sort-option', function() {
29455            var sortByToggle = $(this).find('.sort-carat');
29456
29457            $('.sort-by-selected').html($(this).text() + "<span class=\"sort-carat\"></span>");
29458            sortByToggle.removeClass('active');
29459            $('.sort-by-list').css('display', 'none');
29460            that.sortByFilter = $(this).attr('data-sort-name');
29461            that.makeFilterRequest();
29462        });
29463
29464        if (SHC.util.isIOS()) {
29465            that.handlebarsTarget.on('focus', '.sort-by-list-mobile', function() {
29466                $('.sort-by-selected').find('.sort-carat').addClass('active');
29467            });
29468
29469            that.handlebarsTarget.on('blur', '.sort-by-list-mobile', function() {
29470                $('.sort-by-selected').find('.sort-carat').removeClass('active');
29471            });
29472        }
29473
29474        that.handlebarsTarget.on('change', '.sort-by-toggle-wrapper select', function() {
29475            var selectedValue = this.value;
29476            var options = jQuery('.sort-by-toggle-wrapper ul li');
29477
29478            options.each(function (){
29479                if(this.innerHTML === selectedValue) {
29480                    $(this).trigger('click');
29481                    return false; //break the loop
29482                }
29483            });
29484        });
29485
29486    },
29487
29488    bindGridListToggle: function() {
29489        var that = this;
29490
29491        $(window).on('load',function(){
29492            that.setLastViewToggleClicked();
29493        });
29494
29495        that.handlebarsTarget.on('click', '.list-view-icon, .map-view-icon', function() {
29496            window.google = undefined;
29497            //Sets a cookie based on the first part of the clicked icon's class, grid, list, or map
29498            SHC.util.setCookie('activeView', $(this).attr('class').split('-')[0], 1, "/");
29499            if($(this).hasClass("active")) {
29500                that.setLastViewToggleClicked();
29501                return;
29502            }  else {
29503                that.setLastViewToggleClicked();
29504                $('.grid-list-toggle .active').removeClass('active');
29505                $(this).addClass("active");
29506                that.makeFilterRequest();
29507            }
29508        });
29509
29510        $(window).on('resizeEnd', function () {
29511            // if user resized desktop browser to small size
29512            if(SHC.ui.screenMode === 'small' && !SHC.util.isAndroid() && !SHC.util.isIOS()) {
29513                if($('.list-view-icon').hasClass("active")) {
29514                    return;
29515                } else {
29516                    $('.grid-list-toggle .active').removeClass("active");
29517                    $('.list-view-icon').addClass("active");
29518                    that.makeFilterRequest();
29519                }
29520            }
29521        });
29522        $(window).on('orientationchange', function () {
29523            // if user resized a tablet going from medium breakpoint to small (nexus)
29524            if(SHC.ui.screenMode === 'small') {
29525                if($('.list-view-icon').hasClass("active")) {
29526                    return;
29527                } else if($('.map-view-icon').hasClass("active")) {
29528                    $('.map-list-toggle .active').removeClass("active");
29529                    $('.list-view-icon').addClass("active");
29530                    that.makeFilterRequest({resized: true});
29531                }
29532            }
29533        });
29534    },
29535
29536    bindToggleFilter: function() {
29537        var that = this;
29538        that.handlebarsTarget.on('click', '#directory-filter-toggles .filter-toggle', function() {
29539            var params = {toggleValueChanged:true};
29540            params.sortParam = $('.sort-by-list .active').attr('data-sort-name');
29541            $('#directory-filter-toggles .filter-toggle a.active').removeClass('active');
29542            $('a', this).addClass('active');
29543            that.makeFilterRequest({toggleValueChanged:true, sortParam:$('.sort-by-list .active').attr('data-sort-name')});
29544        });
29545    },
29546    resetFilterValues: function(context) {
29547        context.specialtyFilter = null;
29548        context.subSpecialtyFilter = null;
29549        context.clinicSpecialtyFilter = null;
29550        context.alphabetFilter = null;
29551        context.medicalCategoryFilter = null;
29552        context.genderFilter = null;
29553        context.languageFilter = null;
29554        context.serviceTypeFilter = null;
29555        context.distanceFilter = null;
29556        context.distanceZipCode = null;
29557
29558        context.primaryCareFilter = null;
29559        context.doctorTypeFilter = null;
29560
29561        context.clinicFeaturesFilter = null;
29562        context.clinicCareForFilter = null;
29563        context.specialInterestsFilter = null;
29564
29565        context.conditionFilter = null;
29566        context.trialIdFilter = null;
29567        context.year = null;
29568        context.category = null;
29569        context.categorycb = null;
29570
29571        if(window.location.href.indexOf("sp_trialLocks") !== -1) {
29572            context.recruitingFilter = null;
29573        } else {
29574            context.recruitingFilter = "RECRUITING";
29575        }
29576
29577        SHC.ui.Search.disableDrSpecAutofill = true;
29578
29579       //This is to maintain select state on Doctor Type filter
29580        this.doctorFilterState = false;
29581
29582        jQuery('.cb-option').each(function(){
29583            var input = $(this).find('.cb-input label');
29584            input.removeClass('cb-checked');
29585        });
29586    },
29587
29588    setupCloseFilter: function(openFilter) {
29589        var that = this;
29590        this.window.on('click.filter', function(e){
29591            if (typeof(openFilter) !== 'undefined') {
29592                var $filter = jQuery(openFilter.target).parent().parent();
29593                // Ensure they are clicking outide of the filter
29594                if (!jQuery.contains($filter.get(0), e.target)) {
29595                    $filter.removeClass('visible');
29596                    that.window.off('click.filter');
29597                }
29598            } else {
29599                // openFilter was undefined, find and close any open filters
29600                $('.unfiltered.visible').removeClass('visible');
29601                that.window.off('click.filter');
29602            }
29603        });
29604    },
29605
29606    /**
29607     * A generic function to bind desktop functionality of basic filters.
29608     *
29609     * @param classFilterName whatever the name of the class level variable is such as genderFilter
29610     * @param filterClassSelector .gender or .whatever specific class you gave it in the hbs file
29611     */
29612    bindSimpleFilter: function(classFilterName, filterClassSelector) {
29613        var that = this;
29614        var filterOptionClick = function() {
29615            var selected = jQuery(this);
29616            var mobileDropdown = jQuery('.search-results-filters ' + filterClassSelector + ' select');
29617            mobileDropdown.hide();
29618
29619            if (selected.hasClass('disabled')){
29620                return;
29621            }
29622
29623            if(classFilterName === "alphabetFilter") {
29624                if(selected.hasClass('all')) {
29625                    that.alphabetFilter = null;
29626                } else {
29627                    that.alphabetFilter = jQuery(this).text();
29628                }
29629            } else if(classFilterName === "category"){
29630                that[classFilterName] = $(this).attr('data-attr-category');
29631            }
29632            else {
29633                that[classFilterName] = that.removeCount(jQuery(this).text());
29634            }
29635
29636            if(classFilterName === "subSpecialtyFilter") {
29637                that.specialtyFilter = that.removeCount($(".search-results-filters .specialty .select-title").text());
29638            }
29639            if(classFilterName === "doctorTypeFilter") {
29640                that.primaryCareFilter = that.removeCount($(".search-results-filters .primaryCare .select-title").text());
29641            }
29642
29643            if(SHC.ui.screenMode !== 'small') {
29644                that.makeFilterRequest();
29645            } else {
29646                that.makeFilterRequest({mobileFilter:true});
29647            }
29648        }
29649        this.handlebarsTarget.on('click', '.search-results-filters ' + filterClassSelector + ' li', filterOptionClick);
29650        $('.newsroom-landing').on('click', '.collection.directory ' + filterClassSelector + ' li', filterOptionClick);
29651    },
29652
29653    prepareAutoCompleteFilterRequest: function(element) {
29654        var that = this;
29655        var $filterRail = $('.search-results-filters');
29656        var $elParent = $(element).closest('.auto-complete-filter');
29657        var flag = false;
29658        if ($elParent.hasClass('trials-condition')) {
29659            var condVal = that.removeCount($filterRail.find(".trials-condition input").val());
29660            if(that.conditionFilter !== condVal) {
29661                that.conditionFilter = condVal;
29662                flag = true;
29663            }
29664        }
29665        if ($elParent.hasClass('trials-ids')) {
29666            var idVal = $filterRail.find(".trials-ids input").val();
29667            if (that.trialIdFilter !== idVal) {
29668                that.trialIdFilter = idVal;
29669                flag = true;
29670            }
29671        }
29672        if (flag){
29673            that.makeTrialsFilterRequest($filterRail);
29674        }
29675    },
29676
29677    makeTrialsFilterRequest: function($filterRail) {
29678        var that = this;
29679        var isMobile = SHC.ui.screenMode === 'small' ? true : false;
29680        var $resetFilter = $filterRail.find('.reset-filter');
29681        var $applyFilter = $filterRail.find('.apply-filter');
29682        if (!isMobile) {
29683            that.makeFilterRequest();
29684        } else {
29685            $resetFilter.addClass('vis-on');
29686            $applyFilter.addClass('vis-on');
29687
29688            that.makeFilterRequest({mobileFilter:true, searchFromFilterRail:true});
29689        }
29690    },
29691
29692    /**
29693     * IMPORTANT: The value of your mobile select option is how we select the desktop element on which
29694     * we trigger a click when the option is selected. If your desktop filter stores the values of your mobile
29695     * options within li elements, like in the cases of gender, language, medical-category filters, etc..
29696     * you can just use this function by passing your filter's specific class.
29697     *
29698     * However, if option values produce something like alphaFilter_a which corresponds to the first li's class
29699     * in the desktop filter, you must add a else if case to select your desktop element specific to the value
29700     * of the mobile select option that was selected.
29701     *
29702     * @param filterClassSelector
29703     */
29704    bindMobileFilter: function(filterClassSelector) {
29705        var that = this;
29706        this.handlebarsTarget.on('change', '.search-results-filters ' + filterClassSelector + ' select', function() {
29707            var selectedValue = that.removeCount(jQuery(this).val());
29708            var realElement = "";
29709            if(filterClassSelector === ".specialty") {
29710                realElement = jQuery('.search-results-filters .specialty li#' + selectedValue);
29711            } else if(filterClassSelector === ".clinic-specialty") {
29712                realElement = jQuery('.search-results-filters .clinic-specialty li#' + selectedValue);
29713            } else if(filterClassSelector === ".alphabet") {
29714                realElement = jQuery('.search-results-filters .alphabet .' + selectedValue);
29715            } else if(filterClassSelector === ".primaryCare") {
29716                realElement = jQuery('.search-results-filters .primaryCare li#' + selectedValue);
29717            } else if(filterClassSelector === ".distance") {
29718                realElement = jQuery(".search-results-filters .distance li[data-value='"+ selectedValue +"']");
29719            } else {
29720                realElement = jQuery('.search-results-filters ' + filterClassSelector + ' li').filter(function() {
29721                    return that.removeCount(jQuery(this).text()) === selectedValue;
29722                });
29723            }
29724            realElement.trigger('click');
29725        });
29726    },
29727    /**
29728     * A generic function to bind desktop functionality of multi-select checkbox filters.
29729     *
29730     * @param classFilterName whatever the name of the class level variable is such as clinicFeaturesFilter
29731     */
29732    bindMultiSelectCB: function(classFilterName, filterClassSelector) {
29733        var that = this;
29734        this.handlebarsTarget.on('click', '.search-results-filters ' + filterClassSelector + ' .cb-input', function() {
29735            var selected = jQuery(this);
29736            var clickedCb = $(selected).find('label');
29737            var filterSelector = filterClassSelector;
29738            var filterText = '';
29739            var orFilterText = '';
29740
29741            if (selected.hasClass('cb-disabled')) {
29742                return;
29743            }
29744
29745            if (clickedCb.hasClass('cb-checked')) {
29746                clickedCb.removeClass('cb-checked');
29747            } else{
29748                clickedCb.addClass('cb-checked');
29749            }
29750
29751            that[classFilterName] = [];
29752            var i = 0;
29753
29754            clickedCb.parents('.cb-options-list').find('.cb-option').each(function(){
29755                var input = $(this).find('.cb-input label');
29756                filterText = that.removeCount($(this).find('.cb-label span').text());
29757                if ($(this).parents('.select-group.categorycb').length > 0){
29758                    filterText = input.attr('data-attr-categorycb');
29759                }
29760                if ($(input).hasClass('cb-checked')) {
29761                    if (filterClassSelector !== '.special-interests' && filterClassSelector !== '.categorycb') {
29762                        that[classFilterName][i] = filterText;
29763                        i++;
29764                    } else {
29765                        orFilterText = filterText + '|' + orFilterText;
29766                    }
29767                }
29768            });
29769
29770            if (orFilterText !== '') {
29771                that[classFilterName][i] = orFilterText.substring(0, orFilterText.length - 1);
29772                i = 1;
29773            }
29774
29775            if (i === 1 && filterClassSelector !== '.special-interests' && filterClassSelector !== '.categorycb') {
29776                var singleVal = that[classFilterName][0];
29777                // TODO: pending resolution of RSW-6437 the following two lines are removed. After resolution remove comments and the following workaround code "that[classFilterName][1] = singleVal; "
29778                //that[classFilterName] = null;
29779                //that[classFilterName] = singleVal;
29780                that[classFilterName][1] = singleVal;
29781            }
29782            else if (i === 0) {
29783                that[classFilterName] = null;
29784            }
29785
29786            if(SHC.ui.screenMode !== 'small') {
29787                that.makeFilterRequest();
29788            } else {
29789                that.makeFilterRequest({mobileFilter:true});
29790            }
29791        });
29792    },
29793
29794    initYearFilter: function () {
29795        //set this.year from URL at init so that it persists
29796        this.year = SHC.util.getAttrValueFromURL('sp_year'); 
29797    },
29798    /**
29799     * Bind events to the search results filters
29800     */
29801    bindSearchResultsFilterMenus: function() {
29802        var that = this;
29803        /* Add visible class to dropdown boxes to activate arrow transform in CSS*/
29804        var toggleDropdown = function(e) {
29805            e.stopPropagation();
29806            that.setupCloseFilter(e);
29807            if ($(this).find('.no-pref').length === 0){
29808                var parentSelectGroup = $(this).parent();
29809                // close all other open dropdowns
29810                $('.select-group').not(parentSelectGroup).removeClass("visible");
29811                parentSelectGroup.toggleClass("visible");
29812            }
29813        };
29814        that.handlebarsTarget.on('click', '.search-results-filters .select-box ', toggleDropdown);
29815        $('.newsroom-landing').on('click', '.collection.directory .select-box ', toggleDropdown);
29816
29817        that.handlebarsTarget.on('click', '.search-results-filters .refine-box ', function() {
29818            if($('.search-results-list-overlay').length === 0){
29819                $('body').append('<div class="search-results-list-overlay"></div>');
29820            }
29821            var overlay = $('.search-results-list-overlay');
29822
29823            if ($(this).find('.no-pref').length === 0){
29824                jQuery(this).parent().toggleClass('visible');
29825            }
29826
29827            if($('.search-results-filters').hasClass('visible')){
29828                var searchResultsList = $('.search-results-list');
29829                var totalHeight = $('.search-results-list').height();
29830
29831                //different selector for exact match results list - using the class: search-results-list applies global CSS styles we dont want on exact match
29832                if(SHC.util.pathContains(TRIAL_DIRECTORY_PAGE, window.location.pathname) && ($('.trials-by-condition.exact-match').length) > 0){
29833                    searchResultsList = $('.trials-condition-results');
29834                    totalHeight = SHC.util.clinicalTrialsMobileExactMatchOverlayHeight();
29835                }else if(SHC.util.pathContains(TRIAL_DIRECTORY_PAGE, window.location.pathname) && ($('.clinical-trials-directory.non-exact-match').length) > 0){
29836                    totalHeight = SHC.util.clinicalTrialsMobileNonExactMatchOverlayHeight();
29837                }
29838
29839                var searchResultTopMargin = parseInt(searchResultsList.css('padding-top').replace('px',''));
29840                var position = searchResultsList.offset();
29841                overlay.css( { "left": position.left, "right": "20px","top": position.top + searchResultTopMargin, "height": totalHeight });
29842                overlay.addClass('active');
29843                //prevents horizontal scrolling while overlay is active.
29844                $('body').css("overflow-x", "hidden");
29845                that.setDynamicFooterMargin();
29846                $(this).parent().find('.trial-filter').each(function(e){
29847                    $(this).addClass('visible');
29848                });
29849            }
29850            else{
29851                overlay.removeClass('active');
29852                $('body').css("overflow-x", "");
29853                $('.footer-margin').css('margin-top', '40px');
29854                $(this).parent().find('.trial-filter').each(function(e){
29855                    $(this).removeClass('visible');
29856                });
29857            }
29858
29859            $('.filter-toggle-wrapper').on('click',function(){
29860                overlay.removeClass('active');
29861                $('body').css("overflow-x", "");
29862                $('.footer-margin').css('margin-top', '40px');
29863            });
29864        });
29865
29866        /* Bind Medical Categories */
29867        this.bindSimpleFilter("medicalCategoryFilter", ".medical-categories");
29868        this.bindMobileFilter(".medical-categories");
29869
29870        /* Bind Gender Filter */
29871        this.bindSimpleFilter("genderFilter", ".gender");
29872        this.bindMobileFilter(".gender");
29873
29874        /* Bind Alphabet Filter */
29875        this.bindSimpleFilter("alphabetFilter", ".alphabet");
29876        this.bindMobileFilter(".alphabet");
29877
29878        /* Bind Sub-specialty Filter */
29879        this.bindSimpleFilter("subSpecialtyFilter", ".sub-specialty.unfiltered");
29880        this.bindMobileFilter(".sub-specialty.unfiltered");
29881
29882        /* Bind Clinic Specialty Filter */
29883        this.bindSimpleFilter("clinicSpecialtyFilter", ".clinic-specialty.unfiltered");
29884        this.bindMobileFilter(".clinic-specialty");
29885
29886        /* Bind DocType Filter */
29887        this.bindSimpleFilter("doctorTypeFilter", ".docType.unfiltered");
29888        this.bindMobileFilter(".docType.unfiltered");
29889
29890        /* Bind Language Filter */
29891        this.bindSimpleFilter("languageFilter", ".language");
29892        this.bindMobileFilter(".language");
29893
29894        /* Bind Service Type Filter */
29895        this.bindSimpleFilter("serviceTypeFilter", ".service-type");
29896        this.bindMobileFilter(".service-type");
29897
29898        this.bindSimpleFilter("year", ".year")
29899        this.bindMobileFilter(".year");
29900
29901        this.bindSimpleFilter("category", ".category")
29902        this.bindMobileFilter(".category");
29903
29904        /* Bind Multi-Select Clinics Features Checkbox*/
29905        this.bindMultiSelectCB("clinicFeaturesFilter", ".clinic-features");
29906
29907        /* Bind Multi-Select Clinic Provides Care for Checkbox */
29908        this.bindMultiSelectCB("clinicCareForFilter", ".clinic-care-for");
29909
29910        /* Bind Multi-Select Clinic Provides Care for Checkbox */
29911        this.bindMultiSelectCB("specialInterestsFilter", ".special-interests");
29912
29913        /* Bind Multi-Select Newsroom Category Type Checkbox */
29914        this.bindMultiSelectCB("categorycb", ".categorycb");
29915
29916        /* Bind Clinical Trials Filters */
29917        this.bindRadioBtnFilter(".trials-recruiting");
29918
29919        this.bindMobileFilter(".distance");
29920
29921        if (SHC.util.isIOS()) {
29922            that.handlebarsTarget.on('focus', '.search-results-filters select', function(){
29923                jQuery(this).closest('.select-group').find('.select-arrow').addClass('open');
29924            });
29925
29926            that.handlebarsTarget.on('blur', '.search-results-filters select', function(){
29927                jQuery(this).closest('.select-group').find('.select-arrow').removeClass('open');
29928            });
29929
29930        }
29931
29932        /* Bind Specialty Filter */
29933        that.handlebarsTarget.on('click', '.search-results-filters .specialty li', function() {
29934
29935            var selected = jQuery(this);
29936
29937            that.specialtyFilter = that.removeCount(selected.text());
29938            that.subSpecialtyFilter = null;
29939            var parent = selected.parents('.select-group');
29940            var subSpecialties = jQuery("#doctors-specialties-filter-target .sub-specialty");
29941            var mobileSpecialtyDropdown = jQuery('.search-results-filters .specialty select');
29942            mobileSpecialtyDropdown.hide();
29943            var resetFilter = jQuery(".reset-filter");
29944
29945            if(SHC.ui.screenMode !== 'small') {
29946                that.makeFilterRequest();
29947                if(resetFilter.hasClass("vis-on") === false){
29948                    resetFilter.addClass("vis-on");
29949                }
29950            } else {
29951
29952                that.makeFilterRequest({mobileFilter: true, callback: function(){
29953                    parent.find('.select-title').text(that.removeCount(selected.text()));
29954                    parent.toggleClass('visible');
29955
29956                    // Hide previous filter prior to re-showing only the applicable ones to the selected Specialty.
29957                    if(subSpecialties.hasClass('visible')) {
29958                        subSpecialties.removeClass('visible');
29959                    }
29960
29961                    subSpecialties.find('li').hide();
29962                    subSpecialties.find('option').hide().prop('hidden', true);
29963
29964                    //Re-shows sub-specialty drop down filtered by specialty options.
29965                    subSpecialties.find("li." + selected.attr("id")).show();
29966                    subSpecialties.find("option." + selected.attr("id")).show().prop('hidden', false); // show mobile menu too.
29967
29968                    //Sets default value for Sub-specialty when new primary Specialty selected.
29969                    $('.select-title', subSpecialties).text('No Preference');
29970                }});
29971
29972                //Sets default value for Sub-specialty when new primary Specialty selected.
29973                $('.select-title', subSpecialties).text('No Preference');
29974            }
29975
29976        });
29977
29978        /* Bind Mobile Specialty Filter */
29979        this.bindMobileFilter(".specialty");
29980
29981        /* Bind Primary Care Filter */
29982        that.handlebarsTarget.on('click', '.search-results-filters .primaryCare li', function() {
29983            var selected = jQuery(this);
29984
29985            if (selected.attr('value')) {
29986                that.primaryCareFilter = selected.attr('value');
29987            }else {
29988                that.primaryCareFilter = that.removeCount(selected.text());
29989            }
29990
29991            that.doctorTypeFilter = null;
29992            var parent = selected.parents('.select-group');
29993            var docTypes = jQuery("#doctor-types-filter-target .docType");
29994            var mobileSpecialtyDropdown = jQuery('.search-results-filters .primaryCare select');
29995            mobileSpecialtyDropdown.hide();
29996            var resetFilter = jQuery(".reset-filter");
29997
29998            if(SHC.ui.screenMode !== 'small') {
29999                that.makeFilterRequest();
30000                if(resetFilter.hasClass("vis-on") === false){
30001                    resetFilter.addClass("vis-on");
30002                }
30003            } else {
30004                that.makeFilterRequest({mobileFilter: true, callback: function(){
30005                    parent.find('.select-title').text(that.removeCount(selected.text()));
30006                    parent.toggleClass('visible');
30007
30008                    // Hide previous filter prior to re-showing only the applicable ones to the selected primaryCare.
30009                    if(docTypes.hasClass('visible')) {
30010                        docTypes.removeClass('visible');
30011                    }
30012
30013                    docTypes.find('li').hide();
30014                    docTypes.find('option').hide().prop('hidden', true);
30015
30016                    //Re-shows docType drop down filtered by primaryCare options.
30017                    docTypes.find("li." + selected.attr("id")).show();
30018                    docTypes.find("option." + selected.attr("id")).show().prop('hidden', false); // show mobile menu too.
30019
30020                    //Sets default value for docType when new primary primaryCare selected.
30021                    $('.select-title', docTypes).text('docType');
30022                }});
30023
30024                //Sets default value for docType when new primary primaryCare selected.
30025                $('.select-title', docTypes).text('docType');
30026            }
30027
30028        });
30029
30030        /* Bind Mobile Primary Care Filter */
30031        this.bindMobileFilter(".primaryCare");
30032
30033        /*  Reset Filters Button */
30034        that.handlebarsTarget.on('click', '.reset-filter a', function() {
30035            that.setMobileFilterClickedOverlay();
30036            that.doctorFilterState = false;                                 //This is to maintain select state on Doctor Type filter
30037
30038            that.clinicFeaturesFilter = null;
30039            that.clinicCareForFilter = null;
30040            that.specialInterestsFilter = null;
30041
30042            //grab the current toggle
30043            var toggle = $('.filter-toggle .active').closest('.filter-toggle').attr('id');
30044            var toggleFilters = SHC.savedSearch[toggle];
30045            if (toggleFilters){
30046                for (var filterName in toggleFilters){
30047                    SHC.util.removeFilter(filterName);
30048                }
30049            }
30050
30051            that.resetFilterValues(that);
30052            that.makeFilterRequest();
30053        });
30054
30055        /* Apply Filters Button */
30056        that.handlebarsTarget.on('click', '.apply-filter', function() {
30057            var specialtyDiv = $(".search-results-filters .specialty .select-title");
30058            var subSpecialtyDiv = $(".search-results-filters .sub-specialty .select-title");
30059            var clinicSpecialtyDiv = $(".search-results-filters .clinic-specialty .select-title");
30060            var primaryCareDiv = $(".search-results-filters .primaryCare .select-title");
30061            var docTypeDiv = $(".search-results-filters .docType .select-title");
30062            var alphabetDiv = $(".search-results-filters .alphabet .select-title");
30063            var medicalCategoryDiv = $(".search-results-filters .medical-categories .select-title");
30064            var genderDiv= $(".search-results-filters .gender .select-title");
30065            var languageDiv = $(".search-results-filters .language .select-title");
30066            var serviceTypeText = that.removeCount($(".search-results-filters .service-type .select-title").text());
30067            var distanceFromZipCode = that.distanceFilter.getProximity();
30068            var zipCode = that.distanceFilter.getZipCode();
30069
30070            var filtersDiv = $('.search-results-filters');
30071            var conditionDiv = filtersDiv.find('.trials-condition input');
30072            var trialIdDiv = filtersDiv.find('.trials-ids input');
30073
30074            that.setMobileFilterClickedOverlay();
30075            that.setDynamicFooterMargin();
30076
30077            //Check if specialty is available before checking value, otherwise bad data returned
30078            if (specialtyDiv.length > 0) {
30079                if (specialtyDiv.text() !== "No Preference") {
30080                    that.specialtyFilter = that.removeCount(specialtyDiv.text());
30081                }
30082                if (subSpecialtyDiv.text() !== "No Preference") {
30083                    that.subSpecialtyFilter = that.removeCount(subSpecialtyDiv.text());
30084                }
30085            }
30086            //Check if clinic specialty is available before checking value, otherwise bad data returned
30087            if (clinicSpecialtyDiv.length > 0) {
30088                if (clinicSpecialtyDiv.text() !== "No Preference") {
30089                    that.clinicSpecialtyFilter = that.removeCount(clinicSpecialtyDiv.text());
30090                }
30091            }
30092            //Check if primary care is available before checking value, otherwise bad data returned
30093            if (primaryCareDiv.length > 0) {
30094                if (primaryCareDiv.text() !== "No Preference") {
30095                    that.primaryCareFilter = that.removeCount(primaryCareDiv.text());
30096                }
30097                if (docTypeDiv.text() !== "No Preference") {
30098                    that.doctorTypeFilter = that.removeCount(docTypeDiv.text());
30099                }
30100            }
30101            if (alphabetDiv.text().indexOf('A-Z') === -1) {
30102                that.alphabetFilter = alphabetDiv.text();
30103            }
30104            //Check if medical category filter is available before checking value, otherwise bad data returned.
30105            if (medicalCategoryDiv.length > 0) {
30106                if (medicalCategoryDiv.text() !== "No Preference") {
30107                    that.medicalCategoryFilter = that.removeCount(medicalCategoryDiv.text());
30108                }
30109            }
30110            if (genderDiv.text() !== "No Preference") {
30111                that.genderFilter = that.removeCount(genderDiv.text());
30112            }
30113            if (languageDiv.text() !== "English") {
30114                that.languageFilter = that.removeCount(languageDiv.text());
30115            }
30116            if(serviceTypeText !== "All Services") {
30117                that.serviceTypeFilter = serviceTypeText;
30118            }
30119
30120            // if zip code input received, validate it and include it in the request, or show errors
30121            if(zipCode) {
30122                that.distanceFilter.makeUspsZipCodeRequest(zipCode, true, true);
30123            }
30124            else if(!zipCode && that.distanceFilter.getProximity() !== 10000) {
30125                that.distanceFilter.showErrors();
30126            }
30127            else {
30128                that.makeFilterRequest();
30129            }
30130
30131            if (conditionDiv.val() !== "") {
30132                that.conditionFilter = conditionDiv.val();
30133            }
30134            if (trialIdDiv.val() !== "") {
30135                that.trialIdFilter = trialIdDiv.val();
30136            }
30137
30138            var correctMargin = false;
30139            $("html, body").animate({ scrollTop: 0 }, function(){
30140                if(correctMargin === false){
30141                    that.setDynamicFooterMargin();
30142                }
30143                correctMargin = true;
30144            });
30145        });
30146        var clearFilters = function() {
30147            var selected = jQuery(this);
30148
30149            var specialtyUnfiltered = jQuery(".search-results-filters .specialty.unfiltered");
30150            var subSpecialtyUnfiltered = jQuery(".search-results-filters .sub-specialty.unfiltered");
30151            var clinicSpecialtyUnfiltered = jQuery(".search-results-filters .clinic-specialty.unfiltered");
30152            var primaryCareUnfiltered = jQuery(".search-results-filters .primaryCare.unfiltered");
30153            var docTypeUnfiltered = jQuery(".search-results-filters .docType.unfiltered");
30154            var docTypeFiltered = jQuery(".search-results-filters .docType.filtered");
30155            var alphabetUnfiltered = jQuery(".search-results-filters .alphabet.unfiltered");
30156            var genderSelectTitle = jQuery(".search-results-filters .gender.unfiltered .select-title");
30157            var languageSelectTitle = jQuery(".search-results-filters .language.unfiltered .select-title");
30158            var serviceTypeSelectTitle = jQuery(".search-results-filters .service-type.unfiltered .select-title");
30159            var yearSelectTitle = jQuery(".search-results-filters .year.unfiltered .select-title");
30160            var visibleCount = 0;
30161
30162            var searchResultsFilters = jQuery('.search-results-filters'),
30163                medicalCategories = searchResultsFilters.find('.medical-categories'),
30164                medicalCategoryTitle = medicalCategories.find('.select-title');
30165
30166
30167
30168            if(selected.parents(".select-group").hasClass("specialty")){
30169                //disable autofill of doctor specialty in dr directory until next new search term
30170                if ("organic_phys" === GLOBAL_DIRECTORY_OBJECT) {
30171                    SHC.ui.Search.disableDrSpecAutofill = true;
30172                }
30173                that.specialtyFilter = null;
30174                specialtyUnfiltered.find('.select-title').text('Specialty');
30175
30176                that.subSpecialtyFilter = null;
30177                subSpecialtyUnfiltered.find('.select-title').text('No Preference');
30178                jQuery('.search-results-filters .specialty select').show();
30179            } else if(selected.parents(".select-group").hasClass("sub-specialty")) {
30180                that.subSpecialtyFilter = null;
30181                subSpecialtyUnfiltered.find('.select-title').text('No Preference');
30182            } else if (selected.parents(".select-group").hasClass("clinic-specialty")) {
30183                that.clinicSpecialtyFilter = null;
30184                clinicSpecialtyUnfiltered.find('.select-title').text("No Preference");
30185            } else if(selected.parents(".select-group").hasClass("alphabet")){
30186                that.alphabetFilter = null;
30187                alphabetUnfiltered.find(".select-title").text('All Names A-Z');
30188            } else if(selected.parents(".select-group").hasClass("medical-categories")){
30189                SHC.util.removeFilter('sp_med_categories');
30190                that.medicalCategoryFilter = null;
30191                medicalCategoryTitle.text('No Preference');
30192            } else if(selected.parents(".select-group").hasClass("primaryCare") === true){
30193                that.primaryCareFilter = null;
30194                primaryCareUnfiltered.text('Primary Care Type');
30195
30196                that.doctorTypeFilter = null;
30197                $(docTypeUnfiltered).find('.select-title').text('No Preference');
30198
30199                that.doctorFilterState = false;                                         //This is to maintain select state on Doctor Type filter
30200            } else if(selected.parents(".select-group").hasClass("docType") === true){
30201                that.doctorTypeFilter = null;
30202                $(docTypeUnfiltered).find('.select-title').text('No Preference');
30203            } else if(selected.parents(".select-group").hasClass("gender")){
30204                that.genderFilter = null;
30205                genderSelectTitle.text('No Preference');
30206            } else if(selected.parents(".select-group").hasClass("language")){
30207                that.languageFilter = null;
30208                languageSelectTitle.text('English');
30209            } else if(selected.parents(".select-group").hasClass("service-type")) {
30210                that.serviceTypeFilter = null;
30211                serviceTypeSelectTitle.text("All Services");
30212            } else if(selected.parents(".select-group").hasClass("year")) {
30213                that.year = null;
30214                var yearTitleText = $('.' + currentFilterID).closest('.newsroom-landing') ? "ALL" : "Show All";
30215                yearSelectTitle.text(yearTitleText);
30216            } else if(selected.parents(".select-group").hasClass("category")) {
30217                that.category = null;
30218                yearSelectTitle.text("ALL");
30219            } else if(selected.parents(".select-group").hasClass("categorycb")) {
30220                that.categorycb = null;
30221            }
30222
30223
30224            if(SHC.ui.screenMode !== 'small') {
30225                that.makeFilterRequest();
30226            } else{
30227                that.makeFilterRequest({mobileFilter: true});
30228
30229                // reset mobile select dropdown with magic
30230                jQuery('.search-results-filters #doctors-specialties-filter-target .select-group').removeClass('visible');
30231                jQuery('.search-results-filters .alphabet').removeClass('visible');
30232                jQuery('.sub-specialty select option:first-child').prop('selected','true');
30233                jQuery('.specialty select option:first-child').prop('selected','true');
30234            }
30235        };
30236        that.handlebarsTarget.on('click', '.clear-filterX', clearFilters);
30237        $('.newsroom-landing').on('click', '.collection.directory .clear-filterX ', clearFilters);
30238        
30239        that.handlebarsTarget.on('keyup', '.trials-input-container input' ,function(){
30240            var clearX = $(this).parent().find('.trials-clear-filterX .trials-x-icon');
30241            if(this.value === '' && !clearX.hasClass('hidden')){
30242                clearX.addClass('hidden');
30243            }else{
30244                clearX.removeClass('hidden');
30245            }
30246        });
30247
30248        //when clicking on the X to clear, trigger an S&P request with the new results now that the filter is removed
30249        that.handlebarsTarget.on('click', '.trials-filter-rail .trials-clear-filterX .trials-x-icon', function(){
30250            $(this).closest('.trials-input-container').find('input').val("");
30251            var filterFields = $('input.select-auto-complete.ui-autocomplete-input');
30252            SHC.clinicalTrialsFilter.clearXclick = false;
30253            if( SHC.util.clinicalTrialsConditionsAndIdAreEmpty() ){
30254                SHC.clinicalTrialsFilter.clearXclick = true;
30255            }
30256            SHC.clinicalTrialsFilter.filter.prepareAutoCompleteFilterRequest(filterFields);
30257        });
30258
30259        //handle sticky filter scroll
30260        var adjustStickyFilter = function () {
30261            var searchFilter =  jQuery('.search-results-filters');
30262            if(searchFilter.length && SHC.ui.screenMode !== 'small') {
30263                var filterHeight = searchFilter.height();
30264                var windowHeight = that.window.innerHeight();
30265                var defaultStickyFilterTop = 75;
30266                var adjustedStickyFilterTop = Math.min(windowHeight - (filterHeight + 10), defaultStickyFilterTop);
30267                searchFilter.css('top', adjustedStickyFilterTop);
30268            }
30269        }
30270
30271        var observer = new MutationObserver(function(mutations) {
30272            mutations.forEach(function(mutation) {
30273                for (var i = 0; i < mutation.addedNodes.length; i++) {
30274                    if(mutation.addedNodes[i].classList &&
30275                        mutation.addedNodes[i].classList.contains('container') &&
30276                        mutation.addedNodes[i].classList.contains('directory')) {
30277                        adjustStickyFilter();
30278                    }
30279                }
30280            })
30281        });
30282
30283        if (that.handlebarsTarget && that.handlebarsTarget.length) {
30284            observer.observe(that.handlebarsTarget[0], { childList: true });
30285        }
30286
30287        $(window).on('resizeEnd', function () {
30288            // if user resized browser
30289            if(SHC.ui.screenMode !== 'small') {
30290                adjustStickyFilter();
30291            }
30292        });
30293        $(window).on('orientationchange', function () {
30294            if (SHC.ui.screenMode !== 'small') {
30295                adjustStickyFilter();
30296            }
30297        });
30298        that.handlebarsTarget.on('click', '#alphabet-filter-target .select-arrow', function () {
30299            if (SHC.ui.screenMode !== 'small') {
30300                //make the select options static so it adjusts the parent container height
30301                $('#alphabet-filter-target .select-group.alphabet .select-options').css('position', 'static');
30302                // wait for the other handler to finish
30303                setTimeout(adjustStickyFilter, 100);
30304            }
30305        });
30306    },
30307
30308    getTrialsFilterVal: function($element) {
30309        var filterVal = null;
30310        if($element.hasClass('trials-recruiting')) {
30311            filterVal = $element.find('input:checked').val();
30312            var url = window.location.href;
30313            if(url.indexOf("sp_trialLocks") >= 0) {
30314                if(url.indexOf("#") !== -1) {
30315                    url = url.substring(0, url.indexOf("#"));
30316                }
30317                url = url.substring(url.indexOf("sp_trialLocks"), url.lastIndexOf("%7C"));
30318                url = url.substring(url.lastIndexOf("&") + 1);
30319                filterVal = url === filterVal ? "RECRUITING" : "passthrough";
30320            }
30321        } else {
30322            filterVal = $element.find('input').val();
30323        }
30324        return filterVal;
30325    },
30326
30327    /* After filter binding to set visibility of filter elements */
30328    bindToSpecialtiesLoadedEvent: function() {
30329        var that = this;
30330
30331        $(window).on('filtersLoaded', function() {
30332
30333            /*  The titlesArray declared below is used as a check to see what the current state of a filter is.
30334            *   The items in the array represent the default text of the filters that exist and could possibly be on a particular page.
30335            *   If the displayed title Text is found in this array then no filter options have been selected for that filter.
30336            *   **********  IF ADDING A NEW DROP DOWN FILTER THE DEFAULT TEXT MUST BE ADDED TO THIS ARRAY. **********
30337            */
30338            var titlesArray = ["Specialty", "No Preference", "All Names A-Z", "All Clinics A-Z", "All Topics A-Z", "English", "Primary Care Type", "All Services", "Any Distance","RECRUITING","Show All","ALL", ""];
30339            that.filtersPopd = false;
30340
30341            jQuery('.search-results-filters').each(function(){
30342                var filterDivs = jQuery(this).find('.select-group');    //returns all DIV elements under the select group parent DIV where all Filters reside.
30343                var divCount = filterDivs.length;                       //returns count of any filterDivs on a page to determine if script needs to be run and to set the number of iterations.
30344
30345                var selectBoxDiv = null;
30346                var selectBoxUL = null;
30347                var selectedFilterDiv = null;
30348                var filterType = null;
30349                var currentTitleText = null;
30350                var nextDiv = null;
30351                var subFilterDiv = null;
30352                var visibleCount = 0;
30353                var li_text = null;
30354                var liReturns = null;
30355
30356                var selectedToggle = $('#directory-filter-toggles .filter-toggle a.active').parent().attr('id');
30357
30358                /*  If filterDivs exist then script must be run.
30359                *   DROPDOWN Filters:
30360                *       For all dropdown filters (except distance) there are two states available:
30361                *           "unfiltered" which contains the ul/li options
30362                *           "filtered" which simply displays the selected element in the custom styled box.
30363                *       By default the script will iterate over every other (i += 2) filterDiv in order to check the
30364                *       "unfiltered" options first and check if selection has been made that will require more actions.
30365                *
30366                *   CHECKBOX Filters
30367                *       Multi-select checkbox filters do not have two states available.
30368                *       After a multi-select checkbox is checked the count will iterate only by one since there is not "filtered" state to step over.
30369                */
30370                if (divCount > 0){
30371                    for (i = 0; i < divCount;) {
30372                        selectBoxDiv = jQuery(filterDivs[i]);                           // Primary index [i] is the unfiltered selection box.
30373                        selectBoxUL = selectBoxDiv.find('ul');                          // UL of primary unfiltered selection box. Used for determining no-preference styling
30374                        selectedFilterDiv = $(filterDivs[i+1]);                         // [i+1] is to reference the filtered selection DIV which will always be directly after its related select box.
30375                        filterType = selectBoxDiv.attr("class").split(' ')[1];          // returns the second class in the class list which indicates which filter being currently evaluated.
30376                        if (SHC.ui.Search.DirectoryUtil.isTrialsDirectoryPage()) {
30377                            currentTitleText = that.getTrialsFilterVal(selectBoxDiv);
30378                        } else {
30379                            currentTitleText = that.removeCount(selectBoxDiv.f
30379ind('.select-title').text());
30380                        }
30381                        nextDiv = null;
30382
30383                        /*  This first section handles Multi-select checkboxes.
30384                        *   Multi-select boxes do not increment i by 2 because there is no "filtered" control to step over.
30385                        *   After the external bindCheckBoxFilters method is completed the loop index [i] is set to i + 1 and the next filter in the filterDivs list is assigned to nextDiv variable
30386                        *       This is to determine what type of filter, if any, is next in the filter objects to check.
30387                        *       If next filter is another Multi-select CB then nextDiv value is left as the assigned object and the loop cycles back to the beginning and the process continues.
30388                        */
30389                        if (selectBoxDiv.hasClass('multiSelectCB')) {
30390                            that.bindCheckboxFilters(selectBoxDiv);     // function call to handle select box filters  due to need for nested loops.
30391                            nextDiv = jQuery(filterDivs[i+1]);          // nextDiv var is used to check what type of filter occurs next on the page.
30392                            i += 1;
30393                            /*  If nextDiv filter is NOT another Multi-Select CB, set the filter to be checked to that filter. nextDiv value is set to null to allow entry to rest of script.
30394                            *       If nextDiv filter is Multi-Select CB then i has already been incremented above and script will skip the next section and return to the beginning of the loop. */
30395                            if (!(nextDiv.hasClass('multiSelectCB')) && nextDiv.length !== 0) {
30396                                selectBoxDiv = jQuery(filterDivs[i]);
30397                                selectBoxUL = selectBoxDiv.find('ul');
30398                                selectedFilterDiv = $(filterDivs[i+1]);
30399                                filterType = selectBoxDiv.attr("class").split(' ')[1];
30400                                currentTitleText = that.removeCount(selectBoxDiv.find('.select-title').text());
30401                                nextDiv = null;
30402                            }
30403                        }
30404                        if (nextDiv === null) {
30405                            // Check li length to see if any filter options were populated for filters and disable if not.
30406                            if ((selectBoxUL.find('li').length === 0) || (filterType === 'alphabet' && selectBoxUL.find('li').length === 1)) {
30407                                 selectBoxDiv.find('.select-title, .select-arrow').addClass('no-pref');
30408                                if(SHC.ui.screenMode === 'small') {
30409                                    var mobileSelect = selectBoxDiv.find('.select-options-mobile');
30410                                    mobileSelect.addClass('no-pref');
30411                                    mobileSelect.attr("disabled", true);
30412                                }
30413                            }
30414                            /******* THIS IS THE SECTION OF SCRIPT THAT SETS THE VISIBILITY AND POPULATES THE TEXT OF THE "FILTERED" STATE OF THE DROP DOWN FILTERS. *******/
30415
30416                            /*  Use titlesArray from above to check current selected text in drop down filter.
30417                            *   IF the filter's title text is in the titlesArray then no filter has been selected for this option
30418                            *   ELSE Selection has been made and filter visibility must be handled, filtered text set and check for populated sub-filters to disable if necessary. */
30419                            if (titlesArray.indexOf(currentTitleText) >= 0) {
30420                                selectBoxDiv.addClass('vis-on pop-show');
30421                                selectedFilterDiv.removeClass('vis-on pop-show');
30422                                selectedFilterDiv.find('.selected-filter').text('');
30423
30424                                if (filterType === "specialty" || filterType === "primaryCare"){    // Checks for primary/secondary filter type. For future "bound" controls, similar to specialty/sub-specialty, add title of primary filter here.
30425                                    subFilterDiv = jQuery(filterDivs[i+2]);                         // Sets Sub-filter unfiltered DIV.
30426                                    subFilterDiv.removeClass('vis-on pop-show');
30427                                    i += 2;                                                         // Increment index by 2 to account for hidden sub-filter which have been handled along with the primary filter since no primary filter is selected.
30428                                                                                                    // Single depth filter
30429                                }
30430                            } else {
30431                                that.filtersPopd = true;                                            // filtersPopd var set to true enable visible state of "Reset Filter" after filter check loop completes.
30432                                var currentMapFilter = that.getFilterObjectName(selectBoxDiv);      // Function call to return name of the filter variable used in makeFilterRequest
30432() function. This is to ensure that the filter var persists after page is left and returned to.
30433
30434                                selectBoxDiv.removeClass('vis-on pop-show');                                                    // Remove visibility on the SelectBoxDiv (The unfiltered state of the dropdown which contains the ul element)
30435                                selectedFilterDiv.addClass('vis-on pop-show');                                                  // Add visibility on selectedFilterDiv (The filtered state of the drop down filter.)
30436                                selectedFilterDiv.find('.selected-filter').text(that.removeCount(selectBoxDiv.find('.select-title').text()));     // Populate Filtered text with selected option from ul.
30437                                if (!that[currentMapFilter]) {
30438                                    if (SHC.ui.Search.DirectoryUtil.isTrialsDirectoryPage()) {
30439                                        that[currentMapFilter] = that.getTrialsFilterVal(selectBoxDiv);
30440                                    } else {
30441                                        that[currentMapFilter] = that.removeCount(selectBoxDiv.find('.select-title').text());
30442                                    }
30443                                }
30444
30445                                /* Check for typical "bound" filters. Simply makes sub-filter visible */
30446                                if (filterType === "specialty"){                                // Checks for primary filter control. For future "bound" controls, similar to specialty/sub-specialty, add title of primary filter here.
30447                                  subFilterDiv = jQuery(filterDivs[i+2]);                       // Sets Sub-Filter unfiltered DIV.
30448
30449                                  subFilterDiv.addClass('vis-on pop-show');
30450                                }
30451
30452                                /* Check for complex "bound" filters. Checks for number of sub-filter select items and either makes sub-filter select options (unfiltered state) visible or populates  */
30453                                if (filterType === "primaryCare"){                              // Checks for filter type based on target name. for instance primaryCare" filter control. For new filters of this sort ADD new check.
30454                                    subFilterDiv = jQuery(filterDivs[i+2]);                     // Sets sub-filter unfiltered DIV.
30455                                    subFilterFilteredDiv = jQuery(filterDivs[i+3]);             // Sets sub-filter filtered DIV.
30456
30457                                    liReturns = that.returnActiveSubfilterLiCount({subFilter: subFilterDiv});   // Function call to calculate number of li items in the sub-filter now that primary filter selection has narrowed results.
30458                                    visibleCount = liReturns[0];
30459                                    li_text = liReturns[1];
30460
30461                                    /* Set sub-filter visible state. Set sub-filter's unfiltered selected value to that of the only populated option when only one li is populated by data set. */
30462                                    if (visibleCount === 1 && that.doctorFilterState === false){
30463                                    subFilterFilteredDiv.addClass('vis-on pop-show');
30464                                    subFilterDiv.find('.select-title').text(li_text);
30465                                    that.doctorFilterState = true;                                      //This is to maintain select state on sub-filter
30466                                    that.doctorTypeFilter = that.removeCount(li_text);
30467                                    } else if (visibleCount === 1 && that.doctorFilterState === true){
30468                                        subFilterFilteredDiv.removeClass('vis-on pop-show');
30469                                        subFilterDiv.addClass('vis-on pop-show');
30470                                    } else {
30471                                        subFilterFilteredDiv.removeClass('vis-on pop-show');
30472                                        subFilterDiv.addClass('vis-on pop-show');
30473                                        that.doctorFilterState = false;                                 //This is to maintain select state on sub-filter
30474                                    }
30475
30476                                    // Adds additional footer margin-top to keep the filter menu from overlapping the footer.
30477                                    var currentMargin = parseInt($('.footer-margin').css('margin-top'));
30478                                    var additionalMargin = 79;  // 79 is the difference in margin needed for when sub-filters appear
30479                                    if($('.footer-margin').length && currentMargin > 40){
30480                                        $('.footer-margin').css('margin-top', (currentMargin + additionalMargin).toString() + 'px');
30481                                    }
30482                                }
30483                            }
30484                            /*  Increment i for next step in the loop. "singleDepthFilter" class must be added to none drop down box style filters that have no visible filtered state.
30485                            *       Multi-select CB's and Distance filter dropdown currently have this class.
30486                            *   For singleDepthFilter increment by only 1 to avoid skipping over next filter. */
30487                            if (!selectBoxDiv.hasClass('singleDepthFilter')) {
30488                                i += 2;
30489                            } else{
30490                                i += 1;
30491                            }
30492                        }
30493                    }
30494                }
30495            });
30496
30497            /* Turn on filter reset div visibility after option is selected. */
30498            var resetFilter = jQuery(".reset-filter");
30499            var applyFilter = jQuery(".apply-filter");
30500            var alphabetFilterSpacing = jQuery('#alphabet-filter-target .select-group.alphabet.vis-on.pop-show');
30501            if (that.filtersPopd === true) {
30502                if(resetFilter.hasClass("vis-on") === false){
30503                    resetFilter.addClass("vis-on");
30504                }
30505                if(applyFilter.hasClass("vis-on") === false){
30506                    applyFilter.addClass("vis-on");
30507                }
30508                if(alphabetFilterSpacing.hasClass("mobile-bottom-sp
30508acing")){
30509                    alphabetFilterSpacing.removeClass("mobile-bottom-spacing");
30510                }
30511            } else{
30512                if (resetFilter.hasClass("vis-on") && SHC.ui.Search.DirectoryUtil.isTrialsDirectoryPage() === false){
30513                    that.makeFilterRequest();
30514                }
30515                resetFilter.removeClass("vis-on");
30516                applyFilter.removeClass("vis-on");
30517
30518                if(SHC.ui.Search.DirectoryUtil.isTrialsDirectoryPage() === true && SHC.ui.screenMode === 'small'){
30519                    resetFilter.addClass("vis-on");
30520                    applyFilter.addClass("vis-on");
30521                }
30522
30523                alphabetFilterSpacing.addClass("mobile-bottom-spacing");
30524            }
30525            var conditionParent = $('.search-results-filters .trials-input-container.condition');
30526            if(conditionParent.find('input').val() !== ""){
30527                conditionParent.find('.trials-x-icon').removeClass('hidden');
30528            }
30529
30530            var idParent = $('.search-results-filters .trials-input-container.id');
30531            if(idParent.find('input').val() !== ""){
30532                idParent.find('.trials-x-icon').removeClass('hidden');
30533            }
30534        });
30535    },
30536
30537    /* Returns filter-name used in "makeFilterRequest()" based on Filter DIV being inspected. */
30538    getFilterObjectName: function (filterDiv) {
30539        if (filterDiv.hasClass('specialty')) {
30540            return 'specialtyFilter';
30541        } else if (filterDiv.hasClass('sub-specialty')) {
30542            return 'subSpecialtyFilter';
30543        } else if (filterDiv.hasClass('clinic-specialty')) {
30544            return 'clinicSpecialtyFilter';
30545        } else if (filterDiv.hasClass('alphabet')) {
30546            return 'alphabetFilter';
30547        } else if (filterDiv.hasClass('medical-categories')) {
30548            return 'medicalCategoryFilter';
30549        } else if (filterDiv.hasClass('gender')) {
30550            return 'genderFilter';
30551        } else if (filterDiv.hasClass('language')) {
30552            return 'languageFilter';
30553        } else if (filterDiv.hasClass('service-type')) {
30554            return 'serviceTypeFilter';
30555        } else if (filterDiv.hasClass('primaryCare')) {
30556            return 'primaryCareFilter';
30557        } else if (filterDiv.hasClass('docType')) {
30558            return 'doctorTypeFilter';
30559        } else if (filterDiv.hasClass('clinic-features')) {
30560            return 'clinicFeaturesFilter';
30561        }else if (filterDiv.hasClass('clinic-care-for')) {
30562            return 'clinicCareForFilter';
30563        }else if (filterDiv.hasClass('special-interests')) {
30564            return 'specialInterestsFilter';
30565        }else if (filterDiv.hasClass('trials-condition')) {
30566            return 'conditionFilter';
30567        }else if (filterDiv.hasClass('trials-ids')) {
30568            return 'trialIdFilter';
30569        }else if (filterDiv.hasClass('categorycb')) {
30570            return 'categorycb';
30571        }
30572        else {
30573            return false;
30574        }
30575    },
30576
30577    /* Returns count of available sub-filter options based on filter DIV being inspected. Returns li text that is used in cases where available count === 1 */
30578    returnActiveSubfilterLiCount: function(params) {
30579        var subFilter = null;
30580        var x = 0;
30581
30582        if (params) {
30583            subFilter = params.subFilter || null;
30584        }
30585        var li_Count = jQuery(subFilter).find('li').length;
30586        var visibleCount = 0;
30587        var li_text = null;
30588
30589        for (x = 0; x < li_Count; x += 1){
30590            var li_Item = jQuery(subFilter).find('li')[x],
30591                li_ItemString = jQuery(li_Item).attr('style').toString().replace(/\s+/g, ''); // need to remove spaces for IE
30592            if (li_ItemString.indexOf('display:list-item') > -1){
30593                visibleCount++;
30594                li_text = jQuery(li_Item).text();
30595            }
30596        }
30597        return [visibleCount, li_text];
30598    },
30599
30600    /* Bind function for checkBox filters. Called from bindToSpecialtiesLoadedEvent */
30601    bindCheckboxFilters: function(checkBoxFilterDiv) {
30602        var that = this;
30603        var currentCheckBox = checkBoxFilterDiv;
30604        var currentClassFilter = null;
30605        var currentDivClass = null;
30606        var x;
30607
30608        var currentMultiFilter = that.getFilterObjectName(checkBoxFilterDiv);       // Function call to return name of the filter variable used in makeFilterRequest
30608() function. This is to ensure that the filter var persists after page is left and returned to.
30609
30610        /* Checks the checkBoxFilterDiv parameter passed from bindToSpecialtiesLoadedEvent() to set the working DIV class that will be handled in this function. */
30611        if (checkBoxFilterDiv.hasClass('clinic-features')) {
30612            currentDivClass = 'clinic-features';
30613        } else if (checkBoxFilterDiv.hasClass('clinic-care-for')) {
30614            currentDivClass = 'clinic-care-for';
30615        } else if (checkBoxFilterDiv.hasClass('special-interests')) {
30616            currentDivClass = 'special-interests';
30617        } else if (checkBoxFilterDiv.hasClass('categorycb')) {
30618            currentDivClass = 'categorycb';
30619        } else {
30620            currentMultiFilter = null;
30621        }
30622
30623        /* If currentMultiFilter function has value then proceed with CB filter checks. */
30624        if (currentMultiFilter) {
30625           /*   IF filter map object exists to use in makeFilterRequest() Iterates through checkboxes and marks as selected the necessary options.
30626           *    ELSE iterates through filter values from the URL HASH to extract list of selected filter options and compares them to the checkbox values to determine which were selected.
30627           *        Creates filter map object to maintain selected checkboxes on return to page and marks as selected the necessary options.
30628           *    */
30629            if (that[currentMultiFilter]) {
30630                currentCheckBox.find('.cb-option').each(function(){
30631                    var input = $(this);
30632                    var filterText = that.removeCount(input.find('span').text().toLowerCase());
30633                    if ($(this).parents('.select-group.categorycb').length > 0){
30634                        filterText = input.find('.cb-input label').attr('data-attr-categorycb')
30635                    }
30636                    /* IF currentMultiFilter is an object then multiple items have been checked and returned in an array. ELSE currentMultiFilter is a string of a single item.*/
30637                    if(typeof that[currentMultiFilter] === 'object') {
30638                        for(var x = 0; x < that[currentMultiFilter].length; x++){
30639                            if (that.removeCount(that[currentMultiFilter][x].toLowerCase()).indexOf(filterText.toLowerCase()) > -1){
30640                                input.find('.cb-input label').addClass('cb-checked');
30641                                that.filtersPopd = true;
30642                            }
30643                        }
30644                    } else {
30645                        if (that.removeCount(that[currentMultiFilter].toLowerCase()).indexOf(filterText.toLowerCase()) > -1) {
30646                            input.find('.cb-input label').addClass('cb-checked');
30647                            that.filtersPopd = true;
30648                        }
30649                    }
30650                });
30651            } else {
30652                var undef;
30653                var paramArray = [];
30654                that[currentMultiFilter] = [];
30655                paramArray = window.location.href.slice(window.location.href.indexOf('#') + 1).toLowerCase().split(/([&]\w\d\=)|([&]\w\w)/);
30656
30657                for (var i=0; i < paramArray.length; i++) {
30658
30659                    if ( paramArray[i] === undef || paramArray[i] === "") {
30660                        paramArray.splice(i,1);
30661                        i--;
30662                    } else if (paramArray[i].indexOf('%7c') > -1) {
30663                        paramArray = paramArray.concat(paramArray[i].split('%7c'));
30664                        paramArray.splice(i,1);
30665                    }
30666                }
30667
30668                var filterText = '';
30669                var orFilterText = '';
30670                currentCheckBox.find('.cb-option').each(function(){
30671                    var input = $(this);
30672                    filterText = encodeURIComponent(that.removeCount(input.find('span').text())).toLowerCase();
30673                    if ($(this).parents('.select-group.categorycb').length > 0){
30674                        filterText = input.find('.cb-input label').attr('data-attr-categorycb');
30675                    }
30676                    if (paramArray.indexOf(filterText) > -1){
30677                        input.find('.cb-input label').addClass('cb-checked');
30678                        that.filtersPopd = true;
30679
30680                        /* If checkbox type is special-interests then multi-select 
30680CB must search as an OR by building string with | delimiter. For all other CB filters search as AND build array. */
30681                        if (currentDivClass !== 'special-interests' && currentDivClass !== '.categorycb') {
30682                            if ($(this).parents('.select-group.categorycb').length > 0){
30683                                that[currentMultiFilter].push(filterText);
30684                            } else {
30685                                that[currentMultiFilter].push(that.removeCount(input.find('span').text()));
30686                            }
30687                        } else {
30688                            orFilterText = that.removeCount(input.find('span').text()) + '|' + orFilterText;
30689                        }
30690                    }
30691                });
30692
30693                /* strip last | element from OR type CB's. (special-interests) */
30694                if (orFilterText !== '') {
30695                    that[currentMultiFilter][0] = orFilterText.substring(0, orFilterText.length - 1);
30696                }
30697
30698                /* for AND type checkbox filters, workaround in place for single selected filter options. capture selected value and add as second array element in order to return correct results. */
30699                if ((that[currentMultiFilter])){
30700                    var len = that[currentMultiFilter].length;
30701                    if (len === 1 && currentDivClass !== 'special-interests' && currentDivClass !== 'categorycb') {
30702                        var singleVal = that[currentMultiFilter][0];
30703                        // TODO: pending resolution of RSW-6437 the following two lines are removed. After resolution remove comments and the following workaround code "that[classFilterName][1] = singleVal; "
30704                        //that[currentMultiFilter] = null;
30705                        //that[currentMultiFilter] = singleVal;
30706                        that[currentMultiFilter][1] = singleVal;
30707                    }
30708                    else if (len === 0) {
30709                        that[currentMultiFilter] = null;
30710                    }
30711                }
30712            }
30713        }
30714    },
30715
30716    bindAutoCompleteSelectBoxes: function() {
30717        var that = this;
30718        $(window).on('filtersLoaded', function() {
30719            $('select.select-auto-complete').selectToAutocomplete({}, that);
30720            jQuery.ui.autocomplete.prototype._resizeMenu = function () {
30721                var ul = this.menu.element;
30722                ul.outerWidth(this.element.outerWidth());
30723            }
30724            $('input.select-auto-complete').on('focus', function() {$(this).keydown();});
30725            that.setTrialsInputTextColor();
30726        });
30727        return;
30728    },
30729
30730    setTrialsInputTextColor: function() {
30731        var trialsCondTarget = $('#trials-condition-filter-target'),
30732            trialsCondInput = $('#trials-condition-filter-target .select-auto-complete'),
30733            trialsIdTarget = $('#trials-id-filter-target'),
30734            trialsIdInput = $('#trials-id-filter-target .select-auto-complete'),
30735            filterColorClass = 'filter-text-color';
30736
30737        trialsCondTarget.on('focus', 'input', function() {
30738            trialsCondTarget.find('input').on('keydown', function() {
30739                trialsCondInput.addClass(filterColorClass);
30740            });
30741        });
30742        trialsCondTarget.on('focusout', 'input', function() {
30743            trialsCondInput.removeClass(filterColorClass);
30744        });
30745        trialsIdTarget.on('focus', 'input', function() {
30746            trialsIdTarget.find('input').on('keydown', function() {
30747                trialsIdInput.addClass(filterColorClass);
30748            });
30749        });
30750        trialsIdTarget.on('focusout', 'input', function() {
30751            trialsIdInput.removeClass(filterColorClass);
30752        });
30753    },
30754
30755
30756    /**
30757     * This method returns the HTML markup to be inserted into the appropriate div
30758     */
30759    getDropdownMarkup: function() {
30760        return;
30761    },
30762
30763    /**
30764     * This method activates this dropdown by resuming functionality (if necessary)
30765     *
30766     * TODO make sure that the activate() and getDropdownMarkup() are doing what they are supposed to be doing
30767     *      // I think appending this here seems like a bad Idea, we aren't using getDropdownMarkup() well
30768     */
30769    activate: function(doer, data) {
30770        var that = this;
30771        this.doer = doer;
30772        // process and interpret json data (from tabbar)
30773
30774        //no dropdowns if there is no data
30775        if (data === null || jQuery.isEmptyObject(data.facets))
30776        {
30777            return;
30778        }
30779    },
30780
30781    /**
30782     * This method activates this dropdown by pausing functionality (if necessary)
30783     */
30784    deactivate: function() {
30785    },
30786    /**
30787     * Initializes distance filter and registers make filter request when the filter is ready.
30788     */
30789    initDistanceFilter: function() {
30790        var that = this;
30791        $(window).on("filtersLoaded", function() {
30792            if(that.distanceFilter === null) {
30793                that.distanceFilter = new SHC.ui.Search.DistanceFilter();
30794                $(window).on("distanceFilterRequest", function() {
30795                    that.makeFilterRequest();
30796                });
30797                $(window).on("distanceFilterRequestMobile", function() {
30798                    that.makeFilterRequest({mobileFilter: true});
30799                });
30800            }
30801            else {
30802                that.distanceFilter.rebindEvents();
30803            }
30804        });
30805    },
30806    setSpinnerOverMap: function(){
30807        var section = $('.activesection').text();
30808        var toggleSelected = $('#result-list-toggle-selected-active');
30809        if( $('.map-view-icon.active').length === 1 && (section === 'Doctors' || section === 'Clinics & Locations')
30810            && ( toggleSelected.text() !== 'map-view-icon') ){
30811
30812            //spinner css
30813            $('#spinner-home').css('height', $('.flexcontainer .search-results-list').height());
30814            $('#spinner-home').css('width' , $('.flexcontainer .search-results-list').width());
30815            $('#spinner-home').css('left', $('.flexcontainer .search-results-list').offset().left + 10);
30816            $('#spinner-home').addClass('has-map');
30817
30818            if(location.href.indexOf('%7C') > -1){
30819                $('#spinner-home').addClass('map-passthrough');
30820            }
30821
30822            if ($('#spinner-text.map-wait-text').length === 0){
30823                var waitText = 'Please wait...<br/>We are mapping your results.';
30824                $('<div id="spinner-text" class="map-wait-text">'+waitText+'</div>').insertAfter('#spinner-home #spinner-container');
30825            }
30826            toggleSelected.text('map-view-icon');
30827        }else{
30828            //check if the user is clicking on filters while the overlay is already loading results
30829            if( !($('#spinner-home').is(':visible')) ){
30830                $('#spinner-text.map-wait-text').hide();
30831                $('#spinner-home').css({'top':'', 'left':'0', 'width':'', 'height':'100%'});
30832                $('#spinner-home').removeClass('has-map');
30833            }
30834        }
30835    },
30836    setLastViewToggleClicked: function(){
30837        var selectedView = 'list-view-icon';
30838        if ($('.grid-list-toggle .active').length > 0){
30839            selectedView = $('.grid-list-toggle .active').attr('class').replace('active','').trim();
30840        }
30841        if($('#result-list-toggle-selected-active').length === 0){
30842            var saveSelectedView = '<div id="result-list-toggle-selected-active" style="display:none">'+selectedView+'</div>';
30843            $('body').append(saveSelectedView);
30844        }else{
30845            $('#result-list-toggle-selected-active').text(selectedView);
30846        }
30847    },
30848    setMobileFilterClickedOverlay: function(){
30849        //the overlay needs to go from the 'refine box' to the end of the footer
30850        //var overlayHeight =  - $('.refine-box').offset().top);
30851        $('.search-results #spinner-home').addClass('mobile-filter-active');
30852        $('.search-results #spinner-home.mobile-filter-active').css('height',parseInt($(document).height()));
30853    },
30854
30855    /* Gets the value of Search Menu height and subtracts the value of the distance between top of the results menu and the top of the footer.
30856    *  Then adds 45, the normal footer margin of 40px plus 5, to prevent the search menu from overflowing off the page on microsites.
30857    */
30858    setDynamicFooterMargin: function() {
30859        var minResultsHeight = 854;
30860        var micrositeResultsPage = GLOBAL_SEARCH_RESULTS_TEMPLATE === '/apps/shca/templates/searchresults';
30861        var filterMenuOpen = $('#search-filters').hasClass('visible');
30862        if(micrositeResultsPage) {
30863            var needExtraMargin = $('.search-results-filters').height() >= ($('.footer-margin').offset().top - $('.search-results-filters').offset().top);
30864            var footerMargin = Math.abs($('.search-results-filters').height() - ($('.footer-margin').offset().top - $('.search-results-filters').offset().top) + 45);
30865            if(SHC.ui.screenMode === 'small' && $('.directory').height() <= minResultsHeight && filterMenuOpen && needExtraMargin) {
30866                $('.footer-margin').css('margin-top', footerMargin.toString() + 'px');
30867            } else {
30868                $('.footer-margin').css('margin-top', '40px');
30869            }
30870        }
30871    },
30872    keepCurrentViewOnSpecPrimToggle: function() {
30873        $('#handlebars-target').on('click', '.filter-toggle-wrapper, .select-options li, .clear-filterX', function() {
30874            SHC.util.setCookie('activeView', SHC.ui.Search.DirectoryUtil.getSelectedView(), 1, '/');
30875        });
30876        $('#handlebars-target').on('click', '.select-options li', function() {
30877            SHC.util.setCookie('activeView', SHC.ui.Search.DirectoryUtil.getSelectedView(), 1, '/');
30878        });
30879    },
30880    keepCurrentViewSearchResultsClicks: function() {
30881        if(SHC.ui.Search.DirectoryUtil.isClinicDirectoryPage() || SHC.ui.Search.DirectoryUtil.isDoctorDirectoryPage()) {
30882            $('#handlebars-target').on('click', '.search-results-list a, .search-results-list .profile-tile, .reset-filter a', function() {
30883                SHC.util.setCookie('activeView', SHC.ui.Search.DirectoryUtil.getSelectedView(), 1, '/');
30884            });
30885        }
30886    },
30887    initRadioBtnFilter: function() {
30888        var that = this;
30889        $(window).on('filtersLoaded', function() {
30890            that.recruitingFilter = $('.search-results-filters .trials-recruiting input:checked').val();
30891        });
30892    },
30893    bindRadioBtnFilter: function(filterElement) {
30894        var that = this;
30895        this.handlebarsTarget.on('click','.search-results-filters ' + filterElement + ' input', function() {
30896            that.recruitingFilter = $(this).val();
30897            that.makeTrialsFilterRequest($('.search-results-filters'));
30898        });
30899    },
30900    removeCount: function(filterString) {
30901        return filterString.replace(/ \(\d+\)$/g, "");
30902    }
30903});
30904
30905SHC.Namespace(SHC, "SHC.ui.Search.Dropdown.Predict");
30906SHC.ui.Search.Dropdown.Predict = new SHC.Class();
30907SHC.ui.Search.Dropdown.Predict.unitTestRun = false;
30908
30909SHC.ui.Search.Dropdown.Predict.include({
30910    init: function () {
30911        this.$searchInput = jQuery('#search-term');
30912        this.minChars = 3;
30913        this.resultLimit = 17;
30914        this.$shadowInput = $("#prediction").attr("disabled", "disabled");
30915        this.shadowTextArray = [];
30916        this.suggestionsTitle = "Suggested Searches";
30917        this.mobileResultLimit = 8;
30918        this.capitalizeEnabled = true;
30919        this.showAllResultsText = "See All Results";
30920        this.$dropdownPredictDiv = jQuery('#dropdown-predict');
30921        this.$pulldownDiv = jQuery('#search-pulldown');
30922
30923        this.searchResultsUrl = HOME_PAGE_PATH + "/search-results.html/";
30924        this.trialSearchResultsUrl = HOME_PAGE_PATH + "/search-results.trials.html/#";
30925        var searchVer = document.querySelector('meta[name="shc-search-version"]').content || "v1";
30926        console.log('searchVer (predictive) '+searchVer);
30927        this.predServletUrl = "/bin/api/"+searchVer+"/pred_search.json";
30928        // this.predServletUrl = "/bin/api/v1/pred_search.json"; // hardcode to v1 for now
30929        this.searchUrl = this.predServletUrl + "?do=pred&q=";
30930        this.trialConditionsUrl = "/bin/api/"+searchVer+"/search.json?do=organic_clinical_trials&x1=sp_status&q1=RECRUITING&payload=disabled";
30931        this.dropdownUtil = new SHC.ui.Search.DropdownUtil();
30932        this.$predictiveDiv = $("#dropdown-predict");
30933        this.selectorName = this.getSelectorName();
30934        this.isStanfordlab = SHC.util.isStanfordlab();
30935        this.isValleycare = SHC.util.isValleycare();
30936        this.bindUpdateSelector();
30937        this.exactMatchExclusions = ["other", "types"];
30938        this.additionalPredictiveDoctor = null;
30939        SHC.predictSearchStartedTime = 0;
30940        if (this.isValleycare) {
30941            this.searchResultsUrl = HOME_PAGE_PATH + "/tri-valley/search-results.html/";
30942            this.trialSearchResultsUrl = HOME_PAGE_PATH + "/tri-valley/search-results.trials.html/#";
30943        }
30944    },
30945    /**
30946     * Activates the predict dropdown by preping the event handlers, and binding search input
30947     *  to key up.
30948     */
30949    activate: function () {
30950        var that = this;
30951        var template = jQuery("#shc-search-title").attr("data-page-template");
30952        if( window.location.href.indexOf('search-results.newsroom.html') > 0 || (template && (template.indexOf("newsroomlanding")>-1 || template.indexOf("newsroomlisting")>-1))){
30953            that.searchUrl = that.predServletUrl + "?do=pred_newsroom&q=";
30954        }
30955        if(!that.trialConditions) {
30956            //trials conditions query
30957            $.ajax({
30958                url: that.trialConditionsUrl,
30959                type: 'GET',
30960                dataType: 'jsonp',
30961                success: function (results) {
30962                    that.trialConditions = results;
30963                },
30964                error: function () {
30965                    console.log("Error getting trial conditions");
30966                }
30967            });
30968        }
30969        this.setupEventHandlers();
30970    },
30971    /**
30972     * Deactivate the predict dropdown
30973     */
30974    deactivate: function () {
30975        this.removeEventHandlers();
30976        this.clearShadowInputText();
30977        this.$predictiveDiv.find(".link-item a").removeClass('active');
30978        this.previousTerm = "";
30979    },
30980    /**
30981     * This method returns the HTML markup to be inserted into the appropriate div
30982     */
30983    getDropdownMarkup: function () {
30984    },
30985    /**
30986     * Check if this page has one of the following Sling selectors.
30987     */
30988    getSelectorName: function() {
30989        var template = jQuery("#shc-search-title").attr("data-page-template");
30990        if (template && template.indexOf("clinicaltrials_search")>-1) {
30991            return "trials";
30992        }
30993
30994        if (template && (template.indexOf("newsroomlanding")>-1 || template.indexOf("newsroomlisting")>-1)) {
30995            return "newsroom";
30996        }
30997
30998        var selectors = ["doctors","clinics", "conditions", "treatments", "tests", "trials", "newsroom"];
30999        for (var i=0,n=selectors.length; i<n; i++) {
31000            if (SHC.util.hasSelectorAndSearchTerm(selectors[i], window.location.pathname)) {
31001                return selectors[i];
31002            }
31003        }
31004
31005        return "";
31006    },
31007
31008    /**
31009     * Does the queries to predictive and suggested based on what is in the search input
31010     */
31011    doSuggestedPredictedQueries: function (term) {
31012        var that = this;
31013        if (term.length < that.minChars) {
31014            that.emptyPulldown();
31015        }
31016        that.predictiveResults = [];
31017        that.searchTerm = term;
31018        var searchLaunched = parseInt(jQuery.now());
31019
31020        var predictionUrl = that.searchUrl + encodeURIComponent(term) + "*";
31021        if (that.isValleycare) {
31022            predictionUrl = predictionUrl.replace('do=pred', 'do=pred_vc');
31023        }
31024        if (that.isStanfordlab){
31025            predictionUrl = that.predServletUrl + "?do=pred_slab_site_search&q=" + encodeURIComponent(term) + "*";
31026        }
31027
31028        $.when(
31029            // Predictions query
31030            $.ajax({
31031                url: predictionUrl,
31032                type: 'GET',
31033                dataType: 'jsonp',
31034                success: function (results) {
31035                    that.predictiveResults = results;
31036                },
31037                error: function () {
31038                    console.log("Error getting predictions");
31039                }
31040            })
31041
31042        ).done(function () {
31043            that.onDataReadyHandler([], term);
31044        });
31045    },
31046    /**
31047     * Process data using the search term entered by the user
31048     */
31049    onDataReadyHandler: function (suggestions, term) {
31050        var that = this;
31051        // reset the dropdown and shadowtext
31052        that.emptyPulldown();
31053        that.shadowTextArray = [];
31054
31055        //reset the position of up/down arrow and shadow text index
31056        that.currentlySelectedSuggestion = -1;
31057        that.shadowIndex = 0;
31058
31059        //convert trials to conditions if necessary ("Breast Cancer Trials")
31060        that.checkExactMatchConditionTrial(term);
31061        //get balanced json
31062        var balancedResults = that.getBalancedResults(suggestions);
31063        //get totals for each section ("View all 40 Doctors")
31064        var queryTotalMap = that.getQueryTotalMap(that.predictiveResults);
31065        //check if it's the only section
31066        var onlyCollection = that.getOnlyCollection(balancedResults);
31067        //changing json for handlebars
31068        var fullyGroomedJson = that.groomJsonForHandlebars(balancedResults, queryTotalMap, onlyCollection);
31069
31070        if(this.hideIfNoResults(balancedResults)){
31071            //load groomed json into handlebars template if there are results returned
31072            that.loadPredictiveHandlebars(fullyGroomedJson);
31073            //highlight the correct text in the dropdown
31074            that.refreshHighlighting();
31075            //building ShadowText Array
31076            that.buildingArrayForShadowText(balancedResults);
31077
31078            // make sure we have a search term before calling .length
31079            if(that.searchTerm) {
31080                var length = that.searchTerm.length;
31081                that.adjustShadowInput(length);
31082                //make sure shadowtext and dropdown get cleared if term is below threshold
31083                if (length < that.minChars) {
31084                    that.clearShadowInputText();
31085                    that.emptyPulldown();
31086                }
31087            } else {
31088                //clear everything if search bar is empty
31089                that.clearShadowInputText();
31090                that.emptyPulldown();
31091            }
31092            that.dropdownUtil.removePulldownScrollHandler();
31093            that.dropdownUtil.checkPulldownHeight();
31094        }
31095        var predictiveTerms = new SHC.ui.PredictiveTracking();
31096        predictiveTerms.initializePredictiveTermsEvents(term);
31097        predictiveTerms.initializePredictiveSuggestedLinkEvents(term);
31098
31099    },
31100
31101    /**
31102     * Checks for an exact condition match and if found, replaces
31103     * predictive trial results with "[condition-name] Trials" instead
31104     */
31105    checkExactMatchConditionTrial: function (term) {
31106        var that = this;
31107        var matches = [];
31108        if (this.isStanfordlab || this.isValleycare) {
31109            return;
31110        }
31111        if ($.inArray(term.toLowerCase(), that.exactMatchExclusions) === -1 && this.selectorName !== 'newsroom') {
31112            if (that.trialConditions && that.trialConditions.facets && that.trialConditions.facets.conditions) {
31113                that.trialConditions.facets.conditions.forEach(function (condition) {
31114                    if(SHC.util.isEqualWithEntitiesRemoved(condition.value.toLowerCase(), term.toLowerCase())) {
31115                        var newCondition = {};
31116                        newCondition.title = condition.value + " Trials";
31117                        newCondition.displayName = condition.value + " Trials";
31118                        newCondition.url = "q1=RECRUITING;q2=" + condition.value.replace(' ', '+') + ";x1=sp_status;x2=sp_conditions";
31119                        newCondition.url = that.trialSearchResultsUrl + SHC.util.convertSpSyntax(newCondition.url);
31120                        newCondition.url = SHC.util.adjustPath(newCondition.url, false);
31121                        newCondition.exactMatch = "exact-match";
31122                        matches.push(newCondition);
31123                    }
31124                });
31125            }
31126            if(matches.length > 0) {
31127                var trialsPrediction = $.grep(that.predictiveResults, function (element) {
31128                    return element.collection === "trials";
31129                }, false);
31130                trialsPrediction[0].data = matches;
31131            }
31132        }
31133    },
31134
31135    /**
31136     * Sorts and balances results
31137     */
31138    getBalancedResults: function (suggestions) {
31139        var that = this;
31140        //combine suggestions with predictive results
31141        that.predictiveResults.push({
31142            "collection": "suggestions",
31143            "heading": that.suggestionsTitle,
31144            "data": suggestions
31145        });
31146
31147        // prep data
31148        var mapOfLists = SHC.util.arrayToMapOfLists(that.predictiveResults, "collection", "data");
31149
31150        if (that.capitalizeEnabled) {
31151            mapOfLists["conditions"] = SHC.util.capitalizeObjectList(mapOfLists["conditions"], "displayName");
31152            mapOfLists["treatments"] = SHC.util.capitalizeObjectList(mapOfLists["treatments"], "displayName");
31153            mapOfLists["tests"] = SHC.util.capitalizeObjectList(mapOfLists["tests"], "displayName");
31154        }
31155
31156        // truncate Trials title based on screenMode.
31157        var limit = null; // do not modify for "small" since we wrap text.
31158        if (SHC.ui.screenMode === "large") {
31159            limit = 83;
31160        } else if (SHC.ui.screenMode === "medium") {
31161            limit = 54;
31162        }
31163        if (limit) {
31164            mapOfLists["trials"] = SHC.util.truncateField(mapOfLists["trials"],"title",limit);
31165        }
31166
31167        if(window.location.href.indexOf('search-results.doctors.html') > 0
31168            && typeof mapOfLists.physicians != 'undefined'
31169            && mapOfLists.physicians.length >= 3){
31170            //save doctor for later appending if doctor directory predictive dropdown is needed later
31171            that.additionalPredictiveDoctor =  mapOfLists.physicians[2];
31172        }
31173
31174        //adjust number of results
31175        var limit = that.resultLimit;
31176        if (SHC.ui.screenMode === "small") {
31177            limit = that.mobileResultLimit;
31178        }
31179
31180        // rebalance list
31181        var balancedResults;
31182        var template = jQuery("#shc-search-title").attr("data-page-template");
31183        if(window.location.href.indexOf('search-results.clinics.html') > 0 || 
31184           window.location.href.indexOf('search-results.newsroom.html') > 0 || 
31185           (template && (template.indexOf("newsroomlanding")>-1 || template.indexOf("newsroomlisting")>-1)) ||
31186           SHC.util.isStanfordlab()
31187           ){
31188            balancedResults = mapOfLists;
31189        } else {
31190            balancedResults = SHC.util.balancedTruncate(mapOfLists, limit);
31191        }
31192
31193        return balancedResults;
31194    },
31195
31196    /**
31197     * Check if there's only one section in balanced results
31198     * Used to remove the line between sections when there's only one
31199     */
31200    getOnlyCollection: function (balancedResults) {
31201        var balancedCollectionCount = SHC.util.countProperties(balancedResults),
31202            onlyCollection = (balancedCollectionCount === 1) ? true : false;
31203        return onlyCollection;
31204    },
31205
31206    /**
31207     * Creates array for the shadow text
31208     */
31209    buildingArrayForShadowText: function (balancedResults) {
31210        var that = this;
31211        var collections = ["physicians", "conditions", "treatments", "tests", "clinics", "trials", "suggestions"];
31212        var count = {};
31213
31214        for (var i = 0, n = collections.length; i < n; i++) {
31215            var cName = collections[i],
31216                list = balancedResults[cName];
31217            count[cName] = (list && list.length) ? list.length : 0;
31218            switch (cName) {
31219                case "physicians":
31220                    that.setShadowTextArray(list, 'normal');
31221                    break;
31222                case "conditions":
31223                    that.setShadowTextArray(list, 'normal');
31224                    break;
31225                case "treatments":
31226                    that.setShadowTextArray(list, 'normal');
31227                    break;
31228                case "tests":
31229                    that.setShadowTextArray(list, 'normal');
31230                    break;
31231                case "clinics":
31232                    that.setShadowTextArray(list, 'normal');
31233                    break;
31234                case "trials":
31235                    that.setShadowTextArray(list, 'normal');
31236                    break;
31237                case "suggestions":
31238                    that.setShadowTextArray(list, 'suggestions');
31239                    break;
31240                default:
31241            }
31242        }
31243        // Shadow text stuff
31244        var found = SHC.util.findFirstMatch(balancedResults["conditions"], "title", that.getRegExp());
31245        if (found > -1) {
31246            // shadow text does not complete on doctor names
31247            that.shadowIndex = count["physicians"] + found;
31248        }
31249    },
31250
31251    /**
31252     * Send JSON to handlebars template and output to dropdown
31253     */
31254    loadPredictiveHandlebars: function (fullyGroomedJson) {
31255        var that = this;
31256        var template = jQuery("#shc-search-title").attr("data-page-template");
31257        // var source = $('#dropdownPredictiveTemplate').html();
31258        // var predictiveTemplate = Handlebars.compile(source);
31259        var predictiveTemplate =  JST["handlebars/dropdownPredictiveTemplate.hbs"];
31260
31261        fullyGroomedJson.hasSelector = this.selectorName !== "";
31262        fullyGroomedJson.selectorName = this.selectorName;
31263
31264        if(this.isDoctorPredictiveDropdown(fullyGroomedJson)){
31265            predictiveTemplate =  JST["handlebars/dropdownPredictiveDoctorTemplate.hbs"];
31266            if( fullyGroomedJson.categories[0].count >= 3
31267                && fullyGroomedJson.categories[0].data.length === 2
31268                && this.additionalPredictiveDoctor !== null){
31269                fullyGroomedJson.categories[0].data.push(this.additionalPredictiveDoctor);
31270            }
31271        }
31272        if(window.location.href.indexOf('search-results.clinics.html') > 0){
31273            predictiveTemplate =  JST["handlebars/dropdownPredictiveClinicTemplate.hbs"];
31274        }
31275        if(window.location.href.indexOf('search-results.newsroom.html') > 0 || (template && (template.indexOf("newsroomlanding")>-1 || template.indexOf("newsroomlisting")>-1))){
31276            predictiveTemplate =  JST["handlebars/dropdownPredictiveNewsroomTemplate.hbs"];
31277            that.predictiveResults.searchTerm = {};
31278            that.predictiveResults.searchTerm = that.searchTerm;
31279            fullyGroomedJson = that.predictiveResults;
31280        }
31281        if (this.isStanfordlab) {
31282            predictiveTemplate = JST["handlebars/dropdownPredictiveStanfordlab.hbs"];
31283        }
31284
31285        that.$predictiveDiv.html(predictiveTemplate(fullyGroomedJson));
31286
31287        var suggestions = $('#search-suggestions .search-result-heading.suggested-searches-heading');
31288        var viewAllSuggestions = $('#search-pulldown>#dropdown-predict>a.view-all');
31289        if (suggestions.length === 1){
31290            viewAllSuggestions.addClass('with-suggestions');
31291        }
31292        else{
31293            viewAllSuggestions.removeClass('with-suggestions');
31294        }
31295        if (this.selectorName) {
31296            viewAllSuggestions.hide();
31297        }
31298    },
31299
31300    /**
31301     * Grooms JSON into the format expected by the handlebars template
31302     */
31303    groomJsonForHandlebars: function (balancedResults, queryTotalMap, onlyCollection) {
31304        var that = this;
31305        //Grooming JSON for Handlebars
31306        balancedResults.categories = [];
31307
31308        // We don't need all the extraneous processing below for StanfordLab.
31309        if (this.isStanfordlab) {
31310            balancedResults.searchTerm = that.searchTerm;
31311            balancedResults.onlyCollection = onlyCollection;
31312            // preferred order of categories
31313            var slab_collections = ['slab_test_details','slab_specialty','slab_news'];
31314            var pred = this.predictiveResults;
31315            for (var i=0,n=pred.length; i<n; i++) {
31316                var p = pred[i];
31317                if (p.data && p.data.length > 0 && slab_collections.indexOf(p.collection) > -1 ) {
31318                    var category = {
31319                        heading: p.heading,
31320                        data: p.data,
31321                        type: p.collection
31322                    };
31323                    if (p.collection==='slab_test_details') {
31324                        category.count = queryTotalMap[p.collection];
31325                    }
31326                    balancedResults.categories.push(category);
31327                }
31328            }
31329            balancedResults.categories.sort(function(a,b){
31330                if (slab_collections.indexOf(a.type) < slab_collections.indexOf(b.type)) {
31331                    return -1; 
31332                } else if (slab_collections.indexOf(a.type) > slab_collections.indexOf(b.type)) {
31333                    return 1;
31334                } else {
31335                    return 0;
31336                }
31337            });
31338            return balancedResults;    
31339        }
31340
31341        if (this.selectorName === "doctors" || !this.selectorName) {
31342            balancedResults.categories[0] = {
31343                "heading": "Doctors & Providers",
31344                "type": "doctors",
31345                "count": queryTotalMap["physicians"],
31346                "data": balancedResults["physicians"],
31347                "doctorTitles" : this.predictiveResults[0].facets['doctorTitles'],
31348                "doctorMedicalCategories" : this.predictiveResults[0].facets['medicalCategories']
31349            };
31350        } else {
31351            balancedResults.categories[0] = {"count": 0};
31352        }
31353
31354        if (this.selectorName === "conditions" || (!this.selectorName && !this.isValleycare)) {
31355            balancedResults.categories[1] = {
31356                "heading": "Conditions",
31357                "type": "conditions",
31358                "count": queryTotalMap["conditions"],
31359                "data": balancedResults["conditions"],
31360                "sp_type": "condition"
31361            };
31362            balancedResults.categories[2] = {
31363                "heading": "Treatments",
31364                "type": "treatments",
31365                "count": queryTotalMap["treatments"],
31366                "data": balancedResults["treatments"],
31367                "sp_type": "treatment"
31368            };
31369            balancedResults.categories[3] = {
31370                "heading": "Medical Tests",
31371                "type": "tests",
31372                "count": queryTotalMap["tests"],
31373                "data": balancedResults["tests"],
31374                "sp_type": "test"
31375            };
31376        } else {
31377            balancedResults.categories[1] = {"count": 0};
31378            balancedResults.categories[2] = {"count": 0};
31379            balancedResults.categories[3] = {"count": 0};
31380        }
31381
31382        if (this.selectorName === "clinics" || (!this.selectorName && !this.isValleycare)) {
31383            balancedResults.categories[4] = {
31384                "heading": "Stanford Clinics",
31385                "type": "clinics",
31386                "count": queryTotalMap["clinics"],
31387                "data": balancedResults["clinics"],
31388                "specialty" : this.predictiveResults[4].facets['doctorTitleGroups']
31389            };
31390        } else {
31391            balancedResults.categories[4] = {"count": 0};
31392        }
31393
31394        if (this.selectorName === "trials" || (!this.selectorName && !this.isValleycare)) {
31395            balancedResults.categories[5] = {
31396                "heading": "Clinical Trials",
31397                "type": "trials",
31398                "count": queryTotalMap["trials"],
31399                "data": balancedResults["trials"]
31400            };
31401        } else {
31402            balancedResults.categories[5] = {"count": 0};
31403        }
31404
31405        if (this.selectorName === "newsroom" || (!this.selectorName && !this.isValleycare)) {
31406            balancedResults.categories[6] = {
31407                "heading": "Newsroom",
31408                "type": "newsroom",
31409                "count": queryTotalMap["newsroom"],
31410                "data": balancedResults["newsroom"]
31411            };
31412        } else {
31413            balancedResults.categories[6] = {"count": 0};
31414        }
31415
31416        if (!this.selectorName) {
31417            balancedResults.categories[7] = {
31418                "heading": "Suggested Searches",
31419                "data": balancedResults["suggestions"]
31420            };
31421        } else {
31422            balancedResults.categories[7] = {"count": 0};
31423        }
31424
31425        balancedResults.searchTerm = that.searchTerm;
31426        balancedResults.onlyCollection = onlyCollection;
31427        return balancedResults;
31428    },
31429    /**
31430     * Uses the search term to highlight the correct text of the dropdown
31431     */
31432    refreshHighlighting: function () {
31433        var that = this;
31434        $('.link-item a').each(function () {
31435            var rawHtml = $(this).html();
31436            var searchTerm = SHC.util.escapeCharactersForRegEx(that.$searchInput.val());
31437            var highlightedHtml = SHC.util.highlight(rawHtml, $.trim(searchTerm));
31438            $(this).html(highlightedHtml);
31439        });
31440    },
31441    /**
31442     * Breaks the response of the predictive query into the cond/clin/doc collection chunks
31443     */
31444    getQueryTotalMap: function (list) {
31445        var queryTotalMap = {};
31446        if (!list) {
31447            return queryTotalMap;
31448        }
31449        try {
31450            for (var i = 0, n = list.length; i < n; i++) {
31451                var item = list[i];
31452                if (item.query && item.data && item.data.length > 0) {
31453                    var key = item.collection,
31454                        value = item.query[0].total;
31455                    if (key && value) {
31456                        queryTotalMap[key] = value;
31457                    }
31458                }
31459            }
31460        } catch (err) {
31461        }
31462        return queryTotalMap;
31463    },
31464    /**
31465     * Sets the shadow text that appears in the search bar
31466     */
31467    setShadowTextArray: function (list, type) {
31468        var that = this;
31469        var rawText = '';
31470        if (list && list.length) {
31471            for (var i = 0, n = list.length; i < n; i++) {
31472                if (type === 'normal') {
31473                    rawText = list[i]["displayName"];
31474                } else {
31475                    rawText = list[i];
31476                }
31477                that.shadowTextArray.push(rawText.toLowerCase());
31478            }
31479        }
31480    },
31481    /**
31482     * Sets a value in the shadowInput
31483     * @param text
31484     */
31485    setShadowInputText: function (text) {
31486        this.$shadowInput.val(text);
31487    },
31488    /**
31489     * Clears the shadowInput
31490     */
31491    clearShadowInputText: function () {
31492        this.setShadowInputText("");
31493    },
31494    /**
31495     * Sets the shadow input if it finds a matching term in the shadowtext list.
31496     *  Empties it if there is not matching term
31497     */
31498    adjustShadowInput: function () {
31499        var that = this;
31500        var selectedPrediction = that.shadowTextArray[that.shadowIndex],
31501            searchTerm = that.$searchInput.val(),
31502            regexp = that.getRegExp(searchTerm);
31503        if (searchTerm && searchTerm.length >= that.minChars && that.shadowTextArray.length && regexp.test(selectedPrediction)) {
31504            var caseSensitiveTerm = that.combineTermAndPrediction(searchTerm, regexp.exec(selectedPrediction)[0]);
31505            that.setShadowInputText(caseSensitiveTerm);
31506        } else {
31507            that.clearShadowInputText();
31508        }
31509    },
31510    /**
31511     * Fuses the search input string with the prediction term so the shadow text is cased correctly
31512     * @param term
31513     * @param prediction
31514     */
31515    combineTermAndPrediction: function (term, prediction) {
31516        var termLength = term.length,
31517            predictionLength = prediction.length,
31518            subString = prediction.substr(termLength, (predictionLength - 1)),
31519            combo = term + subString;
31520
31521        return combo;
31522    },
31523    /**
31524     * Creates a regex object to out of the term (the string in the search input)
31525     *  used for matching shadowtext to the input
31526     * @param term
31527     * @returns {RegExp}
31528     */
31529    getRegExp: function () {
31530        var searchTerm = SHC.util.escapeCharactersForRegEx(this.searchTerm);
31531        return new RegExp("\\b" + searchTerm + ".*", "i");
31532    },
31533    /**
31534     * Empties the suggestion and prediction divs
31535     */
31536    emptyPulldown: function () {
31537        this.$predictiveDiv.empty();
31538    },
31539    drawPulldown: function(force) {
31540        var that = this;
31541        if (that.searchTerm !== undefined) {
31542            var term = jQuery.trim(that.searchTerm);
31543            if (term.length < that.minChars) {
31544                that.clearShadowInputText();
31545                that.shadowTextArray = [];
31546                that.emptyPulldown();
31547            } else if (term !== that.previousTerm || force) {
31548                that.doSuggestedPredictedQueries(term);
31549            }
31550            that.previousTerm = term;
31551        }
31552    },
31553    /**
31554     * Handlers and binding of events on and in the search input
31555     */
31556    setupEventHandlers: function () {
31557        var that = this;
31558        // scrolls through the suggested/predictive items
31559        var upArrow = function () {
31560            that.$predictiveDiv.find(".link-item a").removeClass("active");
31561            // if we are somewhere below the input, go up one
31562            if (that.currentlySelectedSuggestion > -1) {
31563                that.currentlySelectedSuggestion--;
31564                // if we are still below the input, move the active around and scroll if we have to
31565                if (that.currentlySelectedSuggestion !== -1) {
31566                    var activeAnchor = that.$predictiveDiv.find(".link-item:eq(" + (that.currentlySelectedSuggestion) + ") a");
31567                    activeAnchor.addClass("active");
31568                    var element = activeAnchor.offset().top;
31569                    var elementAfter = activeAnchor.position().top;
31570                    var win = jQuery(window).height();
31571                    var top = $(window).scrollTop();
31572                    var x = activeAnchor.height() * 3;
31573                    var targetHeight = elementAfter - x;
31574                    if ((top + win - targetHeight) > win) {
31575                        $('#search-container').scrollTop(targetHeight);
31576                    }
31577                }
31578            } else {
31579                that.currentlySelectedSuggestion = -1;
31580            }
31581        };
31582        // scrolls through the suggested/predictive items
31583        var downArrow = function () {
31584            var lastSuggestionPosition = (that.shadowTextArray && that.shadowTextArray.length) ? that.shadowTextArray.length - 1 : 0;
31585            if (that.currentlySelectedSuggestion < lastSuggestionPosition) {
31586                that.currentlySelectedSuggestion++;
31587            } else {
31588                that.currentlySelectedSuggestion = lastSuggestionPosition;
31589            }
31590            that.$predictiveDiv.find(".link-item a").removeClass("active");
31591            var activeAnchor = that.$predictiveDiv.find(".link-item:eq(" + (that.currentlySelectedSuggestion) + ") a");
31592            activeAnchor.addClass("active");
31593            var element = activeAnchor.offset().top;
31594            var elementAfter = activeAnchor.position().top;
31595            var win = jQuery(window).height();
31596            var x = activeAnchor.height();
31597            var windowMovement = element - win + x;
31598            var divMovement = elementAfter - win + x + 184;
31599            var $searchDiv = jQuery('#search-container');
31600            var $window = jQuery(window);
31601            if ($window.scrollTop() >= $searchDiv.offset().top ) {
31602                // plain scroll div
31603                // force a scroll to engage the scroll handler
31604                $window.scrollTop($("#search-container").offset().top + 1);
31605                $('#search-container').scrollTop(elementAfter - win + x + 184);
31606            } else {
31607                if($window.scrollTop() + windowMovement > $searchDiv.offset().top){
31608                    // scroll the window down to the div plus a pixel to force the handler
31609                    $window.scrollTop($searchDiv.offset().top + 1);
31610                    // wait for scroll hander then scroll in the div
31611                    setTimeout(function(){$searchDiv.scrollTop(divMovement);},1);
31612                } else {
31613//                    //plain scroll win
31614                    if ($window.scrollTop() !== 0) {
31615                        if (windowMovement > $window.scrollTop()) {
31616                            that.dropdownUtil.checkPulldownHeight();
31617                            $window.scrollTop(windowMovement);
31618                        }
31619                    } else {
31620                        that.dropdownUtil.checkPulldownHeight();
31621                        $window.scrollTop(windowMovement);
31622                    }
31623                }
31624            }
31625        };
31626        // completes the prediction
31627        var rightArrow = function () {
31628            var prediction = that.$shadowInput.val();
31629            if (prediction) {
31630                that.$searchInput.val(prediction);
31631            }
31632        };
31633        // this is bound to the search input. When you click into it, drop any actives, reset the scroll
31634        //  position, and completes the prediction
31635        // TODO I don't think this should complete the prediction. Need to check with design
31636        that.onSearchInputClickHandler = function (e) {
31637            that.$predictiveDiv.find(".link-item a").removeClass("active");
31638            that.currentlySelectedSuggestion = -1;
31639        };
31640        // key events while you are in the search input
31641        that.keydownHandler = function (evt) {
31642            switch (evt.which) {
31643                // down
31644                case 40:
31645                    downArrow();
31646                    break;
31647                // up
31648                case 38:
31649                    evt.preventDefault();
31650                    upArrow();
31651                    break;
31652                // right
31653                case 39:
31654                    rightArrow();
31655                    break;
31656                // tab
31657                case 9:
31658                    evt.preventDefault();
31659                    rightArrow();
31660                    break;
31661            }
31662        };
31663        // makes sure the search term is whatever is in the input at keyup
31664        that.keyupHandler = function (evt) {
31665            that.adjustShadowInput();
31666        };
31667
31668        that.searchTermKeyUpHandler = function (e) {
31669            var timer;
31670            // clear the timer as keys are still entered
31671            if (timer) {
31672                clearTimeout(timer);
31673            }
31674            if (that.$searchInput) {
31675                that.searchTerm = that.$searchInput.val();
31676            }
31677            timer = setTimeout(function () {
31678                that.drawPulldown();
31679            }, 350);
31680        };
31681        that.exactMatchTrialClickHandler = function (e) {
31682            $(window).on('hashchange', function() {
31683                window.location.reload();
31684            });
31685        };
31686        that.$searchInput.keydown(that.keydownHandler);
31687        that.$searchInput.keyup(that.keyupHandler);
31688        that.$searchInput.on("mouseup", that.onSearchInputClickHandler);
31689        that.$searchInput.keyup(that.searchTermKeyUpHandler);
31690        $('#search-row').off('click', 'a.exact-match', that.exactMatchTrialClickHandler)
31691            .on('click', 'a.exact-match', that.exactMatchTrialClickHandler);
31692    },
31693    removeEventHandlers: function () {
31694        var that = this;
31695        that.$searchInput.unbind("keydown", that.keydownHandler);
31696    },
31697    //hides the result div if there are no results maching search term
31698    hideIfNoResults: function(balancedResults){
31699        var displayResults = false;
31700        var template = jQuery("#shc-search-title").attr("data-page-template");        
31701        if (this.isStanfordlab && balancedResults.slab && balancedResults.slab.length > 0) { 
31702            return true;
31703        }
31704        if (window.location.href.indexOf('search-results.newsroom.html') > 0 || 
31705         (template && (template.indexOf("newsroomlanding")>-1 || 
31706         template.indexOf("newsroomlisting")>-1))){
31707            if(this.predictiveResults[0].data.length > 0
31708                || this.predictiveResults[1].data.length > 0
31709                || this.predictiveResults[2].data.length > 0){
31710                displayResults = true
31711            }
31712        } else {
31713            for(var i=0; i < balancedResults.categories.length; i ++){
31714                if(balancedResults.categories[i].count > 0){
31715                    displayResults = true;
31716                }
31717            }
31718        }
31719        return displayResults;
31720    },
31721    bindUpdateSelector: function() {
31722        var that = this;
31723        $(window).on("updateSearchDirectorySelector", function() {
31724            that.selectorName = that.getSelectorName();
31725        });
31726        // bind resize handler only when #search-term exists
31727        if (that.$searchInput.length>0) {
31728            $(window).on("resizeEnd", function(){
31729                that.drawPulldown(true); // force redraw
31730            });
31731        }
31732    },
31733    isDoctorPredictiveDropdown: function(fullyGroomedJson){
31734        var isDoctorPredictive = false;
31735        if(window.location.href.indexOf('search-results.doctors.html') > 0
31736            && typeof fullyGroomedJson.categories !== 'undefined'
31737            && fullyGroomedJson.categories.length > 0
31738            && fullyGroomedJson.categories[0].heading === 'Doctors & Providers'){
31739            for (var i = 0; i < fullyGroomedJson.categories.length; i++) {
31740                if(i === 0 && fullyGroomedJson.categories[i].count > 0){
31741                    isDoctorPredictive = true;
31742                }else if(fullyGroomedJson.categories[i].count > 0){
31743                    isDoctorPredictive = false;
31744                    break;
31745                }
31746            }
31747        }
31748        return isDoctorPredictive;
31749    }
31750});
31751SHC.Namespace(SHC, "SHC.ui.Search.Dropdown.Tabbar");
31752SHC.ui.Search.Dropdown.Tabbar = new SHC.Class();
31753
31754SHC.ui.Search.Dropdown.Tabbar.include({
31755    init: function(sendNewJsonToSearchCallback) {
31756        this.activeTab = null;
31757        this.searchNav = null;
31758        this.sendNewJsonToSearchCallback = sendNewJsonToSearchCallback;
31759        this.$window = jQuery(window);
31760        this.$filterArea = jQuery("#dropdown-filter");
31761        this.$more = jQuery("a.more");
31762        this.dropdownUtil = new SHC.ui.Search.DropdownUtil();
31763    },
31764
31765    /**
31766     * This method activates this dropdown by resuming functionality (if necessary)
31767     */
31768    activate: function() {
31769        // bind events
31770        this.initializeActiveTab();
31771        this.setupTabbarLinks();
31772        this.determineNoTouchClassForHover();
31773    },
31774    /**
31775     * This method activates this dropdown by pausing functionality (if necessary)
31776     */
31777    deactivate: function() {
31778        this.searchNav.off("click.dropdown-tabbar");
31779        jQuery("body").off("click.dropdown-tabbar");
31780        jQuery("body").off("touchend.dropdown-tabbar");
31781        return;
31782    },
31783
31784    /**
31785     * Ensures that the View All tab is the active tab, and calls functions to set up the 'More'
31786     */
31787    initializeActiveTab: function() {
31788        //this.bindTabClicks();
31789        var defaultTab = this.searchNav.find(".all-results-link").first();
31790        if (!this.activeTab) {
31791            this.activeTab = defaultTab;
31792        }
31793        this.updateActiveTab(this.activeTab);
31794    },
31795
31796
31797    /**
31798     * making the tab active, and reordering
31799     */
31800    updateActiveTab: function (item) {
31801        var that = this;
31802        that.searchNav.find("a").removeClass("active");
31803        item.closest("li").find("a").addClass("active");
31804        that.activeTab = item;
31805        item.addClass('active');
31806        that.updateNotchAndBorders();
31807        //check if item is in more list
31808        var isMoreItem = item.closest('.search-nav-more-container').length > 0;
31809        //if more item
31810        if (isMoreItem) {
31811            //put it directly after 'doctors'
31812            $('#search-nav').find('ul').children().eq(1).after(item.parent().removeClass("more-item"));
31813        }
31814        that.reorderTabs();
31815    },
31816    updateNotchAndBorders: function() {
31817        var that = this;
31818        //only remove border and notch if there's no filters dropdown
31819        if(!$("#filters").height()) {
31820            that.searchNav.find("li").removeClass("active");
31821            $("#dropdown-tabbar").removeClass("active");
31822        }
31823    },
31824
31825    /**
31826     * makes the tab bar and attaches handlers
31827     * @returns {searchNav which is tab bar html}
31828     */
31829    setupTabbarLinks: function() {
31830        var that = this;
31831        //click handler for the "more" dropdown on the tab bar
31832        var onSearchNavClickHandler = function (e) {
31833            e.stopPropagation();
31834            var target = jQuery(this);
31835            //don't adjust active tabs when 'more' is clicked
31836            if(!target.hasClass('more')) {
31837                that.searchNav.find("a").removeClass("active");
31838                target.addClass("active");
31839                that.updateNotchAndBorders();
31840                target.parent().addClass("active");
31841            }
31842            that.searchNavMore.toggle();
31843        };
31844
31845        //if we don't have one, make a hardcoded tab bar
31846        this.moreDropdownEventHandler();
31847        this.bindTabClicks();
31848
31849        this.searchNavMore = this.searchNav.find(".search-nav-more-container");
31850        this.searchNav.on("click.dropdown-tabbar", ".more", onSearchNavClickHandler);
31851    },
31852
31853     /**
31854     * This returns makes tab bar
31855     */
31856    getDropdownMarkup: function() {
31857         if (!this.searchNav) {
31858             var template = JST["handlebars/searchCategoriesTemplate.hbs"];
31859             this.searchNav = jQuery(template({}));
31860         }
31861        return this.searchNav;
31862    },
31863
31864    /**
31865     * Handles the "more" dropdown in the search results
31866     */
31867    moreDropdownEventHandler: function() {
31868        var that = this;
31869        jQuery("body").on("click.dropdown-tabbar", function (e) {
31870           if(that.searchNavMore.is(":visible")) {
31871                $(".search-nav-more-container").hide();
31872            }
31873        });
31874        //closes the dropdown when clicked outside on mobile
31875        jQuery("html, body").on("touchend.dropdown-tabbar", function (e) {
31876            if(!$(e.target).hasClass('more') && !$(e.target).parents('.search-nav-more-container').length && that.searchNavMore.is(":visible")) {
31877                $(".search-nav-more-container").hide();
31878            }
31879        });
31880
31881        //this only applies to non-directory pages
31882        this.$window.on('resizeEnd', that.reorderTabs);
31883    },
31884
31885    /**
31886     * Moves overfow tabs into "more"
31887     */
31888    reorderTabs: function() {
31889        var that = this;
31890        var viewSize = SHC.ui.screenMode;
31891        var tabs = $('#search-nav').find('ul').first();
31892        var moreTabs = tabs.find('.search-nav-more-container');
31893
31894        var NUM_TABS_MOBILE = 4;
31895        var NUM_TABS_TABLET = 4;
31896        var NUM_TABS_DESKTOP = 5;
31897
31898        //move all channels out of more section and remove 'more-item' class
31899        tabs.children().last().before(moreTabs.children().not(".arrow").removeClass("more-item"));
31900
31901        //put them back in as needed
31902        //mobile
31903        var lastTab;
31904        var count = 0; //avoid infinite loop
31905        if (viewSize === 'small') {
31906            while (tabs.children().length > NUM_TABS_MOBILE && count < 20) {
31907                lastTab = tabs.children().last().prev();
31908                lastTab.addClass("more-item");
31909                moreTabs.prepend(lastTab);
31910                count++;
31911            }
31912        }
31913        //tablet
31914        else if (viewSize === 'medium') {
31915            while (tabs.children().length > NUM_TABS_TABLET && count < 20) {
31916                lastTab = tabs.children().last().prev();
31917                lastTab.addClass("more-item");
31918                moreTabs.prepend(lastTab);
31919                count++;
31920            }
31921        }
31922        //desktop
31923        else {
31924            while (tabs.children().length > NUM_TABS_DESKTOP && count < 20) {
31925                lastTab = tabs.children().last().prev();
31926                lastTab.addClass("more-item");
31927                moreTabs.prepend(lastTab);
31928                count++;
31929            }
31930        }
31931
31932        if (moreTabs.children().not('.arrow').length < 1) {
31933            moreTabs.parent().hide();
31934        } else {
31935            moreTabs.parent().show();
31936        }
31937    },
31938
31939    /**
31940     * binds all of the tab clicks in one call
31941     */
31942    bindTabClicks: function () {
31943        this.bindATabClick(".all", "organic");
31944        if (SHC.util.isValleycare()) {
31945            this.bindATabClick(".events", "vc_events");
31946        } else {
31947            this.bindATabClick(".events", "organic_events");
31948        }
31949        this.bindATabClick(".stories", "organic_stories");
31950    },
31951    /**
31952     * Bind a start search on doer to the selector
31953     */
31954    bindATabClick: function (selector, doer) {
31955        var that = this;
31956        jQuery("#control-dropdown-desktop, #control-dropdown-mobile").on("click", selector, function (e) {
31957            if(SHC.ui.Search.DirectoryUtil.getCurrentDirectory() === "all") {
31958                if(doer === "organic") {
31959                    $(".more-container").hide();
31960                    $(".more-symbol.open").removeClass("open").addClass("closed");
31961                }
31962                $("#toggle-title").text(SHC.ui.Search.DirectoryUtil.getDirectoryControlTitleForDoer(doer));
31963                SHC.ui.Search.DirectoryUtil.processedFilter = true;
31964                that.bindStartSearch(e, doer, jQuery(this));
31965                jQuery('#sort-menu-target').empty();
31966            }
31967            else {
31968                var pred = window.location.search.indexOf("src=pred") > 0 ? '&src=pred' : '';
31969                var filter = "?doer=" + doer + pred;
31970                var searchTerm = SHC.ui.Search.DirectoryUtil.getSearchTerm();
31971                if(searchTerm != null) {
31972                    window.location = SHC.ui.Search.DirectoryUtil.searchResultsUrl + "/" + searchTerm + filter;
31973                }
31974                else {
31975                    window.location = SHC.ui.Search.DirectoryUtil.searchResultsUrl;
31976                }
31977            }
31978        });
31979    },
31980
31981    /**
31982     * does a start search on the doer and makes the target (a tab) active
31983     */
31984    bindStartSearch: function (e, doer, target, onDataHandler) {
31985        var that = this;
31986        this.$filterArea.empty();
31987        var binder = new SHC.ui.Search.ResultsBinder();
31988        if (onDataHandler && typeof onDataHandler === 'function') {
31989            var onDataHandlerWrapper = function (data) {
31990                onDataHandler(data);
31991                // trigger this when data is received.
31992            };
31993            binder.startSearch(doer, onDataHandlerWrapper);
31994        } else {
31995            binder.startSearch(doer);
31996        }
31997        this.updateActiveTab(target);
31998    },
31999    determineNoTouchClassForHover: function () {       
32000        if (!("ontouchstart" in document.documentElement)) {          
32001            jQuery('.more').addClass('no-touch');
32002        }
32003     }
32004});
32005
32006SHC.Namespace(SHC, "SHC.ui.Search.DropdownUtil");
32007SHC.ui.Search.DropdownUtil = new SHC.Class();
32008
32009SHC.ui.Search.DropdownUtil.include({
32010    /**
32011     * constructor
32012     */
32013    init: function () {
32014        //basic base stuff
32015        var that = this;
32016        //scroll
32017        this.isStanfordlab = SHC.util.isStanfordlab();
32018        this.$searchInpagenav = jQuery('#search-inpagenav');
32019        this.$searchContainer = jQuery('#search-container');
32020        this.$window = jQuery(window);
32021        this.$pulldown = jQuery("#search-pulldown");
32022        this.$dropdownfilter = jQuery("#dropdown-filter");
32023        this.template = jQuery('#shc-search-title').attr('data-page-template');
32024        this.$childPages = jQuery('.child-pages');
32025        this.$body = $('body');
32026        this.$mastheadAffixed = this.isStanfordlab ? $('.masthead-cmp.stanfordlab') : $('.masthead-affixed');
32027        this.template = $('#shc-search-title').attr('data-page-template');
32028    },
32029
32030    /**
32031     * when the search bar is focused it checks to decide whether the dropdown will be
32032     * off page and based on calculations, adds the appropriate css classes to
32033     * lock the screen
32034     */
32035    checkPulldownHeight: function() {
32036        if(SHC.ui.screenMode !== "small"){
32037            if(SHC.util.isIOS()) {
32038                // scroll up to the search bar
32039                this.$body.animate({scrollTop: this.$searchContainer.offset().top}, 750);
32040            } else if(Modernizr.touch && navigator.platform.indexOf("Win") === -1) {
32041                // places the search at the top of the page and scroll to it
32042                this.$searchContainer.addClass("window-scrolly-parent");
32043            } else {
32044                var currentPostion = this.$searchContainer.offset().top - $(window).scrollTop(),
32045                    originalPosition = this.$searchContainer.position().top;
32046                var onScreen = this.onScreen(this.$searchContainer);
32047
32048                var that = this,
32049                    currentScroll,
32050                    clickedInPageNavTop = this.$searchContainer.offset().top,
32051                    childPages = that.$pulldown.find(".child-pages.hidden-sm").outerHeight(),
32052                    childPages2 = that.$pulldown.find(".child-pages.visible-sm").outerHeight(),
32053                    alertContainer = $('#new-emergency-alert'),
32054                    searchNavHeight =  this.$searchContainer.outerHeight(),
32055                    searchPulldownHeight = this.$pulldown.outerHeight();
32056                    currentScroll = that.$window.scrollTop();
32057
32058                    var calculations = {
32059                        clickedInPageNavTop: clickedInPageNavTop,
32060                        currentScroll: currentScroll
32061                    };
32062                    var newTop = (clickedInPageNavTop - currentScroll);
32063
32064                    var totalHeight = searchPulldownHeight + newTop
32065                            + searchNavHeight + childPages + childPages2;
32066
32067                //don't freeze if they click off before predictive results have loaded
32068                if (this.$dropdownfilter.hasClass("dropdownShow")) {
32069                    return;
32070                }
32071
32072                //check if dropdown is going to be off page
32073                if (totalHeight > this.$window.height()) {
32074                    that.$window.off('.freezingSearchBarAnDropdowns');
32075                    this.$window.on('scroll.freezingSearchBarAndDropdowns', calculations, function(e){
32076                        that.pulldownScrollHandler(e);
32077                    });
32078                //handle dropdown if not going to be off page
32079                } else {
32080                    that.addScrollyClasses();
32081                }
32082
32083                if(onScreen) {
32084                    if (alertContainer.length === 1) {
32085                        this.$searchContainer.css('top' , '57px');
32086                    } else {
32087                        this.$searchContainer.css('top' , originalPosition + 'px');
32088                    }
32089                } else {
32090                    // if search bar isn't visible and .search-button is clicked
32091                    var slabOffset = this.isStanfordlab ? 200 : 0;
32092                    this.$searchContainer.css( 'top', Math.ceil( this.$window.scrollTop() - 35 + slabOffset )+ 'px');
32093                }
32094            }
32095        } else {
32096            this.$body.animate({scrollTop: 0}, 250);
32097        }
32098    },
32099
32100    /**
32101     * allows scrolling til you hit the search bar and then the search bar and dropdown are scrollable but
32102     * the rest of the page is locked
32103     * @param event
32104     */
32105    pulldownScrollHandler: function(event) {
32106        var that = this;
32107        var eventData = event.data;
32108
32109        if ( that.$window.scrollTop() >= eventData.clickedInPageNavTop && that.$pulldown.outerHeight() > 0) {
32110            //add classes to elements to freeze the screen and allow the pulldown to scroll
32111            that.addScrollyClasses();
32112            that.$searchContainer.css({'top' : ''});
32113        } else {
32114            that.removeScrollyClasses();
32115        }
32116    },
32117
32118    /**
32119     * removes classes from pulldownScrollHandler and unbinds event
32120     */
32121    removePulldownScrollHandler: function() {
32122        var that = this;
32123        //remove classes that freeze elements allowing pulldown to scroll
32124        that.removeScrollyClasses();
32125        //unbinding the event
32126        that.$window.off('.freezingSearchBarAndDropdowns');
32127    },
32128
32129    addScrollyClasses: function() {
32130        var that = this,
32131            scrollTop = jQuery(window).scrollTop(),
32132            searchContainer = jQuery('#search-container' ),
32133            topPos = searchContainer.offset(),
32134            elHeight = searchContainer.outerHeight(),
32135            combHeight = topPos.top + elHeight;
32136        that.$body.addClass('window-scrolly-body');
32137        that.$searchContainer.addClass('window-scrolly-parent');
32138        that.$pulldown.addClass('window-scrolly');
32139        $('.child-pages').addClass('window-scrolly');
32140    },
32141
32142    removeScrollyClasses: function() {
32143        var that = this;
32144        that.$body.removeClass('window-scrolly-body');
32145        that.$searchContainer.removeClass('window-scrolly-parent');
32146        that.$pulldown.removeClass('window-scrolly');
32147         $('.child-pages').removeClass('window-scrolly');
32148        that.$searchContainer.css({'top' : ''});
32149    },
32150
32151    isLowerLevelPage: function() {
32152        return (this.template !== "/apps/shc/templates/home"
32153            && this.template !== "/apps/shc/templates/valleycare/valleycarehome"
32154            && this.template !== "/apps/shc/templates/searchresults"
32155            && this.template !== "/apps/shc/templates/directory"
32156            && this.template !== "/apps/shc/templates/newsroomlanding"
32157            && this.template !== "/apps/shc/templates/newsroomlisting"
32158            && this.template !== "/apps/shc/templates/clinicaltrials_search");
32159    },
32160
32161    onScreen: function($element) {
32162        var elementTop = $element.offset().top;
32163        var elementBottom = elementTop + $element.height();
32164        var windowTop = $(window).scrollTop();
32165        var windowBottom = $(window).scrollTop() + $(window).height();
32166        var mastheadTop = this.$mastheadAffixed.offset().top; // should always be 0
32167        var mastheadBottom = this.$mastheadAffixed.height();
32168        var bottomInView = elementBottom <= windowBottom;
32169        var topInView = elementTop >= windowTop;
32170        var coveredByMasthead = (38 + elementTop - windowTop) <= mastheadBottom;
32171        return bottomInView && topInView && !coveredByMasthead;
32172    }
32173});
32174
32175SHC.Namespace(SHC, "SHC.ui.Search.MegaSearch");
32176SHC.ui.Search.MegaSearch = new SHC.Class();
32177
32178SHC.ui.Search.MegaSearch.include({
32179    /**
32180     * constructor
32181     * @param selector
32182     */
32183    init: function () {
32184        "use strict";
32185
32186        // configurables
32187        this.resultLimit = 12;
32188        this.minChars = 3;
32189
32190        this.headerTexts = {fallback: 'What can we help you find?', organic_phys: 'Search by name or specialty', organic_conds_txs: 'Search conditions & treatments',
32191            organic_clinics: 'Search by name, specialty, or city', organic_clinical_trials: 'Search by condition', organic_newsroom: 'Search Newsroom'};
32192
32193        this.autoCompleteUrl = "//content.atomz.com/autocomplete/sp10/04/f3/b2/?query=";
32194        this.searchUrl = GLOBAL_SPURL_OBJECT + "/?do=pred&q=";
32195          // whitelisted parameters:
32196        this.safelist = ["gclid","utm_medium","utm_source","utm_campaign","utm_term","utm_content",
32197          "kwcid","campaignid","adgroup","keyword","matchtype","position","ecid"];
32198        // get the global search results template. If it is empty then fallback to the SHC search results template
32199        this.searchResultsTemplate = GLOBAL_SEARCH_RESULTS_TEMPLATE ? GLOBAL_SEARCH_RESULTS_TEMPLATE : "/apps/shc/templates/searchresults";
32200        this.searchResultsTemplateSHCA = GLOBAL_SEARCH_RESULTS_TEMPLATE ? GLOBAL_SEARCH_RESULTS_TEMPLATE : "/apps/shca/templates/searchresults";
32201        this.margin = 43;
32202        this.transitionDuration = 200;
32203        this.previousTerm = null;
32204        this.shadowTextArray = [];
32205
32206        this.$window = $(window);
32207        this.$body = $('body');
32208        this.$searchInpagenav = $('#search-inpagenav');
32209        this.$searchInpagenavWrapper = $('#search-inpagenav-wrapper');
32210        this.$magnifyingGlass = $(".search-toggle");
32211        this.$searchTitle = $("#shc-search-title");
32212        this.$searchMagnifyingGlass = $("#search-magnifying-glass");
32213        this.$searchInput = $('#search-term');
32214        this.$searchForm = $('#search-form');
32215        this.$searchContainer = $("#search-container");
32216        this.$clickScreen = $('#click-screen');
32217        this.$searchRow = $("#search-row");
32218        this.$pageTitle = $("#search-container .shc-page-title");
32219        this.$searchInputs = $("#search-input-container");
32220        this.$searchInputWrapper = $("#search-input-wrapper");
32221        this.$shadowInput = $("#prediction").attr("disabled", "disabled");
32222        this.$inPageNav = $('#in-page-nav-wrapper');
32223        this.$predictiveDiv = $("#dropdown-predict");
32224        this.$filterArea = $('#filter-area');
32225        this.$clearButton = $("#search-clear");
32226        this.$mastheadAffixed = $('.masthead-affixed');
32227        this.predictionInput = $("#prediction");
32228        this.$skipToMainLink = $(".skip-to-main-content-link");
32229        this.clickScreenRestoreFilters = false;
32230
32231        this.currentlySelectedSuggestion = -1;
32232
32233        // This contains each of the dropdown divs
32234        this.$pulldownDiv = $("#search-pulldown");
32235
32236        this.dropdownUtil = new SHC.ui.Search.DropdownUtil();
32237        if (!SHC.util.isStanfordlab()) {
32238            if (GLOBAL_MICROSITE_SRC && GLOBAL_MICROSITE_SRC.length > 0) {
32239                this.masthead = new SHC.ui.SHCMasthead();
32240            } else {
32241                this.masthead = new SHC.ui.Masthead();
32242            }
32243        }
32244
32245        this.$dropdownTabbarDiv = jQuery('#dropdown-tabbar');
32246        this.$dropdownFilterDiv = jQuery('#dropdown-filter');
32247        this.$dropdownPredictDiv = jQuery('#dropdown-predict');
32248
32249        this.shadowIndex = 0;
32250
32251        this.searchAndPromoteJson = null;
32252        this.searchAndPromoteDoer = null;
32253        this.template = jQuery('#shc-search-title').attr('data-page-template');
32254
32255        this.setHeaderText();
32256        this.$searchInput.attr("placeholder", this.placeHolderText);
32257        this.$searchTitle.html(this.placeHolderText);
32258        this.setupEventHandlers();  // sets up events on the search bar for autocomplete, etc
32259
32260        this.buildAndActivateDropdowns();
32261        this.determineNoTouchClassForHover();
32262
32263        this.controlToggle = jQuery("#control-dropdown-toggle");
32264        this.controlArrow = jQuery("#toggle-arrow");
32265
32266        this.controlDropdownDesktop = jQuery("#control-dropdown-desktop");
32267        this.controlDropdownItems = jQuery(".control-item");
32268        this.controlMoreToggle = jQuery('.more-toggle');
32269        this.controlMoreContainer = jQuery('.more-container');
32270        this.controlMoreSymbol = jQuery('.more-symbol');
32271
32272        this.controlDropdownMobile = jQuery('#control-dropdown-mobile');
32273        this.controlDropdownItemsMobile = jQuery('#control-dropdown-mobile .control-item');
32274        this.controlDropdownMoreMobile = jQuery('#control-dropdown-mobile .more-toggle');
32275
32276        this.controlTitle = jQuery('#toggle-title');
32277
32278        this.globalSearchStarted = false;
32279        this.controlOriginalActive = '';
32280
32281        this.userClick = false;
32282        this.resizeEvent = false;
32283        this.isValleycare = SHC.util.isValleycare();
32284        this.isStanfordlab = SHC.util.isStanfordlab();
32285        this.isClassesPage = window.location.href.indexOf("valleycare/en/events.html") > -1;
32286        this.isSupportGroupsPage = window.location.href.indexOf("valleycare/en/support-groups.html") > -1;
32287
32288        // only attach if you're on a page with the control
32289        if (this.controlToggle.length) {
32290            this.attachControlEvents();
32291        }
32292
32293        this.browserInfo = navigator.userAgent.toLowerCase();
32294        this.isFireFoxMobile = this.browserInfo.match(/(android|ipod|iphone|ipad|apple)/) && this.browserInfo.match(/firefox/) ? true : false;
32295        this.defaultSearchText = [  'Search by name or specialty',
32296                                    'Search by name, specialty, or city',
32297                                    'Search conditions & treatments',
32298                                    'What can we help you find?',
32299                                    'Search by condition',
32300                                    'Search Newsroom',
32301                                    'Search Tri-Valley',
32302                                    'Search Stanford Lab'];
32303        this.searchDirectory = SHC.ui.Search.DirectoryUtil.getCurrentDirectory();
32304    },
32305
32306    /**
32307     * Determines the default text in the search bar
32308     */
32309    setHeaderText: function() {
32310        var fallbackPlaceholder = this.headerTexts.fallback;
32311        //setting the search bar default text
32312        try {
32313            if (this.template === "/apps/shc/templates/home"
32314                || this.template === "/apps/shc/templates/valleycare/valleycarehome"
32315                || this.template === "/apps/shc/templates/newsroomlanding"
32316                || this.isStanfordlab) {
32317                this.placeHolderText = fallbackPlaceholder;
32318            } else if(this.template === "/apps/shc/templates/clinicaltrials_search") {
32319                this.placeHolderText = this.headerTexts.organic_clinical_trials;
32320            } else if (this.template === this.searchResultsTemplate || this.template === '/conf/shc/settings/wcm/templates/stanfordlab-site-search-results') {
32321                var searchterm = SHC.util.getURLSearchTerm(location.pathname);
32322                if(searchterm) {
32323                    this.$searchInput.val(searchterm);
32324                }
32325                else if (typeof GLOBAL_DIRECTORY_OBJECT !== 'undefined' && GLOBAL_DIRECTORY_OBJECT !== null) {
32326                    switch (GLOBAL_DIRECTORY_OBJECT) {
32327                        case("organic_phys"):
32328                            this.placeHolderText = this.headerTexts.organic_phys;
32329                            break;
32330                        case("organic_conds_txs"):
32331                            this.placeHolderText = this.headerTexts.organic_conds_txs;
32332                            break;
32333                        case("organic_clinics"):
32334                            this.placeHolderText = this.headerTexts.organic_clinics;
32335                            break;
32336                        case("organic_clinical_trials"):
32337                            this.placeHolderText = this.headerTexts.organic_clinical_trials;
32338                            break;
32339                        case("organic_newsroom"):
32340                            this.placeHolderText = this.headerTexts.organic_newsroom;
32341                            break;
32342                        default:
32343                            this.placeHolderText = fallbackPlaceholder;
32344                            break;
32345                    }
32346                }
32347                else {
32348                    this.placeHolderText = fallbackPlaceholder;
32349                }
32350
32351            }
32352        } catch (e) {
32353        }
32354    },
32355
32356    /**
32357     * This builds the dropdowns, inserts their markup into their respective divs, deactivates all of them, and then
32358     * determines which ones need to be active and activates them.
32359     */
32360    buildAndActivateDropdowns: function () {
32361        var that = this;
32362
32363        // wrap the callbacks
32364        var wrappedGotNewJsonFromTabbar = function(doer, data){
32365            that.gotNewJsonFromTabbar(doer, data);
32366        };
32367
32368        // instantiate the 5 different dropdown objects
32369        this.tabbarDropdown = new SHC.ui.Search.Dropdown.Tabbar(wrappedGotNewJsonFromTabbar);
32370        this.filterDropdown = new SHC.ui.Search.Dropdown.Filter();
32371        SHC.clinicalTrialsFilter = {};
32372        SHC.clinicalTrialsFilter.filter = this.filterDropdown;
32373        this.predictDropdown = new SHC.ui.Search.Dropdown.Predict();
32374
32375        // insert object contents into their respective divs
32376        // Some of these probably haven't ajaxed their markup yet
32377        this.$dropdownTabbarDiv.html(this.tabbarDropdown.getDropdownMarkup());
32378        this.$dropdownFilterDiv.html(this.filterDropdown.getDropdownMarkup());
32379        this.$dropdownPredictDiv.html(this.predictDropdown.getDropdownMarkup());
32380
32381        // activate and show certain dropdowns
32382        this.initialDropdownActivation(false);
32383        this.initialDropdownShow();
32384    },
32385
32386    /**
32387     * logically activate desired dropdowns
32388     * only these dropdowns potentially need to show right off the bat -- the others show onClick()
32389     */
32390    initialDropdownActivation: function(ignore){
32391        var that = this;
32392
32393        this.deactivateAllDropdowns();
32394
32395        /* Need this in all templates now due to desired behaviour of the More menu links,
32396           we should rename tabbar to something more meaningful eventually, since it's not a tabbar anymore. */
32397        that.activateDropdown(that.tabbarDropdown);
32398
32399        if (this.template === this.searchResultsTemplate || SHC.ui.Search.DirectoryUtil.isNewsroomLandingPage()) {
32400            /* Need this in all templates now due to desired behaviour of the More menu links,
32401               we should rename tabbar to something more meaningful eventually, since it's not a tabbar anymore. */
32402            that.activateDropdown(that.tabbarDropdown);
32403
32404            //make a binder
32405            var binder = new SHC.ui.Search.ResultsBinder();
32406
32407            if (typeof GLOBAL_DIRECTORY_OBJECT === 'undefined' || GLOBAL_DIRECTORY_OBJECT === null || GLOBAL_DIRECTORY_OBJECT === "") {
32408                //when passthrough goes to megasearch it crashes the page, change to normal query
32409                if (window.location.href.indexOf('search-results.html') > -1 && that.getIsPassthroughUrl()) {
32410                    var cleanUrl = window.location.pathname.split('.html/')[0] + '.html/' + that.getSearchTermFromPassthrough();
32411                    window.history.replaceState({"fromStartSearch": true}, '', cleanUrl);
32412                }
32413
32414                //start search on organic
32415                var organicSearch = "";
32416                if (SHC.util.isValleycare()) {
32417                    organicSearch = "organic_vc"
32418                } else if (SHC.util.isStanfordlab()) {
32419                    organicSearch = "slab";
32420                } else {
32421                    organicSearch = "organic";
32422                }
32423
32424                if (!ignore) {
32425                    binder.startSearch(organicSearch, function (data) {
32426                        that.searchAndPromoteJson = data;
32427                        that.searchAndPromoteDoer = organicSearch;
32428                        that.activateDropdown(that.filterDropdown, that.$dropdownFilterDiv);
32429                    });
32430                }
32431                that.showDropdown(that.$dropdownTabbarDiv);
32432            } else {
32433                if (!ignore) {
32434                    // get filter string
32435                    var urlHash = location.hash === "#" ? "" : location.hash;
32436
32437                    // get saved filters
32438                    var savedFilters = this.getSavedFilters(urlHash);
32439
32440                    if (urlHash) { //filterString
32441                        var filterString = urlHash.substr(1);
32442                        that.saveParsedParameters(filterString);
32443                        that.searchAndPromoteDoer = GLOBAL_DIRECTORY_OBJECT;
32444                        that.activateDropdown(that.filterDropdown);
32445                        if (filterString && filterString[0] !== "&") {
32446                            filterString = "&" + filterString;
32447                        }
32448                        if(SHC.util.primaryCareKeywords.indexOf(decodeURIComponent(that.$searchInput.val().toLowerCase())) > -1) {
32449                            binder.startSearch(GLOBAL_DIRECTORY_OBJECT, function (data) {
32450                                that.searchAndPromoteJson = data;
32451                            });
32452                        }else{
32453                            binder.filter(GLOBAL_DIRECTORY_OBJECT, filterString, function (data) {
32454                                that.searchAndPromoteJson = data;
32455                                // front end filter checks
32456                            });
32457                        }
32458                    } else if(savedFilters){
32459                        if(SHC.util.primaryCareKeywords.indexOf(decodeURIComponent(that.$searchInput.val().toLowerCase())) > -1) {
32460                            if (GLOBAL_DIRECTORY_OBJECT === 'organic_phys'){
32461                                savedFilters = SHC.savedSearch['doctors-filter-toggle-primary-care'];
32462                                SHC.savedSearch.toggle = 'doctors-filter-toggle-primary-care';
32463                            }
32464                            else if (GLOBAL_DIRECTORY_OBJECT === 'organic_clinics'){
32465                                savedFilters = SHC.savedSearch['clinics-filter-toggle-primary-care'];
32466                                SHC.savedSearch.toggle = 'clinics-filter-toggle-primary-care';
32467                            }
32468                        }
32469                        binder.filter(GLOBAL_DIRECTORY_OBJECT, savedFilters, function (data) {
32470                            that.searchAndPromoteJson = data;
32471                            // front end filter checks
32472                        });
32473                    } else {
32474                        sessionStorage.removeItem('shcFilters');
32475                        that.searchAndPromoteDoer = GLOBAL_DIRECTORY_OBJECT;
32476                        that.activateDropdown(that.filterDropdown);
32477                        //start search on directory
32478                        binder.startSearch(GLOBAL_DIRECTORY_OBJECT, function (data) {
32479                            that.searchAndPromoteJson = data;
32480                        });
32481                    }
32482                }
32483            }
32484        }
32485        else{
32486            sessionStorage.removeItem('shcFilters');
32487        }
32488    },
32489
32490    getSavedFilters: function(urlHash){
32491        var savedFilters = sessionStorage.getItem('shcFilters');
32492        if (savedFilters) {
32493            savedFilters = JSON.parse(savedFilters);
32494
32495            //populate the SHC.savedSearch variable
32496            if (!SHC.savedSearch) {
32497                SHC.savedSearch = {};
32498            }
32499            // find current toggle
32500            var toggle;
32501            if (GLOBAL_DIRECTORY_OBJECT === 'organic_phys'){
32502                toggle = 'doctors-filter-toggle-specialist';
32503                if (urlHash.indexOf('sp_prim_care_phy') >= 0){
32504                    toggle = 'doctors-filter-toggle-primary-care'
32505                }
32506            } else if (GLOBAL_DIRECTORY_OBJECT === 'organic_clinics'){
32507                toggle = 'clinics-filter-toggle-specialty-care';
32508                if (urlHash.indexOf('sp_prim_care_clinic') >= 0){
32509                    toggle = 'clinics-filter-toggle-primary-care'
32510                } else if (urlHash.indexOf('sp_other_service') >= 0){
32511                    toggle = 'clinics-filter-toggle-other-service'
32512                }
32513            } else if (GLOBAL_DIRECTORY_OBJECT === 'organic_conds_txs'){
32514                toggle = 'conditions-filter-toggle-all';
32515                if (urlHash.indexOf('x1=sp_type&q1=condition') >= 0){
32516                    toggle = 'conditions-filter-toggle-conditions'
32517                } else if (urlHash.indexOf('x1=sp_type&q1=treatment') >= 0){
32518                    toggle = 'conditions-filter-toggle-treatments'
32519                }
32520            }
32521            if (toggle) {
32522                SHC.util.saveSearch(savedFilters);
32523                SHC.savedSearch.toggle = toggle;
32524
32525                return SHC.savedSearch[toggle];
32526            }
32527        }
32528        return null;
32529    },
32530  /**
32531   * Stash a list of whitelisted parameters (safelist).
32532   * Save it in SHC.exports.saveParams for later retrieval.
32533   * @param filter a string
32534   * @returns {null}
32535   */
32536    saveParsedParameters: function(filter) {
32537        if (!filter) {
32538            return null;
32539        }
32540        var params = filter.replace("#","").split("&"), map = {};
32541        for (var i=0,n=params.length; i<n; i++) {
32542            var pair = params[i].split("=");
32543            if (pair[0] && pair[1] && this.safelist.indexOf(pair[0])>-1) {
32544                map[pair[0]] = pair[1];
32545            }
32546        }
32547        // check location.pathname and location.search
32548        // for a gclid parameter
32549        var gclidRegex = /gclid=(.*)/,
32550            gclid = location.search.match(gclidRegex),
32551            gclid2 = location.pathname.match(gclidRegex);
32552        if (gclid && gclid.length && gclid[1]) {
32553            map["gclid"] = gclid[1];
32554        }
32555        if (gclid2 && gclid2.length && gclid2[1]) {
32556            map["gclid"] = gclid2[1];
32557        }
32558        SHC.exports = SHC.exports || {};
32559        SHC.exports.savedParams = map;
32560    },
32561
32562    /**
32563     * Deactivate all of the dropdowns
32564     */
32565    deactivateAllDropdowns: function() {
32566        this.deactivateDropdown(this.tabbarDropdown);
32567        this.deactivateDropdown(this.filterDropdown);
32568        this.deactivateDropdown(this.predictDropdown);
32569    },
32570
32571    /**
32572     * Hide all of the dropdowns
32573     */
32574    hideAllDropdowns: function() {
32575        this.hideDropdown(this.$dropdownFilterDiv);
32576        this.hideDropdown(this.$dropdownPredictDiv);
32577        this.hideDropdown(this.$dropdownTabbarDiv);
32578
32579    },
32580
32581    /**
32582     * Will show which dropdowns need to be shown on page load
32583     */
32584    initialDropdownShow: function(){
32585        this.hideAllDropdowns();
32586        // conditionals to show correct dropdowns
32587        if (this.template === this.searchResultsTemplate || this.template === "/apps/shc/templates/clinicaltrials_search"
32588                || this.template === "/apps/shc/templates/newsroomlanding" || this.template === "/apps/shc/templates/newsroomlisting"
32589                || this.template === '/conf/shc/settings/wcm/templates/stanfordlab-site-search-results') {
32590            this.switchToInput();
32591            if (typeof GLOBAL_DIRECTORY_OBJECT === 'undefined' || GLOBAL_DIRECTORY_OBJECT === null || GLOBAL_DIRECTORY_OBJECT === "") {
32592                this.showDropdown(this.$dropdownTabbarDiv);
32593            }
32594        }
32595    },
32596
32597    /**
32598     * Returns true if the dropdown div is showing
32599     */
32600    isDropdownShowing: function($dropdown) {
32601        return $dropdown.hasClass("dropdownShow");
32602    },
32603
32604    /**
32605     * Activate a dropdown by swapping the visibility class to 'show', and have the dropdown run it's activate()
32606     */
32607    activateDropdown: function(dropdown) {
32608        dropdown.activate(this.searchAndPromoteDoer, this.searchAndPromoteJson);
32609    },
32610
32611    /**
32612     * Deactivate a dropdown by swapping the visibility class to 'hide', and have the dropdown run it's deactivate()
32613     */
32614    deactivateDropdown: function(dropdown){
32615        if(dropdown) { //for some reason this is undefined in IE8, adding check
32616           dropdown.deactivate();
32617        }
32618    },
32619
32620    showDropdown: function($dropdown) {
32621        $dropdown.removeClass('dropdownHide');
32622        $dropdown.addClass('dropdownShow');
32623    },
32624
32625    hideDropdown: function($dropdown) {
32626        $dropdown.removeClass('dropdownShow');
32627        $dropdown.addClass('dropdownHide');
32628    },
32629
32630    gotNewJsonFromTabbar: function(doer, data) {
32631        // pass doer and data to filters dropdown for it to process and interpret
32632        this.searchAndPromoteDoer = doer;
32633        this.searchAndPromoteJson = data;
32634        this.activateDropdown(this.filterDropdown, this.$dropdownFilterDiv);
32635    },
32636
32637    /**
32638     *  Handles the search bar focus and dropdown activation/show when in focus
32639     */
32640    initialFocus: function() {
32641        // need to know for orientation change workaround
32642        this.focused = true;
32643        var that = this;
32644        this.deactivateAllDropdowns();
32645
32646        // show the dropdowns we need
32647        if (this.template === this.searchResultsTemplate) {
32648            if (GLOBAL_DIRECTORY_OBJECT && GLOBAL_DIRECTORY_OBJECT !== undefined && GLOBAL_DIRECTORY_OBJECT !== "") {
32649                // does nothing right now
32650            } else {
32651                // show and activate tabbar
32652                this.activateDropdown(this.tabbarDropdown);
32653                this.showDropdown(this.$dropdownTabbarDiv);
32654            }
32655        }
32656
32657        // do animations
32658        this.animateIn();
32659        this.resizeEvent = false;
32660    },
32661
32662    animateIn: function() {
32663        var that = this;
32664
32665        this.$searchContainer.addClass("small-lock-top");
32666        // Set to make the animation work on animateOut for the homepage:w
32667
32668        this.handleClear();
32669
32670        // hide control dropdown if it exists and is open
32671        if (that.controlToggle.length !== 0 && !that.controlDropdownDesktop.is(':visible')) {
32672            if (that.userClick || !that.resizeEvent) {
32673                that.toggleControlDropdown(that, 'close');
32674            }
32675        }
32676
32677        // show x
32678        this.$clearButton.fadeIn(this.transitionDuration);
32679
32680        // show click screen
32681        this.showClickScreen();
32682        that.$searchRow.removeClass('hidden');
32683        that.$searchRow.addClass('open');
32684        that.$pageTitle.css("display", "none");
32685    },
32686
32687    /**
32688     * Handles the search bar focus and dropdown activation/show when out of focus
32689     */
32690    outFocus: function() {
32691        this.focused = false;
32692        this.$searchInput.blur();
32693        this.$predictiveDiv.empty();
32694        this.restoreDirectoryState();
32695        // there is no h1 on search pages
32696        if (this.template !== this.searchResultsTemplate && this.template != '/conf/shc/settings/wcm/templates/stanfordlab-site-search-results') {
32697            this.switchToH1();
32698        }
32699
32700        // reset words
32701        this.clearShadowText();
32702        this.clearSearchInput();
32703
32704        // activate and show what dropdowns we need
32705        this.initialDropdownActivation(true);
32706        this.initialDropdownShow();
32707
32708        // do animations
32709        this.animateOut();
32710        this.dropdownUtil.removePulldownScrollHandler();
32711    },
32712
32713    /**
32714     * "Global Searches" are started by clicking the magnifying glass in the top right corner.
32715     *      If a global search has been started (especially in the case of being on a directory page), we need to
32716     *      set things back directory specific stuff.
32717     */
32718    globalSearchOut: function () {
32719        if (this.globalSearchStarted) {
32720            this.globalSearchStarted = false;
32721            this.$searchInput.attr("placeholder", this.placeHolderText);
32722            this.controlTitle.text(this.controlOriginalActive);
32723            this.controlDropdownItems.parent().find('.active').removeClass('active');
32724            var classToFind = '',
32725                originalDirectoryString = this.controlOriginalActive.toLowerCase();
32726
32727            if (originalDirectoryString.indexOf('doctors') > -1) {
32728                classToFind = 'doctors';
32729            } else if (originalDirectoryString.indexOf('clinics') > -1) {
32730                classToFind = 'clinics';
32731            } else if (originalDirectoryString.indexOf('conditions') > -1) {
32732                classToFind = 'conditions';
32733            } else if (originalDirectoryString.indexOf('trials') > -1) {
32734                classToFind = 'trials';
32735            } else if (originalDirectoryString.indexOf('newsroom') > -1) {
32736                classToFind = 'newsroom';
32737            } else if (originalDirectoryString.indexOf('stories') > -1) {
32738                classToFind = 'stories';
32739            } else if (originalDirectoryString.indexOf('events') > -1) {
32740                classToFind = 'events';
32741            } else if (originalDirectoryString.indexOf('all') > -1) {
32742                classToFind = 'all';
32743            } else {
32744                classToFind = null;
32745            }
32746            if (classToFind !== null) {
32747                classToFind = '.' + classToFind;
32748                this.controlDropdownItems.parent().find(classToFind).addClass('active');
32749            }
32750            $(window).trigger("updateSearchDirectorySelector");
32751        }
32752    },
32753
32754    animateOut: function() {
32755        // lose click screen
32756        this.hideClickScreen();
32757        this.globalSearchOut();
32758
32759        this.$searchRow.removeClass('open');
32760        if (this.isSupportGroupsPage || this.isClassesPage) {
32761            this.$searchRow.addClass('hidden');
32762        }
32763        this.$pageTitle.css("display", "block");
32764        this.$searchContainer.removeClass("small-lock-top");
32765        // Animate the searchbar to its original width, only on the homepage
32766        if (SHC.ui.screenMode !== 'small') {
32767
32768            // if this is iOS and we are on a larger screen
32769            // then scroll to the top of the page on focus out
32770            if(SHC.util.isIOS()) {
32771                this.$body.animate({scrollTop: 0}, 750);
32772            }
32773        }
32774    },
32775
32776    /**
32777     * Hide the search bar and show the H1 header.
32778     */
32779    switchToH1: function() {
32780        if (this.dropdownUtil.isLowerLevelPage()) {
32781            this.$searchInpagenav.css("height", "");
32782            this.$searchRow.addClass("hidden");
32783            this.$pageTitle.removeClass("hidden");
32784        }
32785
32786        this.$searchInputs.hide();
32787        this.$searchRow.removeClass('active-input');
32788        this.$searchTitle.show();
32789    },
32790
32791    /**
32792     * Hide the H1 header and show the search bar
32793     */
32794    switchToInput: function() {
32795        // set the height to what it is without the search active so that
32796        // when the search bar becomes active things stay positioned the same
32797        this.$searchInpagenav.css("height", this.$searchInpagenav.height());
32798        this.$searchInpagenavWrapper.css("height", this.$searchInpagenav.height());
32799
32800        if (this.dropdownUtil.isLowerLevelPage()) {
32801            this.$pageTitle.addClass("hidden");
32802            this.$searchRow.removeClass("hidden");
32803        }
32804
32805        this.$searchTitle.hide();
32806        this.$searchRow.addClass('active-input');
32807        this.$searchInputs.show();
32808    },
32809
32810    /**
32811     * Handles the search bar focus and dropdown activation/show the text in the search bar is cleared
32812     */
32813    handleClear: function() {
32814        // show the dropdowns we need
32815        this.deactivateAllDropdowns();
32816
32817        // set the input to empty if it needs to be
32818        if (this.$searchInput.val() !== '') {
32819            for (var text in this.headerTexts) {
32820                if (this.$searchInput.val() === this.headerTexts[text]) {
32821                    this.$searchInput.val('');
32822                }
32823            }
32824        }
32825        this.dropdownUtil.removePulldownScrollHandler();
32826        this.dropdownUtil.checkPulldownHeight();
32827    },
32828    /**
32829     * Handlers and binding of events on and in the search input
32830     */
32831    setupEventHandlers: function () {
32832        var that = this;
32833
32834        var initialFocusWrapper = function(e) {
32835            if(!that.$searchRow.hasClass("open") || that.isControlDropdownOpen()) {
32836                e.preventDefault();
32837                that.$magnifyingGlass.removeClass('hovering');
32838                var showSearch = function() {
32839                    that.switchToInput();
32840                    that.$searchInput.select();
32841
32842                    // so we don't trigger initialFocus on a idevice's weird half-focus/active state when you hide the keyboard
32843                    if (!that.$clickScreen.is(':visible') || that.isControlDropdownOpen()) {
32844                        that.initialFocus();
32845                    }
32846                };
32847
32848                var callbackInvoked;
32849                if (!that.isStanfordlab) {
32850                  that.masthead.closeMenu();
32851                  callbackInvoked = that.masthead.closeOpenDrawers(showSearch);
32852                }
32853                if(!callbackInvoked) {
32854                    showSearch();
32855                }
32856
32857                that.$searchInput.off("keydown", tabKeydownHandler).on("keydown", tabKeydownHandler);
32858            }
32859        };
32860
32861        var tabKeydownHandler = function(event) {
32862            if ((event.key === "Tab" || event.keyCode === 9) && that.$searchInput.val().trim() === ""){
32863                that.outFocus();
32864            }
32865        };
32866
32867        var emergencyAlertIndex = function(removeClass, addClass) {
32868            var externalAlert = $('#external-outage-alert');
32869            if(externalAlert.length === 1){
32870                externalAlert.removeClass(removeClass).addClass(addClass);
32871            }
32872
32873            var emergencyAlert = $('#new-emergency-alert');
32874            if(emergencyAlert.length === 1){
32875                emergencyAlert.removeClass(removeClass).addClass(addClass);
32876            }
32877        };
32878
32879        // clicking the magnifying glass in the top right does a global search, so set all that stuff up
32880        var allSearchClick = function(e) {
32881            emergencyAlertIndex('adjusted-zindex', 'adjusted-zindex-min');
32882            initialFocusWrapper(e);
32883            that.globalSearchStarted = true;
32884            that.controlOriginalActive = that.controlTitle.text();
32885            that.controlTitle.text('all');
32886            that.removeDirectorySelector();
32887            that.$searchInput.attr('placeholder', that.headerTexts.fallback);
32888            that.controlDropdownItems.parent().find('.active').removeClass('active');
32889            that.controlDropdownItems.parent().find('.all').addClass('active');
32890        };
32891
32892        let ignoreNextKeyup = false;
32893        // on click
32894        this.$searchInputWrapper.on("click", initialFocusWrapper);
32895        this.$searchTitle.on("click", initialFocusWrapper);
32896        this.$searchTitle.on("keyup", function (e) {
32897            if (e.key === "Enter" || e.keycode === 13) {
32898                if (ignoreNextKeyup) {
32899                    ignoreNextKeyup = false;
32900                    e.preventDefault();
32901                } else {
32902                    initialFocusWrapper(e);
32903                }
32904            }
32905        });
32906        this.$searchMagnifyingGlass.on("click", initialFocusWrapper);
32907
32908        // don't need this for shca
32909        if (HOME_PAGE_PATH.indexOf('content/shca') <= -1) {
32910            this.$magnifyingGlass.on("click", allSearchClick).on("keydown", function(event){
32911                if (event.keyCode === 13) {
32912                    allSearchClick(event);
32913                    ignoreNextKeyup = true;
32914                }
32915            });
32916        }
32917
32918        this.$skipToMainLink.on("keydown", (e) => {
32919            if(e.key === "Enter" || e.keyCode === 13) {
32920                ignoreNextKeyup = true;
32921            }
32922        });
32923
32924        // goes to search.html/term or the selected suggestion
32925        // TODO probably want to trigger binder.startSearch when we are on the search (non-directory) already
32926        var doSubmit = function () {
32927            var term = that.$searchInput.val();
32928            var activeSuggestion = that.$pulldownDiv.find(".link-item a.active");
32929            if (activeSuggestion && activeSuggestion.length) {
32930                window.location = activeSuggestion.attr("href");
32931            }
32932            var currentDirectory = SHC.ui.Search.DirectoryUtil.getCurrentDirectory();
32933
32934            // since they are clicked into the global search, we want to do the all directory search
32935            if (that.globalSearchStarted) {
32936                currentDirectory = 'all';
32937            }
32938
32939            //check if in a passthrough
32940            var searchChunk = window.location.pathname.match(/\.html\/(.*)/);
32941            var passthrough;
32942            if (searchChunk && searchChunk[1] && (searchChunk[1].indexOf('%7C') > -1 || searchChunk[1].indexOf('|') > -1)) {
32943                passthrough = decodeURIComponent(searchChunk[1]);
32944            }
32945
32946            var encodedTerm = '';
32947            if (passthrough && that.getIsPassthroughUrl()) {
32948                var passthroughSplit = passthrough.split("|");
32949                if (term && term.length > 0) {
32950                    if (passthroughSplit.length === 2) {
32951                        passthroughSplit.push('');
32952                    }
32953                    if (passthroughSplit.length === 3) {
32954                        passthroughSplit.push(encodeURIComponent(term));
32955                    } else if (passthroughSplit.length === 4) {
32956                        passthroughSplit[3] = encodeURIComponent(term);
32957                    }
32958                } else {
32959                    if (passthroughSplit.length === 4) {
32960                        passthroughSplit.length = 3;
32961                    }
32962                    if (passthroughSplit.length === 3 && passthroughSplit[2] === '') {
32963                        passthroughSplit.length = 2;
32964                    }
32965                }
32966                encodedTerm = '/' + passthroughSplit.join("|");
32967            } else {
32968                if(term && term.length > 0){
32969                    encodedTerm = '/' + encodeURIComponent(term);
32970                }
32971            }
32972
32973            var filterParams = '';
32974                        if ( $('.filter-toggle-wrapper').length === 1 &&
32975                             (currentDirectory === 'clinics' || currentDirectory === 'doctors' || currentDirectory === 'conditions' || currentDirectory === 'trials') ){
32976                            var toggleSelectedIs  = $('.filter-toggle-wrapper .active').text();
32977                            if (currentDirectory === 'clinics'){
32978                                if (toggleSelectedIs === 'Primary Care'){
32979                                    filterParams = '#&x1=sp_prim_care_clinic&q1=true&tg=save';
32980                                } else if(toggleSelectedIs === 'Other Services'){
32981                                    filterParams = '#&x1=sp_other_service&q1=true&tg=save';
32982                                } else if(toggleSelectedIs === 'Specialty Care' && window.location.href.indexOf('&x1=sp_spec_care_clinic') > 0){
32983                                    filterParams = '#&x1=sp_spec_care_clinic&q1=true&tg=save';
32984                                }
32985                            } else if (currentDirectory === 'doctors'){
32986                                if(toggleSelectedIs === 'Primary Care'){
32987                                    filterParams = '#&x1=sp_prim_care_phy&q1=true&tg=save';
32988                                } else if(toggleSelectedIs === 'Specialists' && window.location.href.indexOf('&x1=sp_spec_care_phy') > 0){
32989                                    filterParams = '#&x1=sp_spec_care_phy&q1=true&tg=save';
32990                                }
32991                            }else if (currentDirectory === 'conditions'){
32992                                if(toggleSelectedIs === 'Conditions'){
32993                                    filterParams = '#&x1=sp_type&q1=condition&tg=save';
32994                                } else if(toggleSelectedIs === 'Treatments'){
32995                                    filterParams = '#&x1=sp_type&q1=treatment&tg=save';
32996                                }
32997                            } else if (currentDirectory === 'trials') {
32998                                //TODO filter locks
32999                            }
33000                        }
33001
33002                        // http://stackoverflow.com/questions/2405117/difference-between-window-location-href-window-location-href-and-window-location
33003                        // if there is a hash in the url already and the search term is the same as the results currently displayed
33004                        // using window.location in the switch case will not reload the page. Need to change the history state and
33005                        // force the reload
33006                        if ( window.location.href.indexOf('#') > window.location.href.indexOf('.html') &&
33007                             (currentDirectory === 'doctors' || currentDirectory === 'clinics' || currentDirectory === 'conditions' || currentDirectory === 'trials')){
33008                            var cleaningUrl = window.location.href.split('?wcmmode=disabled').join('');
33009                            cleaningUrl = cleaningUrl.split('.html');
33010                            cleaningUrl = cleaningUrl[1].split('#');
33011                            var termFromUrl = decodeURIComponent(cleaningUrl[0].split('/').join(''));
33012
33013                            if(term === termFromUrl ){
33014                                var reloadUrl = window.location.href;
33015                                if (reloadUrl.indexOf('&tg=save') === -1){
33016                                    reloadUrl += '&tg=save';
33017                                }
33018                                window.history.replaceState({"fromStartSearch": true}, '', reloadUrl);
33019                                window.location.reload();
33020                            }
33021                        }
33022
33023            switch(currentDirectory) {
33024                case "doctors":
33025                    that.setShcaSearchHashCookie(SHC.ui.Search.DirectoryUtil.doctorsDirectoryUrl + encodedTerm + filterParams);
33026                    window.location = SHC.ui.Search.DirectoryUtil.doctorsDirectoryUrl + encodedTerm + filterParams;
33027                    break;
33028                case "clinics":
33029                    window.location = SHC.ui.Search.DirectoryUtil.clinicsDirectoryUrl + encodedTerm + filterParams;
33030                    break;
33031                case "trials":
33032                    window.location = SHC.ui.Search.DirectoryUtil.trialsDirectoryUrl + encodedTerm + filterParams;
33033                    break;
33034                case "conditions":
33035                    window.location = SHC.ui.Search.DirectoryUtil.conditionsDirectoryUrl + encodedTerm + filterParams;
33036                    break;
33037                case "trials":
33038                    window.location = SHC.ui.Search.DirectoryUtil.trialsDirectoryUrl + encodedTerm + filterParams;
33039                    break;
33040                case "newsroom":
33041                    window.location = SHC.ui.Search.DirectoryUtil.newsroomDirectoryUrl + encodedTerm + filterParams;
33042                    break;
33043                case "all":
33044                    var searchResultsUrl = '';
33045                    if (that.isValleycare) {
33046                      searchResultsUrl = SHC.ui.Search.DirectoryUtil.valleyCareResultsUrl
33047                    } else if (that.isStanfordlab) {
33048                      searchResultsUrl = SHC.ui.Search.DirectoryUtil.stanfordLabResultsUrl
33049                    } else {
33050                      searchResultsUrl = SHC.ui.Search.DirectoryUtil.searchResultsUrl;
33051                    }
33052                    window.location = searchResultsUrl + encodedTerm;
33053                    break;
33054                case "clinical trials":
33055                    window.location = SHC.ui.Search.DirectoryUtil.trialsDirectoryUrl + encodedTerm;
33056                    break;
33057                case "newsroom": case "newsroomlanding":
33058                    window.location = SHC.ui.Search.DirectoryUtil.newsroomDirectoryUrl + encodedTerm;
33059                    break;
33060            }
33061        };
33062        // key events while you are in the search input
33063        var keyupHandler = function (evt) {
33064            switch (evt.keyCode) {
33065                // keyCode9 is "Return" in FireFox on mobile, and "Tab" in every other browser
33066                case 9:
33067                    if (that.isFireFoxMobile){
33068                        doSubmit();
33069                    }
33070                    else if (that.$searchInput.val().trim() === "") {
33071                        that.outFocus();
33072                    }
33073                    break;
33074                // return
33075                case 13:
33076                    if(SHC.ui.Search.DirectoryUtil.isDoctorDirectoryPage() || SHC.ui.Search.DirectoryUtil.isClinicDirectoryPage()) {
33077                        SHC.util.setCookie('activeView', SHC.ui.Search.DirectoryUtil.getSelectedView(), 1, '/');
33078                    }
33079                    doSubmit();
33080                    break;
33081                // esc
33082                case 27:
33083                    if (that.isDropdownShowing(that.$predictiveDiv)) {
33084                        that.$searchInput.val("");
33085                    }
33086                    that.outFocus();
33087                    break;
33088                // any other key ...
33089                default:
33090                    //check if the search bar is empty
33091                    if (that.$searchInput.val() === "") {
33092                        that.$searchInput.attr('placeholder', that.determinePlaceholder());
33093                    } else {
33094                        // do predict if it isn't already showing
33095                        if (!that.isDropdownShowing(that.$predictiveDiv)) {
33096                            that.deactivateAllDropdowns();
33097                            that.hideAllDropdowns();
33098                            that.activateDropdown(that.predictDropdown);
33099                            that.showDropdown(that.$dropdownPredictDiv);
33100                            that.dropdownUtil.removePulldownScrollHandler();
33101                            that.dropdownUtil.checkPulldownHeight();
33102                        }
33103                    }
33104                    break;
33105            }
33106        };
33107
33108        //this is to ignore the tab up event when focused in via keyboard
33109        let ignoreNextTabUp = false;
33110
33111        this.$searchForm.on('focusin', function () {
33112            ignoreNextTabUp = true;
33113        });
33114
33115        this.$searchInput.on("keyup", function (event) {
33116            if (ignoreNextKeyup) {
33117                ignoreNextKeyup = false;
33118                event.preventDefault();
33119            }
33120            else if (ignoreNextTabUp) {
33121                ignoreNextTabUp = false;
33122            }
33123            else {
33124                keyupHandler(event);
33125            }
33126        });
33127
33128        $(document).mousedown(function (e) {
33129            if (!that.$pulldownDiv.is(e.target) // if the target of the click isn't the container...
33130                && that.$searchContainer.has(e.target).length === 0) { // ... nor a descendant of the container
33131                if(that.$searchRow.hasClass("open")) { // check if the searchbar is open
33132                    emergencyAlertIndex('adjusted-zindex-min', 'adjusted-zindex');
33133                    that.outFocus();
33134                }
33135
33136                if(that.isControlDropdownOpen()) { // check if the control dropdown is open
33137                    that.toggleControlDropdown(that);
33138                }
33139            }
33140        });
33141
33142        this.$window.on("resizeEnd", function() {
33143            // adjust the screen when transitioning to "small" from a larger window
33144            if(that.$searchRow.hasClass("open") && SHC.ui.screenMode === 'small') {
33145                that.dropdownUtil.removeScrollyClasses();
33146                that.resizeEvent = true;
33147                that.initialFocus();
33148            }
33149        });
33150
33151        // onmousedown is needed instead of onclick for IE9, known IE9 issue (webbugtrack - bug 487)
33152        this.$clearButton.find('a').on("mousedown", function(e) {
33153            //only fire if left mouse button
33154            if (e.which === 1) {
33155                e.preventDefault();
33156                e.stopImmediatePropagation();
33157                that.handleClear();
33158                that.$searchInput.val("");
33159                if(!that.$searchRow.hasClass("open")) {
33160                    initialFocusWrapper(e);
33161                }
33162            }
33163        }).on("click", function(e) {
33164            e.preventDefault();
33165            that.$searchInput.val("");
33166        });
33167
33168        // a focused input and orientation change will destroy the page on iOS safari
33169        if (window.addEventListener) { //check so we don't break IE8
33170            window.addEventListener("orientationchange", function () {
33171                if (that.focused !== null) {
33172                    window.scroll(0, 0);
33173                }
33174                setTimeout(function () {
33175                    window.scroll(0, that.$searchInput.offset().top);
33176                }, 100);
33177            });
33178        } //IE8 uses attachEvent, but since we should never see an orientation change on IE8 I'm leaving it out
33179        //perform search when clicking on magnifying glass icon
33180        $('span.searchbar-magnifying-glass').on('click',function(){
33181            if(SHC.ui.Search.DirectoryUtil.isDoctorDirectoryPage() || SHC.ui.Search.DirectoryUtil.isClinicDirectoryPage()) {
33182                SHC.util.setCookie('activeView', SHC.ui.Search.DirectoryUtil.getSelectedView(), 1, '/');
33183            }
33184            doSubmit();
33185        });
33186    },
33187    /**
33188     * clears shadow text in search bar
33189     */
33190    clearShadowText: function() {
33191        this.predictionInput.val("");
33192    },
33193
33194    clearSearchInput: function() {
33195        this.$searchInput.val("");
33196    },
33197
33198    hideClickScreen: function () {
33199        // restore the original z-index
33200        this.$searchRow.css("z-index", "");
33201        this.$clickScreen.hide();
33202        if (this.clickScreenRestoreFilters) {
33203            jQuery(".filters-toggle").click();
33204            this.clickScreenRestoreFilters = false;
33205        }
33206    },
33207
33208    showClickScreen: function () {
33209        // put the search row on top
33210        this.$searchRow.css("z-index", "3000");
33211        // hide the filters dropdown on clicking into the search bar to prevent issues with scrolling
33212        var $filtersContent = jQuery(".filters-toggle");
33213        if ($filtersContent.hasClass('active')){
33214            jQuery(".filters-toggle").click();
33215            this.clickScreenRestoreFilters = true;
33216        }
33217
33218        this.$clickScreen.show();
33219
33220        if (this.$inPageNav.length > 0 && this.$inPageNav.is(":visible")) {
33221            this.$clickScreen.appendTo(this.$inPageNav);
33222        } else {
33223            this.$clickScreen.appendTo(document.body);
33224        }
33225
33226        this.$clickScreen.transition({
33227            "opacity": 0.85,
33228            "duration": this.transitionDuration
33229        }, 'ease');
33230
33231        this.$clickScreen.on("click", function (e) {
33232            e.preventDefault();
33233            e.stopImmediatePropagation();
33234        });
33235        this.$filterArea.hide();
33236
33237    },
33238
33239    determineNoTouchClassForHover: function () {
33240        if (!("ontouchstart" in document.documentElement)) {
33241            jQuery('#search-row').addClass('no-touch');
33242        }
33243    },
33244    toggleControlDropdown: function(context, direction) {
33245        var currentDropdown,
33246            mode,
33247            anim = {duration:'fast', easing:'swing'};
33248
33249        if (context.controlToggle.hasClass('desktop')) {
33250            currentDropdown = context.controlDropdownDesktop;
33251            mode = 'desktop';
33252        } else if (context.controlToggle.hasClass('mobile')) {
33253            currentDropdown = context.controlDropdownMobile;
33254            mode = 'mobile';
33255        } else {
33256            console.log("Error: control toggle doesn't have a class indicating mode...");
33257        }
33258
33259        if (direction === 'close') {
33260            currentDropdown.css('min-height','');
33261            currentDropdown.slideUp(anim);
33262            if (!context.globalSearchStarted) {
33263                context.hideClickScreen();
33264            }
33265            context.controlArrow.removeClass('close-arrow').addClass('open-arrow');
33266        } else if (direction === 'open') {
33267            currentDropdown.slideDown(anim);
33268            context.showClickScreen();
33269            context.controlArrow.removeClass('open-arrow').addClass('close-arrow');
33270        } else {
33271            if (mode === 'desktop') {
33272                if (currentDropdown.css('display') === 'block') {
33273                    currentDropdown.css('min-height','');
33274                    currentDropdown.slideToggle(anim);
33275                } else {
33276                    currentDropdown.slideToggle('fast', 'swing', function(){
33277                        var minHeight = context.isValleycare ? '90px' : '213px';
33278                        currentDropdown.css('min-height', minHeight);
33279                    });
33280                }
33281            } else if (mode === 'mobile') {
33282                currentDropdown.slideToggle(anim);
33283            }
33284
33285            if (context.controlArrow.hasClass('close-arrow')) {
33286                context.controlArrow.removeClass('close-arrow').addClass('open-arrow');
33287                if (!context.globalSearchStarted) {
33288                    context.hideClickScreen();
33289                }
33290            } else {
33291                context.controlArrow.removeClass('open-arrow').addClass('close-arrow');
33292                context.showClickScreen();
33293            }
33294        }
33295        this.userClick = false;
33296    },
33297    toggleMoreDropdown: function(context, direction) {
33298        var anim = {duration:'fast', easing:'swing'};
33299        if (direction === 'close') {
33300            context.controlMoreSymbol.removeClass('open').addClass('closed');
33301            context.controlMoreContainer.slideUp(anim);
33302        } else if (direction === 'open') {
33303            context.controlMoreSymbol.removeClass('closed').addClass('open');
33304            context.controlMoreContainer.slideDown(anim);
33305        } else {
33306            context.controlMoreContainer.slideToggle(anim);
33307            if (context.controlMoreSymbol.hasClass('open')) {
33308                context.controlMoreSymbol.removeClass('open').addClass('closed');
33309            } else {
33310                context.controlMoreSymbol.removeClass('closed').addClass('open');
33311            }
33312        }
33313    },
33314    isControlDropdownOpen: function() {
33315        if($('#control-dropdown-desktop').css('display') === 'block' || $('#control-dropdown-mobile').css('display') === 'block') {
33316            return true;
33317        }
33318
33319        return false;
33320    },
33321    resizeControlDropdowns: function() {
33322        if (SHC.ui.screenMode === 'small') {
33323            this.controlDropdownDesktop.hide();
33324            this.controlToggle.removeClass('desktop').addClass('mobile');
33325        } else {
33326            this.controlDropdownMobile.hide();
33327            this.controlToggle.removeClass('mobile').addClass('desktop');
33328        }
33329    },
33330    attachControlEvents: function() {
33331        var that = this;
33332        // ensure presence of all neccessary elements on page
33333        if (!this.controlToggle.length
33334            || !this.controlDropdownDesktop.length
33335            || !this.controlArrow.length
33336            || !this.controlDropdownItems.length
33337            || ((!this.controlMoreToggle.length || !this.controlMoreContainer.length) && !this.isValleycare)) {
33338            console.log('Failure to select an element required for the search control...');
33339            return;
33340        }
33341
33342        // call once to set dropdowns on load
33343        that.resizeControlDropdowns();
33344
33345        // bind dropdown resize to window resize
33346        this.$window.bind('resizeEnd',function() {
33347            that.resizeControlDropdowns();
33348        });
33349
33350        // handle control toggle
33351        this.controlToggle.on('click', function(){
33352            that.predictDropdown.emptyPulldown();
33353            that.userClick = true;
33354            that.toggleControlDropdown(that);
33355        });
33356
33357        // handle more toggle
33358        this.controlMoreToggle.on('click', function() {
33359           that.toggleMoreDropdown(that);
33360        });
33361        // handle control change
33362        this.controlDropdownItems.each(function() {
33363            var dropdownEle = jQuery(this);
33364            dropdownEle.on('click', function() {
33365                if (!jQuery(this).hasClass('active')) {
33366                    that.controlDropdownItems.each(function() {
33367                        jQuery(this).removeClass('active');
33368                    });
33369                    dropdownEle.addClass('active');
33370                }
33371                that.toggleControlDropdown(that, 'close');
33372
33373                var desiredDirectory = dropdownEle.text().toLowerCase();
33374                var currentDirectory = SHC.ui.Search.DirectoryUtil.getCurrentDirectory();
33375
33376                var searchTerm = that.$searchInput.val();
33377                var alternateSearchTerm = jQuery('.search-results-total .case-bold.result-small-font').text();
33378                if (alternateSearchTerm !== null && alternateSearchTerm !== '') {
33379                    if (alternateSearchTerm.toLowerCase() !== searchTerm.toLowerCase()) {
33380                        searchTerm = alternateSearchTerm;
33381                    }
33382                }
33383                var encodedSearchTerm = '';
33384                if(searchTerm && searchTerm.length > 0){
33385                    encodedSearchTerm = '/' + encodeURIComponent(searchTerm);
33386                }
33387
33388                if(desiredDirectory.indexOf(currentDirectory) === -1) {
33389                    var pred = window.location.search.indexOf("src=pred") > 0 ? '?src=pred' : '';
33390                    switch(desiredDirectory) {
33391                        case "doctors & providers":
33392                            if (that.isValleycare) {
33393                                window.location = SHC.ui.Search.DirectoryUtil.valleyCareDirectory + encodedSearchTerm + '#x1=sp_spec_care_phy&q1=true&page=1';
33394                            } else {
33395                                window.location = SHC.ui.Search.DirectoryUtil.guidedDirectoryURL + encodedSearchTerm + "#x1=sp_spec_care_phy&q1=true&page=1";
33396                            }
33397                            break;
33398                        case "clinics & locations":
33399                            window.location = SHC.ui.Search.DirectoryUtil.guidedDirectoryURL + encodedSearchTerm + "#x1=sp_spec_care_clinic&q1=true&page=1";
33400                            break;
33401                        case "clinical trials":
33402                            window.location = SHC.ui.Search.DirectoryUtil.trialsDirectoryUrl + encodedSearchTerm + pred;
33403                            break;
33404                        case "newsroom":
33405                            window.location = SHC.ui.Search.DirectoryUtil.newsroomDirectoryUrl + encodedSearchTerm + pred;
33406                            break;
33407                        case "conditions & treatments":
33408                            window.location = SHC.ui.Search.DirectoryUtil.guidedDirectoryURL + encodedSearchTerm + "#x1=sp_type&q1=%20&page=1";
33409                            break;
33410                        case "all stanford health care":
33411                            window.location = SHC.ui.Search.DirectoryUtil.searchResultsUrl + encodedSearchTerm + '?doer=organic' + pred.replace('?','&');
33412                            break;
33413                        case "stories":
33414                            window.location = SHC.ui.Search.DirectoryUtil.searchResultsUrl + encodedSearchTerm + '?doer=organic_stories' + pred.replace('?','&');
33415                            break;
33416                        case "events":
33417                            var resultsUrl = SHC.ui.Search.DirectoryUtil.searchResultsUrl;
33418                            var doer = 'organic_events';
33419                            if (that.isValleycare) {
33420                                resultsUrl = SHC.ui.Search.DirectoryUtil.valleyCareResultsUrl;
33421                                doer = 'vc_events';
33422                            }
33423                            window.location = resultsUrl + encodedSearchTerm + '?doer=' + doer + pred.replace('?','&');
33424                            break;
33425                    }
33426                }
33427            });
33428        });
33429    },
33430    determinePlaceholder:function() {
33431        if (this.isStanfordlab) {
33432            return this.defaultSearchText[7];
33433        }
33434        var searchDropdown = $('div#toggle-title').text().toLowerCase();
33435        switch (searchDropdown) {
33436            case 'doctors':
33437                return this.defaultSearchText[0];
33438            case 'clinics & locations':
33439                return this.defaultSearchText[1];
33440            case 'trials':
33441                return this.defaultSearchText[4];
33442            case 'conditions & treatments':
33443                return this.defaultSearchText[2];
33444            case 'clinical trials':
33445                return this.defaultSearchText[3];
33446            case 'newsroom':
33447                return this.defaultSearchText[5];
33448            case 'all':
33449                var index = 4;
33450                if (this.isValleycare) {
33451                    index = 6;
33452                } else if (this.isStanfordlab) {
33453                    index = 7;
33454                }
33455                return this.defaultSearchText[index];
33456            default:
33457                return this.defaultSearchText[3];
33458        }
33459    },
33460    removeDirectorySelector: function() {
33461        if(SHC.ui.Search.DirectoryUtil.isDoctorDirectoryPage()) {
33462            history.replaceState({}, 'all', window.location.pathname.replace("doctors.", ""));
33463        }
33464        else if(SHC.ui.Search.DirectoryUtil.isClinicDirectoryPage()) {
33465            history.replaceState({}, 'all', window.location.pathname.replace("clinics.", ""));
33466        }
33467        else if(SHC.ui.Search.DirectoryUtil.isTrialDirectoryPage()) {
33468            history.replaceState({}, 'all', window.location.pathname.replace("trials.", ""));
33469        }
33470        else if(SHC.ui.Search.DirectoryUtil.isNewsroomDirectoryPage()) {
33471            history.replaceState({}, 'all', window.location.pathname.replace("newsroom.", ""));
33472        }
33473        else if(SHC.ui.Search.DirectoryUtil.isConditionDirectoryPage()) {
33474            history.replaceState({}, 'all', window.location.pathname.replace("conditions.", ""));
33475        }
33476        else if(SHC.ui.Search.DirectoryUtil.isTrialsDirectoryPage()) {
33477            history.replaceState({}, 'all', window.location.pathname.replace("trials.", ""));
33478        }
33479        //Predict.js will listen for this to update predictive results
33480        $(window).trigger("updateSearchDirectorySelector");
33481    },
33482    restoreDirectoryState: function() {
33483        if(this.searchDirectory !== "all") {
33484            window.history.replaceState({}, "directory", window.location.pathname.replace("search-results.html", "search-results." + this.searchDirectory + ".html"));
33485        }
33486    },
33487    setShcaSearchHashCookie: function(url){
33488        if(GLOBAL_SEARCH_RESULTS_TEMPLATE.indexOf('shca') > -1 && $.browser.safari === true){
33489            var cookieExpire = new Date();
33490            cookieExpire.setSeconds(cookieExpire.getSeconds() + 5);
33491            //document.cookie = "shca-search-url-hash=" + url + ';path=/;domain=localhost;expires=' + cookieExpire.toUTCString() + ';';
33492            document.cookie = "shca-search-url-hash=" + url + ';path=/;domain=stanfordhealthcare.org;expires=' + cookieExpire.toUTCString() + ';';
33493            document.cookie = "shca-search-url-hash=" + url + ';path=/;domain=stanfordhealthcarealliance.org;expires=' + cookieExpire.toUTCString() + ';';
33494        }
33495    },
33496
33497    getIsPassthroughUrl : function(){
33498        var value = window.location.href;
33499        if(value.indexOf('&sp_trialLocks') > -1
33500            || value.indexOf('&sp_clinics') > -1
33501            || value.indexOf('&sp_clinicLocations') > -1
33502            || value.indexOf('&sp_conditions') > -1){
33503            return true;
33504        }else{
33505            return false;
33506        }
33507    },
33508
33509    getSearchTermFromPassthrough : function (){
33510        var url = window.location.pathname;
33511        var passthrough = url.split('.html/');
33512
33513        if(passthrough.length === 2){
33514            passthrough = passthrough[1];
33515            var regexPassthroughSwitch = new RegExp('&sp_[a-zA-Z]*%7C');
33516            var regexAdditionalParams = new RegExp('[&][_a-zA-Z]*', 'g');
33517            passthrough = passthrough.replace(regexPassthroughSwitch, '');
33518            passthrough = passthrough.replace(regexAdditionalParams, '');
33519
33520            if(passthrough.charAt(0) === '/'){
33521                //the search term is at the end of the string
33522                return passthrough.substring(passthrough.indexOf('.html%7C') + 8);
33523            }else{
33524                //search term at the beginning of the string
33525                return passthrough.substring(0, passthrough.indexOf('%7C/'));
33526            }
33527        }
33528        return '';
33529    },
33530});
33531
33532
33533/* Instantiate here. */
33534shcDOMContentLoaded(function () {
33535  if (jQuery('#search-inpagenav-wrapper').length) {
33536    var searchUI = new SHC.ui.Search.MegaSearch();
33537  }
33538});
33539
33540SHC.Namespace(SHC, "SHC.ui.Search.DistanceFilter");
33541SHC.ui.Search.DistanceFilter = new SHC.Class();
33542
33543/**
33544 * This class must be initialized AFTER filtersLoaded event has fired.
33545 *
33546 * This filter is not quite like the others. Instead of fattening Filter.js it's better for it to
33547 * have its own class.
33548 */
33549SHC.ui.Search.DistanceFilter.include({
33550    init: function () {
33551        this.zipCodeInput = $(".zip-code-input");
33552        this.distanceListOptions = $(".distance li");
33553        this.distanceErrorField = $(".distance-filter-error");
33554        this.distanceErrorContainer = $(".distance-filter-error-container");
33555        this.fromSpan = $(".from-container .from");
33556        this.selectedTitle = $('.distance .select-title');
33557        this.distanceSelectGroup = $('.select-group.distance');
33558        this.validZipCodeEntered = false;
33559        // default is any distance which translates to a 10,000 mi radius
33560        this.selectedDistance = Number(SHC.util.getNumericalDistanceVarsFromURL("sp_q_max")) || 10000;
33561        this.timerId = null;
33562        this.uspsUserId = "391AXIS43894";
33563        this.uspsZipCodeCheckerUrl = "https://secure.shippingapis.com/ShippingAPI.dll?API=CityStateLookup&XML=";
33564        this.zipInputFull = false;
33565
33566        this.populateVarsFromPreviousFilterAttempt();
33567        this.preventAlphaInputForZipCode();
33568        this.listenForZipCodeInput();
33569        this.bindListSelection();
33570        this.listenForTimerReset();
33571    },
33572    /**
33573     * Prevents the zip code text input from accepting alpha/special char input
33574     * by checking character code range.
33575     */
33576    preventAlphaInputForZipCode: function() {
33577        this.zipCodeInput.keypress(function(evt) {
33578            var charCode = (evt.which) ? evt.which : evt.keyCode;
33579
33580            if (charCode > 31 && (charCode < 48 || charCode >
33580 57) && charCode !== 8) {
33581                return false;
33582            }
33583
33584            return true;
33585        });
33586    },
33587    bindListSelection: function() {
33588        var that = this;
33589        this.distanceListOptions.click(function() {
33590            var $this = $(this);
33591
33592            that.distanceSelectGroup.removeClass("visible");
33593            that.selectedTitle.text($this.text());
33594            that.selectedDistance = $this.data("value");
33595            that.fromSpan.addClass("distance-selected");
33596
33597
33598            // if valid zip code already entered then we're good to go, otherwise start timer for zip code input
33599            if (that.validZipCodeEntered) {
33600                if(that.hasError()) {
33601                    if(SHC.ui.screenMode !== "small") {
33602                        that.showErrors();
33603                    }
33604                }
33605                else {
33606                    if(SHC.ui.screenMode === "small") {
33607                        that.triggerMobileFilterRequest();
33608                    }
33609                    else {
33610                        that.triggerFilterRequest();
33611                    }
33612                }
33613            }
33614            else if(that.zipCodeInput.val()) {
33615                // if they entered an invalid zip code show errors on select
33616                if(SHC.ui.screenMode !== "small") {
33617                    if (that.hasError()) {
33618                        that.showErrors();
33619                    }
33620                }
33621            }
33622            // no zip code and selected "any distance"
33623            else if(that.selectedDistance === 10000) {
33624                that.hideErrors();
33625                if(that.inEffect()) {
33626                    if(SHC.ui.screenMode === "small") {
33627                        that.triggerMobileFilterRequest();
33628                    }
33629                    else {
33630                        that.triggerFilterRequest();
33631                    }
33632                }
33633            }
33634            // no zip but not "any distance"
33635            else {
33636                if(SHC.ui.screenMode !== "small") {
33637                    that.timerId = setTimeout(function () {
33638                        if (that.hasError()) {
33639                            that.showErrors();
33640                        }
33641                    }, 1000);
33642                }
33643            }
33644
33645        });
33646    },
33647    listenForZipCodeInput: function() {
33648        var that = this;
33649        this.zipCodeInput.blur(function() {
33650            var $this = $(this);
33651            var inputLength = $this.val().length;
33652            if(inputLength < 5 && inputLength > 0) {
33653                that.validZipCodeEntered = false;
33654                if(SHC.ui.screenMode !== "small") {
33655                    that.showErrors();
33656                }
33657            }
33658            else if(that.selectedDistance !== 10000 && !$this.val()) {
33659                that.validZipCodeEntered = false;
33660                if(SHC.ui.screenMode !== "small") {
33661                    that.timerId = setTimeout(function () {
33662                        if(that.hasError()) {
33663                            that.showErrors();
33664                        }
33665                    }, 1000);
33666                }
33667            }
33668            else if(inputLength === 0) {
33669                that.validZipCodeEntered = false;
33670            }
33671        });
33672        this.zipCodeInput.keyup(function(evt) {
33673            var $this = $(this);
33674            var zipCodeValue = $this.val();
33675            var zipCodeValueLength = zipCodeValue.length;
33676            var charCode = (evt.which) ? evt.which : evt.keyCode;
33677
33678            // if showing error and they've started editing, hide the error
33679            if($this.hasClass("zip-code-error") && zipCodeValueLength < 5) {
33680                $this.removeClass("zip-code-error");
33681                that.hideErrors();
33682            }
33683            // upon entry of the 5th digit
33684            if(zipCodeValueLength === 5 && !that.zipInputFull) {
33685                $(".apply-filter").addClass("vis-on");
33686                //$(".reset-filter").addClass("vis-on"); // this is redundant, it gets set in filterTargetDivs()
33687                if(SHC.ui.screenMode === "small") {
33688                    that.makeUspsZipCodeRequest(zipCodeValue, false);
33689                }
33690                else {
33691                    that.makeUspsZipCodeRequest(zipCodeValue, true);
33692                    SHC.util.setCookie('activeView', SHC.ui.Search.DirectoryUtil.getSelectedView(), 1, '/');
33693                }
33694                that.zipInputFull = true;
33695            }
33696            // if they press enter without a full zip code in there, show error
33697            else if(zipCodeValueLength < 5 && charCode === 13) {
33698                that.validZipCodeEntered = false;
33699                if(SHC.ui.screenMode !== "small") {
33700                    that.showErrors();
33701                }
33702            }
33703            // if they've emptied zip code field, distance is "Any Distance", and filter is currently being applied
33704            else if(!zipCodeValue && that.selectedDistance === 10000 && that.inEffect()) {
33705                that.validZipCodeEntered = false;
33706                if(SHC.ui.screenMode === "small") {
33707                    that.triggerMobileFilterRequest();
33708                }
33709                else {
33710                    that.triggerFilterRequest();
33711                }
33712            }
33713        });
33714        this.zipCodeInput.keypress(function() {
33715            if($(this).val().length === 5) {
33716                that.zipInputFull = true;
33717            }
33718            else {
33719                that.zipInputFull = false;
33720            }
33721        });
33722    },
33723    listenForTimerReset: function() {
33724        var that = this;
33725        this.zipCodeInput.focus(function() {
33726           if(that.timerId) {
33727               clearTimeout(that.timerId);
33728           }
33729        });
33730    },
33731    makeUspsZipCodeRequest: function(zipCode, showErrors, fromApplyFilter) {
33732        var that = this;
33733        $.get(this.uspsZipCodeCheckerUrl + this.buildUspsXMLForZipCodeCheck(zipCode))
33734            .success(function(data) {
33735                that.parseUspsResponse(data);
33736                if(showErrors) {
33737                    if(that.hasError()) {
33738                        that.showErrors();
33739                    }
33740                    else {
33741                        if(SHC.ui.screenMode === "small") {
33742                            if(fromApplyFilter) {
33743                                that.triggerFilterRequest();
33744                            }
33745                            else {
33746                                that.triggerMobileFilterRequest();
33747                            }
33748                        }
33749                        else {
33750                            that.triggerFilterRequest();
33751                        }
33752                    }
33753                }
33754            });
33755    },
33756    showErrors: function() {
33757        if(!this.zipCodeInput.val()) {
33758            this.distanceErrorField.text("Please enter a zip code.");
33759            this.distanceErrorContainer.addClass('show-inline-error');
33760        }
33761        else if(!this.validZipCodeEntered) {
33762            this.distanceErrorField.text("Zip code not found. Please try again.");
33763            this.zipCodeInput.addClass("zip-code-error");
33764            this.distanceErrorContainer.addClass('show-inline-error');
33765        }
33766        $('.search-results #spinner-home').removeClass('mobile-filter-active');
33767        this.distanceErrorContainer.show();
33768
33769    },
33770    triggerFilterRequest: function() {
33771        $(window).trigger("distanceFilterRequest");
33772    },
33773    triggerMobileFilterRequest: function() {
33774        $(window).trigger("distanceFilterRequestMobile");
33775    },
33776    hideErrors: function() {
33777        this.distanceErrorField.text("");
33778        this.distanceErrorContainer.hide();
33779    },
33780    errorShowing: function() {
33781        return this.distanceErrorContainer.is(":visible");
33782    },
33783    hasZipCodeError: function() {
33784        return this.zipCodeInput.hasClass("zip-code-error");
33785    },
33786    buildUspsXMLForZipCodeCheck: function(zipCode) {
33787        return '<CityStateLookupRequest USERID="'+ this.uspsUserId +'"><ZipCode ID="0"><Zip5>'+ zipCode +'</Zip5></ZipCode></CityStateLookupRequest>';
33788    },
33789    /**
33790     * If the the doc contains an error tag, it's because a zip code doesn't exist,
33791     * otherwise it won't have an error tag.
33792     *
33793     * @param data - xml document response from USPS
33794     */
33795    parseUspsResponse: function(data) {
33796        this.validZipCodeEntered = data.getElementsByTagName('Error').length < 1;
33797    },
33798    getProximity: function() {
33799        return this.selectedDistance;
33800    },
33801    getZipCode: function() {
33802        return this.zipCodeInput.val();
33803    },
33804    populateVarsFromPreviousFilterAttempt: function() {
33805        var zipCode = this.zipCodeInput.val();
33806
33807        if(zipCode) {
33808            this.makeUspsZipCodeRequest(zipCode);
33809            $(".apply-filter").addClass("vis-on");
33810            $(".reset-filter").addClass("vis-on");
33811        }
33812    },
33813    hasError: function() {
33814        return !this.validZipCodeEntered;
33815    },
33816    isEmpty: function() {
33817        return !this.zipCodeInput.val() && this.selectedDistance === 10000;
33818    },
33819    rebindEvents: function() {
33820        this.zipCodeInputSelector = ".zip-code-input";
33821        this.distanceListOptionsSelector= ".distance li";
33822        this.zipCodeInput = $(this.zipCodeInputSelector);
33823        this.distanceListOptions = $(this.distanceListOptionsSelector);
33824        this.distanceErrorField = $(".distance-filter-error");
33825        this.distanceErrorContainer = $(".distance-filter-error-container");
33826        this.fromSpan = $(".from-container .from");
33827        this.selectedTitle = $('.distance .select-title');
33828        this.distanceSelectGroup = $('.select-group.distance');
33829
33830        this.preventAlphaInputForZipCode();
33831        this.listenForZipCodeInput();
33832        this.bindListSelection();
33833        this.listenForTimerReset();
33834        this.populateVarsFromPreviousFilterAttempt();
33835    },
33836    /**
33837     * Checks to see if the filter is currently being used by observing the url for relevant vars.
33838     *
33839     * sp_q_max and sp_q_location are guaranteed to be in the url after a successful clinic or doctor distance query.
33840     */
33841    inEffect: function() {
33842        return window.location.hash.indexOf("sp_q_max") > -1 && window.location.hash.indexOf("sp_q_location") > -1;
33843    }
33844});
33845SHC.Namespace(SHC, "SHC.ui.Search.SearchResultsMap");
33846SHC.ui.Search.SearchResultsMap = new SHC.Class();
33847SHC.ui.Search.SearchResultsMap.include({
33848     init: function(data) {
33849         var that = this;
33850         this.results = data.results.data;
33851         this.openInfoWindow = null;
33852         this.activeMarker = null;
33853         // use the common Doctor Profile photo instance and take advantage of Dispatcher caching.
33854         this.transformSuffix = "/jcr:content/renditions/original.transform/280x280-gray/image.jpg";
33855         this.defaultPhoto = "/etc/clientlibs/shc/main/img/shc-logo-profiledeck.jpg";
33856         // don't load the map if there are no results
33857         if(parseInt(data.general.total) > 0) {
33858             this.loadGoogleMaps(function() {
33859                 that.normalSize = {size: new google.maps.Size(26.162, 38.236), zIndex: 1};
33860                 that.bigSize = {size: new google.maps.Size(31.412, 45.912), zIndex: 10};
33861
33862                 if(that.results && $('.search-results-map').length > 0) {
33863                     // create Google Map object
33864                     var map = new google.maps.Map($('.search-results-map')[0], {
33865                         mapTypeControl: false,
33866                         zoomControl: false,
33867                         streetViewControl: false
33868                     });
33869
33870                     that.addCustomZoomControls(map);
33871
33872                     // check if we are on the clinic directory or the doctor directory
33873                     if(SHC.ui.Search.DirectoryUtil.isClinicDirectoryPage()) {
33874                         that.loadClinicDirectoryMap(map);
33875                     } else if(SHC.ui.Search.DirectoryUtil.isDoctorDirectoryPage()) {
33876                         that.loadDoctorDirectoryMap(map);
33877                     }
33878                 }
33879             });
33880         }
33881     },
33882     loadGoogleMaps: function(callback) {
33883         if (!(typeof window.google === 'object' && window.google.maps)) {
33884            var scriptLink = "//maps.googleapis.com/maps/api/js?libraries=weather,geometry&sensor=false&key=" + SHC.util.getGoogleAPIKey();
33885            $.getScript(scriptLink).success(function () {
33886                 $.getScript("/etc/clientlibs/shc/main/js/vendor/infobubble.min.js").success(function() {
33887                     $.getScript("/etc/clientlibs/shc/main/js/vendor/jquery.mCustomScrollbar.concat.min.js", callback);
33888                 });
33889             });
33890         } else {
33891             callback();
33892         }
33893     },
33894     addCustomZoomControls: function(map) {
33895         var zoomIn = document.createElement('span');
33896         zoomIn.className = 'gmap-zoom-in';
33897         zoomIn.style.cursor = 'pointer';
33898
33899         var zoomOut = document.createElement('span');
33900         zoomOut.className = 'gmap-zoom-out';
33901         zoomOut.style.cursor = 'pointer';
33902
33903         var zoomContainer = document.createElement('div');
33904         zoomContainer.appendChild(zoomIn);
33905         zoomContainer.appendChild(zoomOut);
33906
33907         google.maps.event.addDomListener(zoomIn, 'click', function() {
33908             map.setZoom(map.getZoom() + 1);
33909         });
33910
33911         google.maps.event.addDomListener(zoomOut, 'click', function() {
33912             map.setZoom(map.getZoom() - 1);
33913         });
33914
33915         map.controls[google.maps.ControlPosition.TOP_RIGHT].push(zoomContainer);
33916     },
33917     loadClinicDirectoryMap: function(map) {
33918         var mapIcon = 'https://stanfordhealthcare.org/etc/clientlibs/shc/main/img/SHC_Map_Pin_Active.png';
33919         var bounds = new google.maps.LatLngBounds();
33920         var latitude, longitude;
33921         // iterate over all the clinics and add them to the map
33922         for (var i = 0; i < this.results.length; i++) {
33923             latitude = this.results[i].latitude;
33924             longitude = this.results[i].longitude;
33925             if(latitude && longitude) {
33926                 // create a map marker for this clinic
33927                 var marker = new google.maps.Marker({
33928                    position: new google.maps.LatLng(latitude, longitude),
33929                    map: map,
33930                    icon: {
33931                        url: mapIcon,
33932                        size: this.normalSize.size,
33933                        scaledSize: this.normalSize.size
33934                    },
33935                    zIndex: this.normalSize.zIndex
33936                 });
33937
33938                 this.addClinicClickListeners(this.results[i], marker, map);
33939
33940                 //extend the bounds to include each marker's position
33941                 bounds.extend(marker.position);
33942             }
33943         }
33944
33945         // reset the map's bounds so that all the marker's show
33946         map.fitBounds(bounds);
33947     },
33948     loadDoctorDirectoryMap: function(map) {
33949         var bounds = new google.maps.LatLngBounds();
33950         /* mappedCoordinates is an object that stores a latitude, longitude, and the
33951          * number of times we've mapped this location, so that we can manipulate the lat and long
33952          * to a slightly different location.
33953          */
33954         var mappedCoordinates = [];
33955         var latitude, longitude;
33956         var clinicNames = [];
33957         var locationPassThroughInfo = SHC.util.getLocationPassThroughInfo();
33958         var clinicPassThroughInfo = SHC.util.getClinicPassThroughInfo();
33959         if(clinicPassThroughInfo.clinicName !== null && clinicPassThroughInfo.groupName !== null) {
33960             SHC.util.getMultiClinicPassThroughInfo(clinicPassThroughInfo.groupName).done(function(data){
33961                 for(var iter = 0; iter < data.maplocations.length; iter++) {
33962                     clinicNames.push(data.maplocations[iter].title);
33963                 }
33964             }).fail(function(){
33965                 clinicNames = null;
33966             });
33967         }
33968         // place clinics in the same location into a new array called mappedCoordinates
33969         for (var i = 0; i < this.results.length; i++) {
33970             latitude = parseFloat(this.results[i].clinic_latitude);
33971             longitude = parseFloat(this.results[i].clinic_longitude);
33972
33973             // some pcha clinics don't have coordinates, servlet assigns them 0.0 to keep facets in tact
33974             // but we can't show them on the map or we'd stretch it to show africa
33975             if(latitude && longitude && (latitude !== 0.0 || longitude !== 0.0)) {
33976                 // if in location pass through, don't include locations other than the one at this lat/lng
33977                 if(locationPassThroughInfo.address !== null && locationPassThroughInfo.address !== SHC.util.getMainAddress(SHC.util.getCompleteAddress(this.results[i].clinic_address))) {
33978                     continue;
33979                 }
33980                 var isDuplicateCoordinate = false;
33981                 for(var j = 0; j < mappedCoordinates.length; j++) {
33982                     // if this lat/lng has been mapped already
33983                     if(mappedCoordinates[j].latitude === latitude && mappedCoordinates[j].longitude === longitude) {
33984                         mappedCoordinates[j].clinics.push(this.results[i]);
33985                         // increase the number of times it has been
33986                         mappedCoordinates[j].count += 1;
33987                         mappedCoordinates[j].numDoctors += this.results[i].doctors.length;
33988                         isDuplicateCoordinate = true;
33989                         // no need to go through the rest, each unique lat/lng pair will only be in there once
33990                         break;
33991                     }
33992                 }
33993                 // if it wasn't in the mappedCoordinates object, put it in with a count of one
33994                 if(!isDuplicateCoordinate) {
33995                     var coordinate = {};
33996                     coordinate.latitude = latitude;
33997                     coordinate.longitude = longitude;
33998                     coordinate.clinics = [];
33999                     coordinate.clinics.push(this.results[i]);
34000                     coordinate.count = 1;
34001                     coordinate.numDoctors = this.results[i].doctors.length;
34002                     mappedCoordinates.push(coordinate);
34003                 }
34004             }
34005         }
34006         for(var locationIndex = 0; locationIndex < mappedCoordinates.length; locationIndex++) {
34007             var clinicsByDoctors = false;
34008             var typeOfLocation = this.getTypeOfLocation(mappedCoordinates[locationIndex].numDoctors, mappedCoordinates[locationIndex].clinics.length);
34009             var icon = "";
34010             if(typeOfLocation === "fewDrMultiLocation" || typeOfLocation === "multiDrMultiLocation" || typeOfLocation === "multiDrSingleLocation") {
34011                 clinicsByDoctors = this.reformatIfHasDuplicates(mappedCoordinates[locationIndex]);
34012             }
34013             if(clinicsByDoctors) {
34014                 icon = this.getIconFromNumDoctors(clinicsByDoctors.length);
34015                 mappedCoordinates[locationIndex].numDoctors = clinicsByDoctors.length;
34016             }
34017             else {
34018                 icon = this.getIconFromNumDoctors(mappedCoordinates[locationIndex].numDoctors);
34019             }
34020
34021             var marker = new google.maps.Marker({
34022                 position: new google.maps.LatLng(mappedCoordinates[locationIndex].latitude, mappedCoordinates[locationIndex].longitude),
34023                 map: map,
34024                 icon: icon,
34025                 zIndex: this.normalSize.zIndex,
34026                 index: locationIndex
34027             });
34028
34029             // add a marker and click listeners for this lcoation
34030             this.addDoctorClickListeners(mappedCoordinates[locationIndex], marker, map, typeOfLocation, clinicsByDoctors);
34031
34032             //extend the bounds to include each marker's position
34033             bounds.extend(marker.position);
34034
34035             // reset the map's bounds so that all the marker's show
34036             map.fitBounds(bounds);
34037         }
34038
34039     },
34040     loadTemplate: function (incomingData, template) {
34041         return template(incomingData);
34042     },
34043     buildGettingHereLink: function(url) {
34044         var path = SHC.util.getPathFromUrl(url);
34045         // ie doesn't always have the forward slash at the beginning so add it if it's not there.
34046         if(path.indexOf('/') !== 0) {
34047             path = '/' + path;
34048         }
34049         var link = path.substr(0, path.lastIndexOf('.html')) + '.mapmodal.html';
34050
34051         return SHC.util.adjustPath(link, true);
34052     },
34053     setMarkerIconSize: function(marker, iconSize) {
34054         if(marker) {
34055             var icon = marker.getIcon();
34056             icon.size = iconSize.size;
34057             icon.scaledSize = iconSize.size;
34058             marker.setIcon(icon);
34059             marker.zIndex = iconSize.zIndex;
34060         }
34061     },
34062     addClinicClickListeners: function(result, marker, map) {
34063         var that = this;
34064
34065         var infoWindowContent = "",
34066             clinic,
34067             markerLocationInfo,
34068             infoWindowWidth;
34069         // only put in a header if there's more than 1 clinic at this location, otherwise we'll only use the single clinic template
34070         if (result.clinics.length > 1) {
34071             var clinicHeaderInfo = {
34072                 numClinics: result.clinics.length,
34073                 address: result.clinics[0].addressLine1,
34074                 city: result.clinics[0].city,
34075                 state: result.clinics[0].state
34076             };
34077
34078             infoWindowContent += this.loadTemplate(clinicHeaderInfo, JST["directory-handlebars/info-window-clinic-header.hbs"]);
34079             infoWindowContent += "<div class='info-window-clinic-content-wrapper'>";
34080         }
34081         else {
34082             infoWindowContent += "<div class='info-window-clinic-content-wrapper single-clinic-content-wrapper'>";
34083         }
34084
34085
34086         for (var i = 0; i < result.clinics.length; i++) {
34087             clinic = result.clinics[i];
34088             markerLocationInfo = {
34089                 pagePath: clinic.url,
34090                 title: clinic.title,
34091                 address: clinic.addressLine1,
34092                 address2: clinic.addressLine2,
34093                 city: clinic.city,
34094                 state: clinic.state,
34095                 zipcode: clinic.zip,
34096                 locationDetails: this.buildGettingHereLink(clinic.url)
34097             };
34098             if (result.clinics.length > 1) {
34099                 infoWindowWidth = 300;
34100                 infoWindowContent += this.loadTemplate(markerLocationInfo, JST["directory-handlebars/info-window-clinics-template.hbs"]);
34101             }
34102             else {
34103                 infoWindowWidth = 230;
34104                 infoWindowContent += this.loadTemplate(markerLocationInfo, JST["directory-handlebars/info-window-clinic-template.hbs"]);
34105             }
34106         }
34107         infoWindowContent += "</div>";
34108
34109         var infoWindow = new InfoBubble({
34110             content: infoWindowContent,
34111             maxWidth: infoWindowWidth,
34112             minWidth: infoWindowWidth,
34113             minHeight: 300,
34114             maxHeight: 200,
34115             shadowStyle: 0,
34116             padding: 16,
34117             borderRadius: 5,
34118             closeSrc: "/etc/clientlibs/shc/main/svg/close-icon-info-bubble.svg"
34119         });
34120
34121         // listener for when marker is clicked
34122         google.maps.event.addListener(marker, 'click', function() {
34123             // set the active marker's icon back to it's regular size
34124             that.setMarkerIconSize(that.activeMarker, that.normalSize);
34125
34126             // set the clicked markers' icon to be big
34127             that.setMarkerIconSize(marker, that.bigSize);
34128
34129             // close any active info windows (only want one open at a time)
34130             if(that.openInfoWindow) {
34131                that.openInfoWindow.close();
34132             }
34133
34134             that.activeMarker = marker;
34135             that.openInfoWindow = infoWindow;
34136             infoWindow.open(map, marker);
34137
34138             // fire event for analytics
34139             $(window).trigger("ClinicDirectoryMapClick");
34140         });
34141
34142         // listener for when open info window is closed
34143         google.maps.event.addListener(infoWindow, 'closeclick', function() {
34144             // set the active marker's icon back to it's regular size
34145             that.setMarkerIconSize(that.activeMarker, that.normalSize);
34146             that.openInfoWindow = null;
34147         });
34148
34149         google.maps.event.addListener(infoWindow, 'domready', function(){
34150             if (result.clinics.length > 1) {
34151                 $('.info-window-clinic-content-wrapper').mCustomScrollbar({
34152                     theme: "map-view"
34153                 });
34154             }
34155             // bind the "Getting Here" links in the info window
34156             new SHC.ui.Modal('.info-window-modal.info-window-location');
34157             $(window).trigger("ClinicDirectoryDomReady");
34158         });
34159     },
34160    addDoctorClickListeners: function(result, marker, map, typeOfLocation, clinicsByDoctors) {
34161        var that = this;
34162
34163        var infoBubbleContent = "";
34164        var bubbleWidth = 301;
34165        var bubbleHeight = 299;
34166
34167        if(typeOfLocation === "singleDrSingleLocation" || typeOfLocation === "fewDrSingleLocation") {
34168            infoBubbleContent += this.loadFewOrSingleSingleBubble(result);
34169        }
34170        else if(typeOfLocation === "fewDrMultiLocation") {
34171            infoBubbleContent += this.loadFewMultiBubble(result, clinicsByDoctors);
34172        }
34173        else if(typeOfLocation === "multiDrSingleLocation") {
34174            bubbleWidth = 228;
34175            bubbleHeight = 170;
34176
34177            infoBubbleContent += this.loadMultiSingleBubble(result);
34178        }
34179        else if(typeOfLocation === "multiDrMultiLocation") {
34180            infoBubbleContent += this.loadMultiMultiBubble(result);
34181        }
34182
34183        var infoBubble = new InfoBubble({
34184            content: infoBubbleContent,
34185            minWidth: bubbleWidth,
34186            maxWidth: bubbleWidth,
34187            shadowStyle: 0,
34188            padding: 16,
34189            borderRadius: 5,
34190            maxHeight: bubbleHeight,
34191            closeSrc: "/etc/clientlibs/shc/main/svg/close-icon-info-bubble.svg"
34192        });
34193
34194        // listener for when marker is clicked
34195        google.maps.event.addListener(marker, 'click', function() {
34196            // close any active info windows (only want one open at a time)
34197            if(that.openInfoWindow) {
34198                that.openInfoWindow.close();
34199            }
34200
34201            that.activeMarker = marker;
34202            that.openInfoWindow = infoBubble;
34203            infoBubble.open(map, marker);
34204            // bind the "Getting Here" links in the info window
34205            new SHC.ui.Modal('.info-window-modal.info-window-location');
34206
34207            // fire event for analytics
34208            $(window).trigger("DoctorDirectoryMapClick");
34209        });
34210
34211        var lastMapMarkerIndex = SHC.util.getCookie("lastMapMarkerIndex");
34212        var lastMapLatitude = SHC.util.getCookie("lastMapLatitude");
34213        var lastMapLongitude = SHC.util.getCookie("lastMapLongitude");
34214        var lastMapZoom = SHC.util.getCookie("lastMapZoom");
34215
34216        // if marker.index matches cookie marker index, trigger click
34217        if(lastMapMarkerIndex) {
34218            if(Number(lastMapMarkerIndex) === marker.index) {
34219                new google.maps.event.trigger(marker, 'click');
34220            }
34221        }
34222
34223        // listener for when open info window is closed
34224        google.maps.event.addListener(infoBubble, 'closeclick', function() {
34225            // set the active marker's icon back to it's regular size
34226            that.openInfoWindow = null;
34227            SHC.ui.Search.DirectoryUtil.clearMapCookies();
34228        });
34229
34230        google.maps.event.addListener(infoBubble, 'domready', function(){
34231            var $contentWrapper = $('.info-window-doctor-content-wrapper');
34232            var $header = $('.info-window-header-container.doctors');
34233            $contentWrapper.mCustomScrollbar({
34234                theme: "map-view"
34235            });
34236
34237            $('.location-passthrough-link').click(function() {
34238                SHC.util.setCookie("activeView", "list", 1, "/");
34239            });
34240            $('.clinic-passthrough-link').click(function() {
34241                SHC.util.setCookie("activeView", "list", 1, "/");
34242            });
34243            // save position/zoom/center of location as they click on a doctor or clinic
34244            $header.on('click', 'a', function() {
34245                that.setCookies(map.getZoom(), map.getCenter().lat(), map.getCenter().lng(), marker.index);
34246
34247            });
34248            $contentWrapper.on('click', 'a', function() {
34249                that.setCookies(map.getZoom(), map.getCenter().lat(), map.getCenter().lng(), marker.index);
34250            });
34251
34252            $(window).trigger("DoctorDirectoryDomReady");
34253        });
34254    },
34255    /**
34256     * Generates markup for >= 20 doctors at more than one clinic
34257     *
34258     * @param result - clinic with doctors and clinic info
34259     * @returns {string} markup for infobubble
34260     */
34261    loadMultiMultiBubble: function (result) {
34262        var infoBubbleContent = "";
34263        var locationHeaderInfo = {};
34264
34265        locationHeaderInfo.numDoctors = result.numDoctors;
34266        locationHeaderInfo.numClinics = result.clinics.length;
34267        locationHeaderInfo.address = SHC.util.getMainAddress(SHC.util.getCompleteAddress(result.clinics[0].clinic_address));
34268        locationHeaderInfo.location = result.clinics[0].clinic_latitude + "," + result.clinics[0].clinic_longitude;
34269        infoBubbleContent += this.loadTemplate(locationHeaderInfo, JST["directory-handlebars/info-bubble-header-multi-multi.hbs"]);
34270
34271        infoBubbleContent += "<div class='info-window-doctor-content-wrapper multi-multi scrollable'>";
34272        var clinicInfo = {};
34273        for (var i = 0; i < result.clinics.length; i++) {
34274            clinicInfo = {
34275                clinicPath: result.clinics[i].clinic_path,
34276                clinicName: result.clinics[i].clinic_name,
34277                numDoctors: result.clinics[i].doctors.length
34278            };
34279            infoBubbleContent += this.loadTemplate(clinicInfo, JST["directory-handlebars/info-bubble-clinic-pass-through.hbs"]);
34280        }
34281        infoBubbleContent += "</div>";
34282
34283        return infoBubbleContent;
34284    },
34285    /**
34286     * Generates markup for < 20 doctors at more than one clinic.
34287     *
34288     * Looks for duplicate doctors and reorders data if one is found.
34289     *
34290     * @param result - clinic with doctors and clinic info
34291     * @param clinicsByDoctors - reorganized data for doctors at multiple clinics at one location
34292     * @returns {string} array of clinics with doctors or array of doctors with clinics
34293     */
34294    loadFewMultiBubble: function(result, clinicsByDoctors) {
34295        var infoBubbleContent = "";
34296        var locationHeaderInfo = {};
34297        var doctor, doctorInfo = {};
34298        var i,j;
34299
34300
34301        // if one location has more than one clinic with the same doctor, we need to rearrange the data
34302        locationHeaderInfo.numDoctors = clinicsByDoctors ? clinicsByDoctors.length : result.numDoctors;
34303        locationHeaderInfo.numClinics = result.clinics.length;
34304        locationHeaderInfo.address = result.clinics[0].clinic_address;
34305
34306        infoBubbleContent += this.loadTemplate(locationHeaderInfo, JST["directory-handlebars/info-bubble-header-few-multi.hbs"]);
34307        infoBubbleContent += "<div class='info-window-doctor-content-wrapper few-multi scrollable'>";
34308
34309        // if doctors belonged to multiple clinics at this same location, use the restructured data
34310        if(clinicsByDoctors) {
34311            for (i = 0; i < clinicsByDoctors.length; i++) {
34312                doctor = clinicsByDoctors[i];
34313                doctorInfo = {
34314                    pagePath: doctor.profile_url,
34315                    title: doctor.title,
34316                    clinicalTitle: SHC.util.setPhysicianShortTitle(doctor.group_titles),
34317                    doctorProfileImage: this.getDoctorPhoto(doctor.image_url),
34318                    clinics: doctor.clinics
34319                };
34320                infoBubbleContent += this.loadTemplate(doctorInfo, JST["directory-handlebars/info-window-doctor-template.hbs"]);
34321            }
34322        }
34323        else {
34324            for (i = 0; i < result.clinics.length; i++) {
34325                for(j = 0; j < result.clinics[i].doctors.length; j++) {
34326                    doctor = result.clinics[i].doctors[j];
34327                    doctorInfo = {
34328                        pagePath: doctor.profile_url,
34329                        title: doctor.title,
34330                        clinicalTitle: SHC.util.setPhysicianShortTitle(doctor.group_titles),
34331                        doctorProfileImage: this.getDoctorPhoto(doctor.image_url),
34332                        clinicName: result.clinics[i].clinic_name,
34333                        clinicPath: result.clinics[i].clinic_path
34334                    };
34335                    infoBubbleContent += this.loadTemplate(doctorInfo, JST["directory-handlebars/info-window-doctor-template.hbs"]);
34336                }
34337            }
34338        }
34339
34340        infoBubbleContent += "</div>";
34341
34342        return infoBubbleContent;
34343    },
34344    /**
34345     * Generates markup for single doctor, single clinic/  < 20 doctors at a single clinic
34346     *
34347     * @param result - clinic with doctors and clinic info
34348     * @returns {string} markup for infobubble
34349     */
34350    loadFewOrSingleSingleBubble: function(result) {
34351        var infoBubbleContent = "";
34352        var locationHeaderInfo = {}, doctor, doctorInfo = {};
34353
34354        locationHeaderInfo.infoPath = result.clinics[0].clinic_path;
34355        locationHeaderInfo.infoAddress = result.clinics[0].clinic_address;
34356        locationHeaderInfo.infoHeader = result.clinics[0].clinic_name;
34357        infoBubbleContent += this.loadTemplate(locationHeaderInfo, JST["directory-handlebars/info-bubble-header-few-single.hbs"]);
34358
34359        if(result.clinics[0].doctors.length > 2) {
34360            infoBubbleContent += "<div class='info-window-doctor-content-wrapper few-single scrollable'>";
34361        }
34362        else {
34363            infoBubbleContent += "<div class='info-window-doctor-content-wrapper single-single'>";
34364        }
34365        for (i = 0; i < result.clinics[0].doctors.length; i++) {
34366            doctor = result.clinics[0].doctors[i];
34367            doctorInfo = {
34368                pagePath: doctor.profile_url,
34369                title: doctor.title,
34370                clinicalTitle: SHC.util.setPhysicianShortTitle(doctor.group_titles),
34371                doctorProfileImage: this.getDoctorPhoto(doctor.image_url)
34372            };
34373            infoBubbleContent += this.loadTemplate(doctorInfo, JST["directory-handlebars/info-window-doctor-template.hbs"]);
34374        }
34375        infoBubbleContent += "</div>";
34376
34377        return infoBubbleContent;
34378    },
34379    /**
34380     * Generates markup for >= 20 doctors at a single clinic
34381     *
34382     * @param result - clinic with doctors and clinic info
34383     * @returns {string} markup for infobubble
34384     */
34385    loadMultiSingleBubble: function(result) {
34386        var infoBubbleContent = "";
34387        var locationHeaderInfo = {};
34388
34389        locationHeaderInfo.clinicName = result.clinics[0].clinic_name;
34390        locationHeaderInfo.clinicPath = result.clinics[0].clinic_path;
34391        locationHeaderInfo.numDoctors = result.numDoctors;
34392        locationHeaderInfo.address = result.clinics[0].clinic_address;
34393
34394        infoBubbleContent += this.loadTemplate(locationHeaderInfo, JST["directory-handlebars/info-bubble-header-multi-single.hbs"]);
34395        return infoBubbleContent;
34396    },
34397    /**
34398     * Returns path to map marker pin png matching the number of doctors
34399     *
34400     * @param numDoctors
34401     * @returns {string} path to marker image
34402     */
34403    getIconFromNumDoctors: function(numDoctors) {
34404        var icon = "";
34405        if(numDoctors > 199) {
34406            icon = "/etc/clientlibs/shc/main/img/Maps/pins/Numbers/map-marker_200+.png";
34407        }
34408        else if(numDoctors > 174) {
34409            icon = "/etc/clientlibs/shc/main/img/Maps/pins/Numbers/map-marker_175+.png";
34410        }
34411        else if(numDoctors > 149) {
34412            icon = "/etc/clientlibs/shc/main/img/Maps/pins/Numbers/map-marker_150+.png";
34413        }
34414        else if(numDoctors > 124) {
34415            icon = "/etc/clientlibs/shc/main/img/Maps/pins/Numbers/map-marker_125+.png";
34416        }
34417        else if(numDoctors > 99) {
34418            icon = "/etc/clientlibs/shc/main/img/Maps/pins/Numbers/map-marker_100+.png";
34419        }
34420        else if(numDoctors > 74) {
34421            icon = "/etc/clientlibs/shc/main/img/Maps/pins/Numbers/map-marker_75+.png";
34422        }
34423        else {
34424            icon = "/etc/clientlibs/shc/main/img/Maps/pins/Numbers/map-marker_"+ numDoctors +".png";
34425        }
34426
34427        return icon;
34428    },
34429    /**
34430     * Returns which type of bubble should be made given the number of docs and clinics
34431     *
34432     * @param numDoctors
34433     * @param numClinics
34434     * @returns {*} the type of bubble as a string
34435     */
34436    getTypeOfLocation: function(numDoctors, numClinics) {
34437        // look for single doctors multiple clinics case
34438        if(numDoctors === 1 && numClinics === 1) {
34439            return "singleDrSingleLocation";
34440        }
34441        else if(numDoctors < 21) {
34442            // few doctors
34443            if(numClinics > 1) {
34444                return "fewDrMultiLocation";
34445            }
34446            else {
34447                return "fewDrSingleLocation";
34448            }
34449        }
34450        else {
34451            // lotsa doctas
34452            if(numClinics > 1) {
34453                return "multiDrMultiLocation";
34454            }
34455            else {
34456                return "multiDrSingleLocation";
34457            }
34458        }
34459    },
34460    /**
34461     * Looks for duplicate doctors at a single location working at multiple clinics
34462     * and restructures the data if it is the case for this clinic.
34463     *
34464     * @param result - clinic with doctors and clinic info
34465     * @returns {*} array of doctor objects, at least one of them will have multiple clinics at this one location
34466     */
34467    reformatIfHasDuplicates: function(result) {
34468        var combinedDoctors = [];
34469        var resultModified = false;
34470
34471        //join all doctors from all clinics and save the name of their clinic
34472        for(var i = 0; i < result.clinics.length; i++) {
34473            for(var j = 0; j < result.clinics[i].doctors.length; j++) {
34474                var newLength = combinedDoctors.push(result.clinics[i].doctors[j]);
34475                if(typeof combinedDoctors[newLength-1].clinics === 'undefined') {
34476                    combinedDoctors[newLength-1].clinics = [];
34477                }
34478                combinedDoctors[newLength-1].clinics.push(result.clinics[i]);
34479            }
34480        }
34481
34482        function doctorComparator(doctorOne, doctorTwo) {
34483            return doctorOne.name.localeCompare(doctorTwo.name);
34484        }
34485
34486        combinedDoctors = combinedDoctors.sort(doctorComparator);
34487        var duplicateIndexes = [];
34488
34489        // go through the duplicate doctors and pass their clinics to the next entry of themselves
34490        // mark the current duplicate for deletion
34491        for(var k = 0; k < combinedDoctors.length - 1; k++) {
34492            // if this doctor is the same as the next one
34493            if(combinedDoctors[k].name.localeCompare(combinedDoctors[k+1].name) === 0) {
34494                resultModified = true;
34495                // add his clinics to his clinics in the next bucket
34496                for(var l = 0; l < combinedDoctors[k].clinics.length; l++) {
34497                    combinedDoctors[k+1].clinics.push(combinedDoctors[k].clinics[l]);
34498                }
34499                // mark this one for deletion
34500                duplicateIndexes.push(k);
34501            }
34502        }
34503
34504        // delete the duplicates that don't contain all of the doctor's clinics, in reverse order so that we don't mess up the indexes
34505        for(var m = duplicateIndexes.length - 1; m >= 0; m--) {
34506            combinedDoctors.splice(duplicateIndexes[m], 1);
34507        }
34508
34509        if(resultModified) {
34510            return combinedDoctors;
34511        }
34512        else {
34513            return false;
34514        }
34515    },
34516    setCookies: function(zoom, centerLat, centerLng, markerIndex) {
34517        SHC.util.setCookie("lastMapZoom", zoom, 1, "/");
34518        SHC.util.setCookie("lastMapLatitude", centerLat, 1, "/");
34519        SHC.util.setCookie("lastMapLongitude", centerLng, 1, "/");
34520        SHC.util.setCookie("lastMapMarkerIndex", markerIndex, 1, "/");
34521    },
34522    getDoctorPhoto: function(doctorImage) {
34523        if (doctorImage) {
34524            return doctorImage+this.transformSuffix;
34525        }
34526        return this.defaultPhoto;
34527    }
34528});
34529
34530SHC.Namespace(SHC, "SHC.ui.PrimaryCareTool");
34531SHC.ui.primaryCareTool = new SHC.Class();
34532
34533SHC.ui.primaryCareTool.include({
34534    /*
34535     * constructor
34536     */
34537    init: function(parent) {
34538        this.parent = parent;
34539        this.menuItemLimit = 2;
34540        this.menuItemLimitAll = 8;
34541        this.primaryCareMap = null;
34542        this.$button = jQuery(parent).find(".button-custom-submit");
34543        this.$careType = jQuery(parent).find(".dropdown-title-text");
34544        this.$zipTextBox = jQuery(parent).find(".zipcode-textbox");
34545        this.$zipTitle = jQuery(parent).find(".zipcode-title");
34546        this.$primaryCareError = jQuery(parent).find(".primary-care-error");
34547        this.$zipcodeError = jQuery(parent).find(".zipcode-error");
34548        if(jQuery(this.parent)){
34549            this.activate();
34550        }
34551    },
34552
34553    activate: function() {
34554        var _this = this;
34555        var dropFirstClick = false;
34556
34557        // Opens map panel when 'Find Now' button is clicked
34558        jQuery(_this.parent).find(".button-custom-submit").on("click enter", function(){
34559            jQuery(_this.parent).find('.primary-care-image').hide();
34560            jQuery(_this.parent).find(".openmap").slideDown('fast');
34561            jQuery(_this.parent).find(".container").css("margin-bottom","40px");
34562        });
34563
34564        // trigger validates function on textbox keyup
34565        _this.$zipTextBox.on("keyup", function (){
34566            if(jQuery(this).val().length >= 5) {
34567                _this.validateForSubmit();
34568            }
34569        });
34570
34571        _this.$zipTextBox.on("blur", function (){
34572            if(!_this.isValidZip()) {
34573                _this.showZipError();
34574            }
34575        });
34576
34577        //handles hiding and showing of menu and map            
34578        jQuery('body').find(_this.parent).on("click", ".list-view", function(){
34579            if(jQuery(this).hasClass("list-view-off")){
34580                jQuery(this).removeClass("list-view-off").addClass("list-view-on");
34581                jQuery(_this.parent).find(".map-view").addClass("map-view-off").removeClass("map-view-on");
34582                jQuery(_this.parent).find(".list-results").show();
34583                jQuery(_this.parent).find("#gmap").hide();
34584            }else{
34585                jQuery(this).addClass("list-view-off").removeClass("list-view-on");
34586                jQuery(_this.parent).find(".map-view").removeClass("map-view-off").addClass("map-view-on");
34587
34588                jQuery(_this.parent).find("#gmap").show();
34589                jQuery('#gmap').css("height", "560px");
34590                jQuery('#gmap').css("width", jQuery(_this.parent).find(".list-results").width() + "px");
34591                jQuery(_this.parent).find(".list-results").hide();
34592                _this.primaryCareMap.resizeMap();
34593            }
34594            
34595
34596        });
34597        jQuery('body').find(_this.parent).on("click", ".map-view", function(){
34598
34599            if(jQuery(this).hasClass("map-view-off")){
34600
34601
34602                jQuery(this).removeClass("map-view-off").addClass("map-view-on");
34603                jQuery(_this.parent).find(".list-view").addClass("list-view-off").removeClass("list-view-on");
34604
34605                jQuery(_this.parent).find("#gmap").show();
34606                jQuery('#gmap').css("height", "560px");
34607                jQuery('#gmap').css("width", jQuery(_this.parent).find(".list-results").width() + "px");
34608                jQuery(_this.parent).find(".list-results").hide();
34609                _this.primaryCareMap.resizeMap();
34610            }else{
34611                jQuery(this).addClass("map-view-off").removeClass("map-view-on");
34612                jQuery(_this.parent).find(".list-view").removeClass("list-view-off").addClass("list-view-on");
34613                jQuery(_this.parent).find("#gmap").hide();
34614                jQuery(_this.parent).find(".list-results").show();
34615            }
34616        });
34617        //on map resize adjust the size of the map and refresh
34618         jQuery(window).on('resizeEnd', function () {
34619             setTimeout(function () {
34620                jQuery('.primary-care').find('#gmap').css("width", "auto");
34621                if(_this.primaryCareMap){
34622                    _this.primaryCareMap.resizeMap();
34623                }
34624            }, 200);
34625         });
34626        //show dropdown on menu click
34627        jQuery(_this.parent).find(".dropdown-title").on("click.pcdropdown", function(){
34628            dropFirstClick = true;
34629            jQuery( ".dropdown-menu" ).toggle();
34630        });
34631        //hide dropdown if clicked outside of dropdown
34632        jQuery(document).click(function () {
34633           if(this !== jQuery(_this.parent).find(".dropdown-menu"))  {
34634               jQuery(_this.parent).find(".dropdown-menu").hide();
34635               if(dropFirstClick) {
34636                   if (_this.$careType.text() === "Primary Care Type") {
34637                       _this.$primaryCareError.show();
34638                   } else {
34639                       _this.$primaryCareError.hide();
34640                   }
34641               }
34642           }
34643        });
34644        // change primary care type in the menu name
34645        jQuery(_this.parent).find("#primary-care-dropdown-menu a").on("click.pcmenu",function(evt) {
34646            evt.preventDefault();
34647            _this.$careType.html($(this).html() + "<div class=\"dropdown-underline\"></div>");
34648            var dataValue = $(this).data("node-name");
34649            _this.$careType.data("node-name", dataValue);
34650            jQuery( ".dropdown-menu" ).toggle();
34651            //check for proper zip and primary care validation
34652            _this.validateForSubmit();
34653        });
34654        // click behavior for primary care search button
34655        jQuery(_this.parent).find("#primary-care-search-button").on("click.pcbutton",function(evt) {
34656            evt.preventDefault();
34657            _this.primaryCareMap = new SHC.ui.Map(function() {
34658               _this.primaryCareMap.doPrimaryCareRequest();
34659            });
34660        });
34661        // click behavior for see more results link    jQuery('body').on("click", '.marker-menu.icon', function () {
34662        jQuery('body').on('click', '.list-results a.see-more-link', function(e){
34663            e.preventDefault();
34664            var $hiddenResults = jQuery('.location-result.more');
34665            var $hiddenHRs = jQuery('hr.more');
34666            var $lastShowingResult = jQuery('.location-result.showing.last');
34667            var $lastShowingHR= jQuery('hr.showing.last');
34668
34669            $lastShowingHR.removeClass('last');
34670            $lastShowingResult.removeClass('last');
34671
34672            // loop
34673            jQuery.each($hiddenResults, function(index, value) {
34674                var $value = jQuery(value);
34675                if (index > _this.menuItemLimit) {
34676                    return false;
34677                } else {
34678                    $value.removeClass('more').addClass('showing');
34679                    if (index === _this.menuItemLimit) {
34680                        $value.addClass('last');
34681                    }
34682                }
34683                
34684            });
34685            jQuery.each($hiddenHRs, function(index, value) {
34686                var $value = jQuery(value);
34687                if (index > _this.menuItemLimit) {
34688                    return false;
34689                } else {
34690                    $value.removeClass('more').addClass('showing');
34691                    if (index === _this.menuItemLimit) {
34692                        $value.addClass('last');
34693                    }
34694                }
34695            });
34696            if ($hiddenResults.length <= _this.menuItemLimit + 1) {
34697                jQuery('.see-more-link-row').hide();
34698            }
34699        });
34700        jQuery('body').on('click', '.list-results a.see-more-link-all', function(e){
34701            e.preventDefault();
34702            var $hiddenResults = jQuery('.location-result.more');
34703            var $hiddenHRs = jQuery('hr.more');
34704            var $lastShowingResult = jQuery('.location-result.showing.last');
34705            var $lastShowingHR= jQuery('hr.showing.last');
34706
34707            $lastShowingHR.removeClass('last');
34708            $lastShowingResult.removeClass('last');
34709
34710            // loop
34711            jQuery.each($hiddenResults, function(index, value) {
34712                var $value = jQuery(value);
34713                if (index > _this.menuItemLimitAll) {
34714                    return false;
34715                } else {
34716                    $value.removeClass('more').addClass('showing');
34717                    if (index === _this.menuItemLimitAll) {
34718                        $value.addClass('last');
34719                    }
34720                }
34721            });
34722            jQuery.each($hiddenHRs, function(index, value) {
34723                var $value = jQuery(value);
34724                if (index > _this.menuItemLimitAll) {
34725                    return false;
34726                } else {
34727                    $value.removeClass('more').addClass('showing');
34728                    if (index === _this.menuItemLimitAll) {
34729                        $value.addClass('last');
34730                    }
34731                }
34732            });
34733            if ($hiddenResults.length <= _this.menuItemLimitAll + 1) {
34734                jQuery('.see-more-link-row-all').hide();
34735            }
34736        });
34737        jQuery('body').on('click', '.primary-care-tool a.see-all-results', function(e){
34738            e.preventDefault();
34739            _this.primaryCareMap = new SHC.ui.Map(function() {
34740                _this.primaryCareMap.getPrimaryCareJSON(true);
34741            });
34742        });
34743        
34744        // fix style bug in IE
34745        var ie = SHC.util.isIE();
34746        if(ie) {
34747            console.log("in ie");
34748            jQuery(_this.parent).addClass("isIE");
34749        }
34750    },
34751
34752    isValidCareType: function() {
34753        var careType = this.$careType.text();
34754        if (careType !== 'Primary Care Type') {
34755            return true;
34756        }
34757        return false;
34758    },
34759
34760    // validates zip code
34761    isValidZip: function(){
34762        var zip = this.$zipTextBox.val();
34763
34764        if (zip.match(/^[0-9]{5}$/)) {
34765            return true;
34766        }
34767        zip=zip.toUpperCase();
34768        if (zip.match(/^[A-Z][0-9][A-Z][0-9][A-Z][0-9]$/)) {
34769            return true;
34770        }
34771        if (zip.match(/^[A-Z][0-9][A-Z].[0-9][A-Z][0-9]$/)) {
34772            return true;
34773        }
34774        return false;
34775    },
34776
34777    // validates zip code for US and Canada codes and enables button when valid
34778    // also makes sure they have selected a care type
34779    validateForSubmit: function() {
34780        var validCardType = this.isValidCareType();
34781        var validZipCode = this.isValidZip();
34782
34783        if(validCardType) {
34784            this.$zipTextBox.fadeIn();
34785            this.$zipTitle.fadeIn();
34786            this.$zipcodeError.hide();
34787            this.$zipTextBox.focus();
34788        }
34789
34790        if(validZipCode && validCardType) {
34791            this.$zipcodeError.hide();
34792            this.$button.removeAttr("disabled");
34793            this.$button.show();
34794            this.$button.focus();
34795        }else if (validCardType && !validZipCode){
34796            this.showZipError();
34797        } else {
34798            this.$zipcodeError.hide();
34799            this.$button.hide();
34800        }
34801    },
34802
34803    showZipError: function() {
34804        if(this.$zipTextBox.val() !== "") {
34805            this.$zipcodeError.show();
34806        }
34807        this.$button.hide();
34808    }
34809});
34810SHC.Namespace(SHC, "SHC.ui.Quiz");
34811SHC.ui.Quiz = new SHC.Class();
34812SHC.ui.Quiz.current = 0;
34813SHC.ui.Quiz.answer = [];
34814SHC.ui.Quiz.restore = function () {
34815    SHC.ui.Quiz.current = 0;
34816    (SHC.ui.Quiz.answer).length = 0;
34817    $('.nextButton').removeClass('hidden');
34818    $('#quizcontainer').find('a.btn').show();
34819    $('.nextButton').find('a.btn').show();
34820    $('input:radio').removeAttr('checked');
34821    $("div.questionUnit").find('.answer').hide();
34822    $('.take_the_quiz').show();
34823    return false;
34824};
34825
34826SHC.ui.Quiz.include({
34827    init: function (parent) {
34828
34829        "use strict";
34830
34831        var that = this;
34832        if ($(parent).length > 0) {
34833            var len = $("#quizcontainer").find("div.questionUnit").length;
34834            $("div.questionUnit").eq(SHC.ui.Quiz.current).show();
34835
34836            if (SHC.util.WCM.isAuthorMode() || SHC.util.WCM.isDesignMode()) {
34837                $(".EDIT .quiz-summary").removeClass('hidden');
34838                $(".EDIT .take_the_quiz").hide();
34839                $('.quizparsys_wrapper').removeClass('hidden');
34840            }
34841
34842            for (var i = 0; i < len; i++) {
34843                $("div.questionUnit").eq(i).addClass("position" + i);
34844            }
34845
34846            $('input[type="radio"]').unbind().bind('click', function () {
34847                if ($(this).is(':checked')) {
34848                    that.processResult(this);
34849                }
34850            });
34851
34852            $('#quizcontainer .btn').unbind().bind('click', function () {
34853                $(this).blur();
34854                that.transit(len, $(this).closest('div').attr('class'));
34855            });
34856
34857            $('.nextButton').addClass('hidden');
34858            $('#tab-nav').find('.panel-collapse li').on('click', function () {
34859                that.reset();
34860            });
34861            $('#tabbed-nav').find('.child_list .child-links a').on('click', function () {
34862                that.reset();
34863            });
34864            that.showButton(len);
34865        }
34866    },
34867
34868    processResult: function (that) {
34869        var selectedAnswer = $(that).val();
34870        var actualAnswer = $(that).closest('form').attr('data-answer');
34871        if (selectedAnswer.toLowerCase() === actualAnswer.toLowerCase()) {
34872            this.showResult("Correct", that);
34873        } else {
34874            this.showResult("Incorrect", that);
34875        }
34876    },
34877
34878    showResult: function (result, that) {
34879        $("div.questionUnit").eq(SHC.ui.Quiz.current).find('.error').hide();
34880        $(that).closest("div.questionUnit").find("div.radioContainer").hide();
34881        $(that).closest(".EDIT div.questionUnit").find("div.radioContainer").show();
34882        var unit = $(that).closest("div.questionUnit").find('div.answer');
34883        unit.show();
34884        unit.find('h4').text(result);
34885        SHC.ui.Quiz.answer.push(result);
34886    },
34887
34888    transit: function (len, type) {
34889
34890        var that = this;
34891        var isAnswered = that.radioButtonCheck();
34892
34893        if (isAnswered || type === "prevButton" || type === "take_the_quiz") {
34894
34895            if (type === "prevButton") {
34896
34897                SHC.ui.Quiz.current--;
34898                $("div.questionUnit").hide();
34899                $("div.questionUnit").eq(SHC.ui.Quiz.current).find("div.radioContainer").show();
34900                $("div.questionUnit").eq(SHC.ui.Quiz.current).show();
34901                that.showButton(len);
34902
34903            } else if (type === "gradeButton") {
34904                $("div.questionUnit").hide();
34905                $("div.quiz-summary").removeClass('hidden');
34906                $("#quizcontainer").find('a.btn').hide();
34907                that.showFinalSummary(len);
34908
34909            } else if (type === "startOver") {
34910                that.reset();
34911                $('.take_the_quiz').hide();
34912                $('.quizparsys_wrapper').removeClass('hidden');
34913                $('.nextButton').removeClass('hidden');
34914                $("div.questionUnit").eq(SHC.ui.Quiz.current).show();
34915                $("div.radioContainer").show();
34916
34917            } else if (type === "take_the_quiz") {
34918                $('.take_the_quiz').hide();
34919                $('.quizparsys_wrapper').removeClass('hidden');
34920                $('.nextButton').removeClass('hidden');
34921
34922            } else {
34923
34924                SHC.ui.Quiz.current++;
34925                $("div.questionUnit").hide();
34926                $("div.questionUnit").eq(SHC.ui.Quiz.current).show();
34927                that.showButton(len);
34928            }
34929
34930        } else {
34931            $("div.questionUnit").eq(SHC.ui.Quiz.current).find('.error').show();
34932        }
34933
34934        if (that.msieversion()) {
34935            $('div.questionUnit').find('input').focus();
34936        }
34937
34938    },
34939
34940    showButton: function (len) {
34941        if (SHC.ui.Quiz.current === 0) {
34942            $('.prevButton').hide();
34943            $('.gradeButton').addClass('hidden');
34944        } else if (SHC.ui.Quiz.current === len - 1) {
34945            $('.nextButton').addClass('hidden');
34946            $('.gradeButton').removeClass('hidden');
34947        } else {
34948            $('.prevButton').show();
34949            $('.nextButton').removeClass('hidden');
34950            $('.gradeButton').addClass('hidden');
34951        }
34952    },
34953
34954    showFinalSummary: function (len) {
34955        $('span.total-question').text(len);
34956        $("div.quiz-summary").find('a.btn').show();
34957        var totalCorrectAnswer = this.calculateAnswer(SHC.ui.Quiz.answer);
34958        $('span.total-correct-answer').text(totalCorrectAnswer);
34959
34960    },
34961
34962    calculateAnswer: function (array) {
34963        var count = 0;
34964        for (var i = 0; i < array.length; ++i) {
34965            if (array[i] === "Correct") {
34966                count++;
34967            }
34968        }
34969        return count;
34970    },
34971
34972    reset: function () {
34973        var that = this;
34974        SHC.ui.Quiz.current = 0;
34975        (SHC.ui.Quiz.answer).length = 0;
34976        $('.nextButton').removeClass('hidden');
34977        $('#quizcontainer').find('a.btn').show();
34978        $('.nextButton').find('a.btn').show();
34979        $('input:radio').removeAttr('checked');
34980        $("div.questionUnit").find('.answer').hide();
34981        $('.take_the_quiz').show();
34982        $('.quiz-summary').addClass('hidden');
34983        that.init();
34984    },
34985
34986    radioButtonCheck: function () {
34987
34988        if ($("div.questionUnit").eq(SHC.ui.Quiz.current).find('input').is(':checked')) {
34989            return true;
34990        } else {
34991            return false;
34992        }
34993    },
34994
34995    msieversion: function () {
34996        var ua = window.navigator.userAgent;
34997        var msie = ua.indexOf("MSIE ");
34998        if (msie > 0) {      // If Internet Explorer, return version number
34999            return true;
35000        } else {
35001            return false;
35002        }
35003        return false;
35004    }
35005
35006});
35007SHC.Namespace(SHC, "SHC.ui.RevealBox");
35008SHC.ui.RevealBox = new SHC.Class();
35009
35010SHC.ui.RevealBox.include({
35011    init: function (parent) {
35012      this.parent = $(parent);
35013
35014      this.activate();
35015      this.autoActivate();
35016    },
35017
35018    activate: function () {
35019      var that = this;
35020
35021      var handleClick = function (e) {
35022        e.preventDefault();
35023        var clicked = jQuery(this);
35024        $(this).closest(".reveal-box").find(".reveal-arrow").toggleClass("active");
35025        $(this).closest(".reveal-box").find(".reveal-content").slideToggle(function () {
35026            if ($(this).closest('#tabbed-nav').length > 0) {
35027                window.scrollBy(0, 1); //for sticky nav
35028            }
35029            var tileTruncation = new  SHC.ui.TileTruncation();
35030        });
35031        if ($(this).closest(".reveal-box").find(".reveal-arrow").hasClass("active")) {
35032            var titleDisplacement = 120;
35033            if (jQuery("#in-page-nav:hidden").length <= 0) {
35034                titleDisplacement += 67;
35035            }
35036            setTimeout(function(){
35037                var alertbox = $("#new-emergency-alert");
35038                var offsetRevealBox = clicked.closest(".reveal-box").find(".reveal-content").offset().top-titleDisplacement;
35039                var animation = alertbox.length > 0 ? {scrollTop: offsetRevealBox - alertbox.height() } : {scrollTop: offsetRevealBox};
35040                $('html,body').animate(animation, 500, 'swing', function() {});
35041                $(document.body).scrollspycustom('refresh');
35042            }, 500);
35043            
35044            //push heading text to adobe data layer on collapsed
35045        	var headingText = $(this).closest(".reveal-box").find(".reveal-title").text().replace(/^\s+|\s+$/g, '');
35046        	stanford.analytics.send(stanford.analytics.createComponentClickSection('',headingText, "accordion"));
35047        }
35048      };
35049
35050      if(!$('body').attr("data-faq-bound")) {
35051          $('#main, #presentation-mode, #modal').on('click', '.faq-trigger', handleClick);
35052          $('#main, #presentation-mode, #modal').on('keypress', '.reveal-content-wrapper', handleClick);
35053      }
35054      $('body').attr("data-faq-bound", "true");
35055    },
35056    autoActivate: function() {
35057        var handleHash = function () {
35058            var urlHash = window.location.href.split("#")[1];
35059            if (urlHash) {
35060                var $selectedBox = jQuery('.faq-anchor[name="' + urlHash + '_"]');
35061
35062                if ($selectedBox.length) {
35063                    if (!$selectedBox.parent().find('.reveal-content').is(':visible')) {
35064                        var triggerElement = $selectedBox.closest('.revealbox_faq').find('.reveal-title.faq-trigger');
35065                        jQuery(triggerElement).trigger('click');
35066                    } else { //just scroll
35067                        setTimeout(function () {
35068                            var animation = {scrollTop: $selectedBox.offset().top - jQuery('#search-inpagenav').outerHeight()};
35069                            $('html,body').animate(animation, 500, 'swing', function () {
35070                            });
35071                            $(document.body).scrollspycustom('refresh');
35072                        }, 500);
35073                    }
35074                }
35075            }
35076        };
35077        handleHash();
35078        jQuery(window).on('hashchange', handleHash);
35079    }
35080});
35081SHC.Namespace(SHC, "SHC.ui.ThematicPanel");
35082SHC.ui.ThematicPanel = new SHC.Class();
35083SHC.ui.ThematicPanel.include({
35084    /*
35085     * constructor
35086     */
35087     init: function(parent) {
35088        var _this = this;
35089        this.parent = jQuery(parent);
35090        this.wrapper = this.parent.find(".thematic-panel-wrapper");
35091        this.panels = this.wrapper.find(".thematic-panel");
35092        this.controls = this.parent.find(".controls");
35093        this.paddles = this.controls.find(".paddles");
35094        this.paddleLeft = this.paddles.find(".paddle-left");
35095        this.paddleRight = this.paddles.find(".paddle-right");
35096
35097        // options
35098        this.activeClass = "active";
35099        this.animationSpeed = 350;
35100        this.currentId = 0;
35101        this.paddleFadeSpeed = 150;
35102        this.panelMargin = 2;
35103        this.panelDimSpeed = 250;
35104        this.panelWidth = this.panels.eq(0).width();
35105
35106        // get started
35107        this.activate();
35108    },
35109
35110    /*
35111     * activate the component
35112     */
35113     activate: function() {
35114        var _this = this;
35115
35116        // create controls
35117        if (this.panels.length > 1) {
35118            for (var i = 0; i < this.panels.length; i++) {
35119                var active = (i === 0) ? this.activeClass : "";
35120                this.controls.append("<a href=\"#\" class=\"toggle " + active + "\" data-id=\"" + i + "\">" + i + "</a>");
35121            }
35122        }
35123
35124        // on toggle click
35125        var handleToggle = function(e) {
35126            e.preventDefault();
35127
35128            // set new position and call animation
35129            var id = jQuery(this).data("id");
35130            _this.currentId = id;
35131            _this.animatePanels(id);
35132        };
35133
35134        // on swipe right
35135        var onSwipeRight = function(e) {
35136            e.preventDefault();
35137            var newId = _this.currentId - 1;
35138            if (newId >= 0) {
35139                _this.currentId = newId;
35140                _this.animatePanels(newId);
35141            }
35142        };
35143
35144        // on swipe left
35145        var onSwipeLeft = function(e) {
35146            e.preventDefault();
35147            var newId = _this.currentId + 1;
35148            if (newId < _this.panels.length) {
35149                _this.currentId = newId;
35150                _this.animatePanels(newId);
35151            }
35152        };
35153
35154        // on screen resize
35155        var onResize = function(e) {
35156            _this.wrapper.css({"marginLeft": _this.getPosition()});
35157            if (_this.panels.length > 1) {
35158                var panelWidth = _this.panels.eq(0).width();
35159                if (panelWidth) {
35160                    _this.panelWidth = panelWidth;
35161                }
35162                if (SHC.ui.viewportWidth >= 1140) {
35163                    _this.paddles.fadeIn(_this.paddleFadeSpeed);
35164                } else {
35165                    _this.paddles.fadeOut(_this.paddleFadeSpeed);
35166                }
35167            }
35168        };
35169
35170        // event listeners
35171        this.controls.find(".toggle").on("click", handleToggle);
35172        this.paddleLeft.on("click", onSwipeRight);
35173        this.paddleRight.on("click", onSwipeLeft);
35174        this.parent.on("swiperight", onSwipeRight);
35175        this.parent.on("swipeleft", onSwipeLeft);
35176        $(window).on("resizeEnd", onResize);
35177
35178        onResize();
35179        this.updatePaddles();
35180    },
35181
35182    /*
35183     * run animation
35184     */
35185    animatePanels: function() {
35186        var _this = this;
35187
35188        // update toggle
35189        this.setActiveToggle();
35190
35191        // handle panel overlays
35192        this.setActivePanel();
35193
35194        // update paddles
35195        this.updatePaddles();
35196
35197        // animate the tiles
35198        this.wrapper.transit({
35199            "marginLeft": _this.getPosition()
35200        }, this.animationSpeed, "easeOutCubic");
35201
35202    },
35203    /*
35204     * set active panel / handle panel overlays
35205     */
35206    setActivePanel: function() {
35207        this.panels.not(":eq(" + this.currentId + ")").find(".overlay").fadeIn(this.panelDimSpeed);
35208        this.panels.eq(this.currentId).find(".overlay").fadeOut(this.panelDimSpeed);
35209    },
35210    /*
35211     * set active toggle
35212     */
35213    setActiveToggle: function() {
35214        this.controls.find(".toggle").removeClass("active");
35215        this.controls.find(".toggle").eq(this.currentId).addClass("active");
35216    },
35217
35218    /*
35219     * update paddles
35220     */
35221    updatePaddles: function() {
35222        if (this.panels.length > 1) {
35223            // enable/disable right paddle
35224            if (this.currentId < this.panels.length - 1) {
35225                this.paddleRight.fadeIn(this.paddleFadeSpeed);
35226            } else {
35227                this.paddleRight.fadeOut(this.paddleFadeSpeed);
35228            }
35229
35230            // enable/disable left paddle
35231            if (this.currentId > 0) {
35232                this.paddleLeft.fadeIn(this.paddleFadeSpeed);
35233            } else {
35234                this.paddleLeft.fadeOut(this.paddleFadeSpeed);
35235            }
35236        }
35237    },
35238
35239    /*
35240     * get position
35241     */
35242    getPosition: function() {
35243       return (-1 * this.currentId * this.panelWidth) + (-1 * this.currentId * this.panelMargin);
35244    }
35245     
35246});
35247
35248window.onload = function(){
35249    var agent = navigator.userAgent;
35250    if( agent.indexOf('MSIE 7') > 0 || agent.indexOf('MSIE 8') > 0 ||
35251        agent.indexOf('MSIE 9') > 0 || agent.indexOf('MSIE 10') > 0){
35252
35253        //general message
35254        var download_link = 'https://www.microsoft.com/en-us/download/internet-explorer.aspx';
35255        var download_msg = 'Go to Microsoft.com and update to Internet Explorer 11';
35256
35257        //specific to OS
35258        if (agent.indexOf("Windows NT 6.2") > 0){
35259            //windows 8
35260            download_link = 'https://www.microsoft.com/en-us/download/details.aspx?id=40854';
35261        }else if (agent.indexOf("Windows NT 6.1") > 0){
35262            //windows 7
35263            download_link = 'https://www.microsoft.com/en-us/download/Internet-Explorer-11-for-Windows-7-details.aspx';
35264        }else if ( (agent.indexOf("Windows NT 6.0") > 0) || (agent.indexOf("Windows NT 5.1") > 0)){
35265            //vista - xp
35266            download_link = 'https://www.google.com/chrome/browser/desktop';
35267            download_msg = 'Please use an alternate browser like Google Chrome';
35268        }
35269
35270        var warningText = '<span>BROWSER NOT SUPPORTED</span> - ' +
35271            'You are using an unsupported browser. Some features may not work correctly.<br>' +
35272            '<a href="' + download_link + '">' + download_msg + '</a>';
35273
35274        var warning = document.createElement("div");
35275        warning.id = 'not-supported-browser';
35276        warning.innerHTML = warningText;
35277
35278        var masthead = jQuery('.masthead');
35279        masthead[0].parentNode.insertBefore(warning, masthead[0].nextSibling);
35280    }
35281};
35282// IMPORTANT: This class has dependencies on both google maps and gmaps.js
35283// These libraries are loaded dynamically when a new instance of SHC.ui.Map
35284// is created. If the SHC.ui.Map instance is to be used immediately after
35285// instantiation then this should be done by passing a callback function
35286// to the constructor to ensure the new SHC.ui.Map instance is not used
35287// before instantiation finishes.
35288
35289SHC.Namespace(SHC, "SHC.ui.Map");
35290SHC.ui.Map = new SHC.Class();
35291
35292SHC.ui.Map.include({
35293    // creates the map with accompanying functionality
35294    init: function (callback) {
35295        var that = this;
35296        this.loadNecessaryLibraries(function() {
35297            that.activeClinicIcon = "/etc/clientlibs/shc/main/img/Maps/pins/Star/star_active.svg";
35298            that.inactiveClinicIcon = "/etc/clientlibs/shc/main/img/Maps/pins/Star/star_small.svg";
35299            that.activeParkingIcon = "/etc/clientlibs/shc/main/img/Maps/pins/Parking/parking-self_active.svg";
35300            that.activeValetIcon = "/etc/clientlibs/shc/main/img/Maps/pins/Parking/parking-valet_active.svg";
35301            that.alphabetMarkerIconBasePath = "/etc/clientlibs/shc/main/img/Maps/pins/Alphabets/";
35302            that.markerSuffix = ".svg";
35303            if (!(window.ActiveXObject) && "ActiveXObject" in window) {
35304                that.markerSuffix = ".png";
35305                that.activeClinicIcon = "/etc/clientlibs/shc/main/img/Maps/pins/Star/star_active.png";
35306                that.inactiveClinicIcon = "/etc/clientlibs/shc/main/img/Maps/pins/Star/star_small.png";
35307                that.activeParkingIcon = "/etc/clientlibs/shc/main/img/Maps/pins/Parking/parking-self_active.png";
35308                that.activeValetIcon = "/etc/clientlibs/shc/main/img/Maps/pins/Parking/parking-valet_active.png";
35309            }
35310            that.display = jQuery("#map-display");
35311            that.zoom = (SHC.ui.screenMode === 'small') ? 15 : 16;
35312            that.buildingArray = [];
35313            that.parkingArray = [];
35314            that.valetArray = [];
35315            that.allMarkersArray = [];
35316            that.gmap = null;
35317            that.zoomInControl = null;
35318            that.zoomOutControl = null;
35319            that.singleMapWidth = 822;
35320            that.singleMapHeight = 605;
35321            that.multiMapWidth = 822;
35322            that.multiMapHeight = 822;
35323            that.normalSize = new google.maps.Size(26.162, 38.236);
35324            that.bigSize = new google.maps.Size(31.412, 45.912);
35325            that.smallMenu = jQuery('.menu-marker.hamburger');
35326            that.smallMenuTarget = jQuery('.menu-target');
35327            that.locationsListTarget = jQuery('.locations-list-target');
35328            that.charBase = 65;
35329
35330            that.l3ServletRequestPath = "/bin/api/v1/content/shcmap.clinic.";
35331            that.campaignServletRequestPath = "/bin/api/v1/content/shcmap.campaign.";
35332            that.locationServletRequestPath = "/bin/api/v1/content/shcmap.location.";
35333            that.primaryCareServletRequestPath = "/bin/api/v1/content/shcmap.primarycare.";
35334            that.styles = that.makeStyles();
35335
35336            //primary care init stuff
35337            that.primaryCareMarkerLimit = 2;
35338            that.primaryCareMarkerErrorLimit = 8;
35339            that.latLngZip = "";
35340            that.locationArray = [];
35341            that.primaryCareMenuListTarget = jQuery(".pc-handlebar-target");
35342            if(callback && typeof callback === 'function') {
35343                callback();
35344            }
35345        });
35346    },
35347    loadNecessaryLibraries: function(callback) {
35348        var that = this;
35349        that.loadGoogleMaps(function() {
35350            that.loadGMaps(callback);
35351        });
35352    },
35353    loadGoogleMaps: function(callback) {
35354        if (!(typeof window.google === 'object' && window.google.maps)) {
35355            var scriptLink = "//maps.googleapis.com/maps/api/js?libraries=weather,geometry&sensor=false&key=" + SHC.util.getGoogleAPIKey();
35356            $.getScript(scriptLink, callback);
35357        } else {
35358            callback();
35359        }
35360    },
35361    loadGMaps: function(callback) {
35362        if(typeof GMaps !== 'object') {
35363            $.getScript('/etc/clientlibs/shc/main/js/vendor/gmaps.js', callback);
35364        } else {
35365            callback();
35366        }
35367    },
35368    // Styles for the map
35369    makeStyles: function () {
35370        return [
35371            {
35372                "featureType": "all",
35373                "elementType": "labels",
35374                "stylers": [
35375                    {"visibility": "off"}
35376                ]
35377            },
35378            {
35379                "featureType": "road",
35380                "elementType": "labels",
35381                "stylers": [
35382                    {"visibility": "on"}
35383                ]
35384            }
35385        ];
35386    },
35387    // Creates a new gmap object
35388    createMap: function (baseLat, baseLng) {
35389        var that = this;
35390        this.gmap = new GMaps({
35391            div: "gmap",
35392            lat: baseLat,
35393            lng: baseLng,
35394            draggable: true,
35395            zoom: this.zoom,
35396            zoomControl: true,
35397            mapTypeControl: false
35398        });
35399
35400        $(window).trigger("gmapDivCreated");
35401
35402        this.gmap.setOptions({
35403            styles: this.styles,
35404            zoomControl: false,
35405            panControl: false,
35406            streetViewControl: false
35407        });
35408
35409        this.zoomInControl = this.gmap.addControl({
35410            content: "<span class=\"gmap-zoom-in\" href=\"#\">Zoom In</span>",
35411            position: "TOP_RIGHT",
35412            events: {
35413                click: function () {
35414                    that.gmap.setZoom(that.gmap.getZoom() + 1);
35415                }
35416            }
35417        });
35418
35419        this.zoomOutControl = this.gmap.addControl({
35420            content: "<span class=\"gmap-zoom-out\" href=\"#\">Zoom Out</span>",
35421            position: "TOP_RIGHT",
35422            events: {
35423                click: function () {
35424                    that.gmap.setZoom(that.gmap.getZoom() - 1);
35425                }
35426            }
35427        });
35428
35429        jQuery(window).on('resizeEnd', function () {
35430            that.adjustMapWindow();
35431            if (this.resizeTO) {
35432                clearTimeout(this.resizeTO);
35433            }
35434            this.resizeTO = setTimeout(function () {
35435                if (SHC.ui.screenMode === 'small') {
35436                    that.setDimensions();
35437                }
35438            }, 100);
35439        });
35440        jQuery(document).ready(function ($) {
35441            setTimeout(function () {
35442                google.maps.event.trigger(this.gmap, 'resize');
35443                google.maps.event.trigger($('#map-display'), 'resize');
35444            }, 100);
35445        });
35446    },
35447    // Adjusts map window so list view is hidden on large and map shows
35448    adjustMapWindow: function () {
35449        if (jQuery(window).width() > 1023) {
35450            jQuery(".menu-target").hide();
35451            jQuery(".marker-menu").removeClass("active");
35452            jQuery(".marker-menu.icon").addClass("active");
35453            jQuery("#map-display").show();
35454        }
35455    },
35456    // Creates a letter marker with a balloon out of json from the map servlet
35457    createBalloonMarker: function (markerJSONChunk, index, type) {
35458        var that = this;
35459        var markerIcon = {url: that.inactiveClinicIcon};
35460        var markerLetter = "";
35461        if (index < 26) {
35462            markerLetter = String.fromCharCode(that.charBase + index);
35463            markerIcon = {url: that.alphabetMarkerIconBasePath + markerLetter + that.markerSuffix};
35464        }
35465        var infoWindowHandlebar = that.loadTemplate(markerJSONChunk, JST["handlebars/info-window-template.hbs"]);
35466        if (type === "primarycare") {
35467            infoWindowHandlebar = that.loadTemplate(markerJSONChunk, JST["handlebars/pc-info-window-template.hbs"]);
35468        }
35469
35470        var infoWindow = {
35471            content: infoWindowHandlebar
35472        };
35473
35474        var lType = "Maps:Pin:" + markerJSONChunk.title;
35475        var markerObject = this.gmap.createMarker({
35476            lat: markerJSONChunk.latitude,
35477            lng: markerJSONChunk.longitude,
35478            infoWindow: infoWindow,
35479            icon: markerIcon,
35480            click: function (e) {
35481                that.setActiveIcon(markerObject);
35482                if (typeof s !== "undefined") {
35483                    scTrackLink(lType, '', {eVar26: lType});
35484                }
35485            }
35486        });
35487        var infoWindowClosed = function () {
35488            var oldIcon = markerObject.getIcon();
35489            oldIcon.size = that.normalSize;
35490            oldIcon.scaledSize = that.normalSize;
35491
35492            markerObject.setIcon(oldIcon);
35493        };
35494        var reinitModal = function () {
35495            var modal = new SHC.ui.Modal(".open-modal-primary-care");
35496        };
35497        if (type === "primarycare") {
35498            google.maps.event.addListener(markerObject.infoWindow, 'domready', reinitModal);
35499        }
35500        google.maps.event.addListener(markerObject.infoWindow, 'closeclick', infoWindowClosed);
35501        return markerObject;
35502    },
35503    // Creates a plain marker out of json from the map servlet
35504    createSimpleMarker: function (markerJSONChunk) {
35505        var that = this;
35506        var markerObject = that.gmap.createMarker({
35507            lat: markerJSONChunk.latitude,
35508            lng: markerJSONChunk.longitude,
35509            clickable: false,
35510            icon: that.activeClinicIcon, // + markerLetter + ".png",
35511        });
35512        return markerObject;
35513    },
35514    createSimpleMarkerAndShow: function(markerJSONChunk) {
35515        var currentMarker = this.createSimpleMarker(markerJSONChunk);
35516        this.buildingArray.push(currentMarker);
35517        this.allMarkersArray.push(currentMarker);
35518        this.showBuildingMarkers();
35519    },
35520    // Creates a parking marker out of json from the map servlet
35521    createParkingMarker: function (markerJSONChunk) {
35522        var that = this;
35523        var markerObject = that.gmap.createMarker({
35524            lat: markerJSONChunk.latitude,
35525            lng: markerJSONChunk.longitude,
35526            clickable: false,
35527            icon: that.activeParkingIcon, // the bigger one since they are always going to look active
35528        });
35529        return markerObject;
35530    },
35531    // Creates a valet marker out of json from the map servlet
35532    createValetMarker: function (markerJSONChunk) {
35533        var that = this;
35534        var markerObject = that.gmap.createMarker({
35535            lat: markerJSONChunk.latitude,
35536            lng: markerJSONChunk.longitude,
35537            clickable: false,
35538            icon: that.activeValetIcon, // the bigger one since they are always going to look active
35539        });
35540        return markerObject;
35541    },
35542    // keeps track of what is the active icon and changing that marker icon
35543    setActiveIcon: function (activeMarker) {
35544
35545        var icon = activeMarker.getIcon();
35546
35547        for (i = 0; i < this.buildingArray.length; i++) {
35548            var oldIcon = this.buildingArray[i].getIcon();
35549            oldIcon.size = this.normalSize;
35550            oldIcon.scaledSize = this.normalSize;
35551
35552            this.buildingArray[i].setIcon(oldIcon);
35553        }
35554        icon.size = this.bigSize;
35555        icon.scaledSize = this.bigSize;
35556
35557        activeMarker.setIcon(icon);
35558    },
35559    setBuildingIcon: function (state) {
35560        jQuery.each(this.buildingArray, function (index, obj) {
35561            // remove the marker
35562            obj.setIcon(state);
35563        });
35564    },
35565    setAllBoundaries: function () {
35566        this.setBoundaries(this.allMarkersArray);
35567    },
35568    setBuildingBoundaries: function () {
35569        this.setBuildingIcon(this.activeClinicIcon);
35570        this.setBoundaries(this.buildingArray);
35571        this.gmap.setZoom(this.zoom);
35572    },
35573    showBuildingMarkers: function () {
35574        this.gmap.addMarkers(this.buildingArray);
35575    },
35576    showParkingMarkers: function () {
35577        this.gmap.addMarkers(this.parkingArray);
35578        this.setBuildingIcon(this.inactiveClinicIcon);
35579    },
35580    showValetMarkers: function () {
35581        this.gmap.addMarkers(this.valetArray);
35582    },
35583    showAllMarkers: function () {
35584        this.gmap.addMarkers(this.allMarkersArray);
35585    },
35586    hideBuildingMarkers: function () {
35587        jQuery.each(this.buildingArray, function (index, obj) {
35588            // remove the marker
35589            obj.setMap(null);
35590        });
35591    },
35592    hideParkingMarkers: function () {
35593
35594        jQuery.each(this.parkingArray, function (index, obj) {
35595            // remove the marker
35596            obj.setMap(null);
35597        });
35598    },
35599    hideValetMarkers: function () {
35600
35601        jQuery.each(this.valetArray, function (index, obj) {
35602            // remove the marker
35603            obj.setMap(null);
35604        });
35605    },
35606    hideAllMarkers: function () {
35607
35608        jQuery.each(this.allMarkersArray, function (index, obj) {
35609            // remove the marker
35610            obj.setMap(null);
35611        });
35612    },
35613    doCampaignRequest: function (campaignName) {
35614        var that = this;
35615        var targetUrl = this.campaignServletRequestPath + campaignName + ".add-clinics.json";
35616
35617        // hit our servlet to give us our info about related l3 clinics
35618        var request = jQuery.ajax({
35619            url: targetUrl,
35620            async: true,
35621            contentType: "application/json"
35622        }).done(function (data) {
35623            //set up our google map using our json
35624            var lat = data.mapaverages[0].avgLat;
35625            var lng = data.mapaverages[0].avgLng;
35626            that.createMap(lat, lng);
35627            //set up marker on the map
35628            jQuery.each(data.maplocations, function (index, chunk) {
35629                var currentMarker = that.createBalloonMarker(chunk, index, "normal");
35630                that.gmap.addMarker(currentMarker);
35631                that.buildingArray.push(currentMarker);
35632                that.allMarkersArray.push(currentMarker);
35633            });
35634            that.showBuildingMarkers();
35635            //set zoom level based on markers
35636            that.setAllBoundaries();
35637            //set up the small info menu with content
35638            that.smallMenuTarget.append(that.loadTemplate(data.maplocations, JST["handlebars/small-info-menu-template.hbs"]));
35639            //bind click behavior that changes the href of the links
35640            //in the info windows to open in multimap modal or page
35641            jQuery('body').off('click.infowindow').on('click.infowindow', '#modal-content a.info-window-modal', function (e) {
35642                //TODO hook history
35643                e.preventDefault();
35644                var href = $(this).attr('href');
35645                var newHref = href.replace('.mapmodal', '.mapmodalcontent');
35646                jQuery('#modal-content').load(newHref);
35647            });
35648
35649            jQuery('body').off('click.dumbthing').on('click.dumbthing', '#modal-content a.back-to-locations-link', function (e) {
35650                //TODO hook history
35651                e.preventDefault();
35652                var href = $(this).attr('href');
35653                var newHref = href.replace('.multimapmodal', '.multi_clinic_map');
35654                jQuery('#modal-content').load(newHref);
35655            });
35656
35657            jQuery('body').on("click", '.marker-menu.hamburger', function () {
35658                jQuery('.menu-buttons').find('a').removeClass('active');
35659                $(this).addClass('active');
35660                that.smallMenuTarget.show();
35661                that.display.hide();
35662            });
35663
35664            jQuery('body').on("click", '.marker-menu.icon', function () {
35665                jQuery('.menu-buttons').find('a').removeClass('active');
35666                $(this).addClass('active');
35667                that.smallMenuTarget.hide();
35668                that.display.show();
35669            });
35670            that.setSideLinks();
35671        });
35672    },
35673    // Does an ajax request to the map servlet to get the l3 json
35674    doL3Request: function (l2Name) {
35675        var that = this;
35676        var targetUrl = this.l3ServletRequestPath + l2Name + ".add-clinics.include-l2.json";
35677
35678        // hit our servlet to give us our info about related l3 clinics
35679        var request = jQuery.ajax({
35680            url: targetUrl,
35681            async: true,
35682            contentType: "application/json"
35683        }).done(function (data) {
35684            //set up our google map using our json
35685            var lat = data.mapaverages[0].avgLat;
35686            var lng = data.mapaverages[0].avgLng;
35687            that.createMap(lat, lng);
35688            //set up marker on the map
35689            jQuery.each(data.maplocations, function (index, chunk) {
35690                var currentMarker = that.createBalloonMarker(chunk, index, "normal");
35691                that.gmap.addMarker(currentMarker);
35692                that.buildingArray.push(currentMarker);
35693                that.allMarkersArray.push(currentMarker);
35694            });
35695            that.showBuildingMarkers();
35696            //set zoom level based on markers
35697            that.setAllBoundaries();
35698            //set up the small info menu with content
35699            that.smallMenuTarget.append(that.loadTemplate(data.maplocations, JST["handlebars/small-info-menu-template.hbs"]));
35700            //bind click behavior that changes the href of the links
35701            //in the info windows to open in multimap modal or page
35702            jQuery('body').off('click.infowindow').on('click.infowindow', '#modal-content a.info-window-modal', function (e) {
35703                //TODO hook history
35704                e.preventDefault();
35705                var href = $(this).attr('href');
35706                var newHref = href.replace('.mapmodal', '.mapmodalcontent');
35707                jQuery('#modal-content').load(newHref, function() {
35708                    if($('.location-page.clinic-mapmodalcontent').length) {
35709                        var officeMarkerPath = $('.location-page.clinic-mapmodalcontent').attr('officeMarkerPath');
35710                        var showLink = true;
35711                        jQuery('.map-target').load(officeMarkerPath + '.html #map-container', function(){
35712                           var locationPage = new SHC.ui.LocationPage(showLink);
35713                        });
35714                    }
35715                });
35716            });
35717
35718            jQuery('body').off('click.dumbthing').on('click.dumbthing', '#modal-content a.back-to-locations-link', function (e) {
35719                //TODO hook history
35720                e.preventDefault();
35721                var href = $(this).attr('href');
35722                var newHref = href.replace('.multimapmodal', '.multi_clinic_map');
35723                jQuery('#modal-content').load(newHref);
35724            });
35725
35726            jQuery('body').on("click", '.marker-menu.hamburger', function () {
35727                jQuery('.menu-buttons').find('a').removeClass('active');
35728                $(this).addClass('active');
35729                that.smallMenuTarget.show();
35730                that.display.hide();
35731            });
35732
35733            jQuery('body').on("click", '.marker-menu.icon', function () {
35734                jQuery('.menu-buttons').find('a').removeClass('active');
35735                $(this).addClass('active');
35736                that.smallMenuTarget.hide();
35737                that.display.show();
35738            });
35739            that.setSideLinks();
35740        });
35741
35742    },
35743    //Ajax request and population of Locations List Component
35744    doLocationListRequest: function (l2Name) {
35745        var that = this;
35746        var targetUrl = this.l3ServletRequestPath + l2Name + ".json";
35747
35748        // hit our servlet to give us our info about related l3 clinics
35749        var request = jQuery.ajax({
35750            url: targetUrl,
35751            async: true,
35752            contentType: "application/json"
35753        }).done(function (data) {
35754            //set up the small info menu with content
35755            that.locationsListTarget.html(that.loadTemplate(data.maplocations, JST["handlebars/practice-locations-list-handlebar.hbs"]));
35756            modal = new SHC.ui.Modal(".open-modal-primary-care");
35757            const isL2Page = document.querySelectorAll('.clinic-l2-page');
35758            if (isL2Page) {
35759                that.makeAppointmentClickEvents();
35760            }
35761        });
35762
35763    },
35764    // Does an ajax request to the map servlet to get the building/parking/valet json
35765    doLocationRequest: function (locationSubpath) {
35766        var that = this;
35767        // ajax to the right thing
35768        var targetUrl = this.locationServletRequestPath + l
35768ocationSubpath + ".json";
35769        var request = jQuery.ajax({
35770            url: targetUrl,
35771            async: true,
35772            contentType: "application/json"
35773        }).done(function (data) {
35774            //set up our google map using our json
35775            // TODO lat and lng of the single building
35776            var lat = data.mainmarker[0].latitude;
35777            var lng = data.mainmarker[0].longitude;
35778            that.createMap(lat, lng);
35779            // create markers
35780            // spin on building, parking, and valet separately
35781            //TODO name these right
35782            jQuery.each(data.mainmarker, function (key, value) {
35783                var currentMarker = that.createSimpleMarker(value);
35784                that.buildingArray.push(currentMarker);
35785                that.allMarkersArray.push(currentMarker);
35786            });
35787            that.showBuildingMarkers();
35788            if (data.parkingmarkers) {
35789                jQuery.each(data.parkingmarkers, function (key, value) {
35790                    var currentMarker = that.createParkingMarker(value);
35791                    that.parkingArray.push(currentMarker);
35792                    that.allMarkersArray.push(currentMarker);
35793                });
35794            }
35795            if (data.valetmarkers) {
35796                jQuery.each(data.valetmarkers, function (key, value) {
35797                    var currentMarker = that.createValetMarker(value);
35798                    that.valetArray.push(currentMarker);
35799                    that.allMarkersArray.push(currentMarker);
35800                });
35801            }
35802            if (jQuery('#modal-content').attr('data-show-links') === 'true') {
35803                jQuery('.back-to-locations').show();
35804                jQuery('.clinic-details-link').show();
35805            }
35806
35807        });
35808    },
35809
35810    //handles Primary Care component close location requests and displays appropriate data
35811    doPrimaryCareRequest: function () {
35812        var that = this;
35813        that.getFormValues();
35814        //get lat and lng from a zip code
35815        var geocoder = new google.maps.Geocoder();
35816        geocoder.geocode({'address': that.primaryCareZipCode}, function (results, status) {
35817            if (status === google.maps.GeocoderStatus.OK) {
35818                //store our geocoded lat/lng from the zip code
35819                that.latLngZip = results[0].geometry.location;
35820                //get our JSON and and manipulate the data to get the closest locations
35821                that.getPrimaryCareJSON(false);
35822            } else {
35823                console.log("Geocode was not successful for the following reason: " + status);
35824            }
35825        });
35826    },
35827
35828    //load infowindow handlebar with ajaxed data
35829    loadTemplate: function (incomingData, template) {
35830        return template(incomingData);
35831    },
35832    //set boundary for zoom level
35833    setBoundaries: function (markerArray) {
35834        var bounds = [];
35835        for (i = 0; i < markerArray.length; i++) {
35836            bounds.push(markerArray[i].getPosition());
35837        }
35838        this.gmap.fitLatLngBounds(bounds);
35839        if (markerArray.length === 1) {
35840            this.gmap.setZoom(this.zoom);
35841        }
35842    },
35843    // when the multimap doL3request function fires it will set this value so
35844    // a normal location page map modal will show the back links
35845    setSideLinks: function () {
35846        jQuery('#modal-content').attr('data-show-links', 'true');
35847    },
35848    setDimensions: function () {
35849        var ratio = this.mapHeight / this.mapWidth;
35850
35851        this.display.height(this.display.width() * ratio);
35852        if (typeof this.gmap !== 'undefined') {
35853            this.gmap.refresh();
35854        }
35855    },
35856
35857    getPrimaryCareJSON: function (doAll) {
35858        var that = this;
35859        var fail;
35860        var lat, lng, modal;
35861        that.primaryCareSelection = that.primaryCareSelection;
35862        var targetUrl = that.primaryCareServletRequestPath + that.primaryCareSelection + ".json";
35863        if (doAll) {
35864            targetUrl = that.primaryCareServletRequestPath + "care-type.json";
35865        }
35866        var distance;
35867        var request = jQuery.ajax({
35868            url: targetUrl,
35869            async: true,
35870            contentType: "application/json"
35871        }).done(function (data) {
35872            if (!doAll) {
35873                //set up our google map using our json
35874                lat = data.mapaverages[0].avgLat;
35875                lng = data.mapaverages[0].avgLng;
35876                that.createMap(lat, lng);
35877
35878                //spin through the chunks one at a time and build a new object key:distance value:chunk
35879                jQuery.each(data.maplocations, function (index, chunk) {
35880                    //check to see if primary care name exists to use instead of the title
35881                    var primaryCareName = chunk.primaryCareName;
35882                    if (primaryCareName.length > 1) {
35883                        //if it's there use it instead of the title
35884                        chunk.title = primaryCareName;
35885                    }
35886                    //get the distance of chunk lat/lng and our zip lat/lng
35887                    distance = that.calculateDistances(chunk);
35888                    distance = distance.toFixed(1);
35889                    //check if our location has the same zip as what was queried
35890                    var inZipInfo = "";
35891                    if (that.primaryCareZipCode === chunk.zipcode) {
35892                        inZipInfo = "in " + that.primaryCareZipCode;
35893                    } else {
35894                        inZipInfo = distance + " miles from " + that.primaryCareZipCode;
35895                    }
35896                    //make new object with clinic info and distance
35897                    var currentObj = {
35898                        distance: distance,
35899                        chunk: chunk,
35900                        inZip: inZipInfo
35901                    };
35902                    that.locationArray.push(currentObj);
35903
35904                });
35905                //sort our array of clinics by distance
35906                that.sortStuff(that.locationArray);
35907
35908                //check the first distance: if >1500 miles, do the 'No Results' logic
35909                var maxDistanceCheck = parseFloat(that.locationArray[0].distance);
35910                if (maxDistanceCheck >= 1500) {
35911                    //do no results logic
35912                    that.primaryCareErrorHandling();
35913                } else {
35914                    //continue as normal
35915                    //set up marker on the map
35916                    jQuery.each(that.locationArray, function (index, newChunk) {
35917                        //remove any results that are > 1500 miles that are not the first result
35918                        var maxDistanceCheckForChunk = parseFloat(newChunk.distance);
35919                        if (maxDistanceCheckForChunk < 1500) {
35920                            //add our marker to the map and add to our marker arrays
35921                            var currentMarker = that.createBalloonMarker(newChunk.chunk, index, "primarycare");
35922                            that.gmap.addMarker(currentMarker);
35923                            that.buildingArray.push(currentMarker);
35924                            that.allMarkersArray.push(currentMarker);
35925                        } else {
35926                            //remove the object from our array so it doesn't show up when loading the handlebar
35927                            that.locationArray.splice(index, 1);
35928                        }
35929                    });
35930                    that.showBuildingMarkers();
35931                    //set zoom level based on markers
35932                    that.setAllBoundaries();
35933
35934                    //set up the small info menu with content show header and buttons
35935                    jQuery(".primary-care-tool .results-top").show();
35936
35937                    that.primaryCareMenuListTarget.html(that.loadTemplate(that.locationArray, JST["handlebars/primary-care-handlebar.hbs"]));
35938                    modal = new SHC.ui.Modal(".open-modal-primary-care");
35939                }
35940
35941            } else {
35942                //set up our google map using our json
35943                lat = data.mapaverages[0].avgLat;
35944                lng = data.mapaverages[0].avgLng;
35945                that.createMap(lat, lng);
35946
35947                //spin through the chunks one at a time and build a new object key:distance value:chunk
35948                //set up marker on the map
35949                jQuery.each(data.maplocations, function (index, chunk) {
35950                    var currentMarker = that.createBalloonMarker(chunk, index, "primarycare");
35951                    that.gmap.addMarker(currentMarker);
35952                    that.buildingArray.push(currentMarker);
35953                    that.allMarkersArray.push(currentMarker);
35954                });
35955                that.showBuildingMarkers();
35956                //set zoom level based on markers
35957                that.setAllBoundaries();
35958
35959                //set up the small info menu with content show header and buttons
35960                jQuery(".primary-care-tool .results-top").show();
35961                that.primaryCareMenuListTarget.html(that.loadTemplate(data, JST["handlebars/primary-care-handlebar-all.hbs"]));
35962                modal = new SHC.ui.Modal(".open-modal-primary-care");
35963            }
35964        }).fail(function () {
35965            that.primaryCareErrorHandling();
35966        });
35967    },
35968
35969    primaryCareErrorHandling: function () {
35970        //switch to list view so error handlebar will show and change classes on menu buttons
35971        jQuery('.primary-care-tool .list-view').removeClass("list-view-off").addClass("list-view-on");
35972        jQuery('.primary-care-tool').find(".map-view").addClass("map-view-off").removeClass("map-view-on");
35973        jQuery('.primary-care-tool').find(".list-results").show();
35974        jQuery('.primary-care-tool').find("#gmap").hide();
35975        //hide normal header and buttons
35976        jQuery(".primary-care-tool .results-top").hide();
35977        this.primaryCareMenuListTarget.html(this.loadTemplate("", JST["handlebars/pc-error-template.hbs"]));
35978    },
35979
35980    calculateDistances: function (chunk) {
35981        var chunkLatLng = new google.maps.LatLng(chunk.latitude, chunk.longitude);
35982        var distance = google.maps.geometry.spherical.computeDistanceBetween(this.latLngZip, chunkLatLng) / 1609.344;
35983        return distance;
35984    },
35985
35986    sortStuff: function (stuff) {
35987
35988        var compareDistances = function (a, b) {
35989            return a.distance - b.distance;
35990        };
35991
35992        stuff.sort(compareDistances);
35993
35994    },
35995
35996    getFormValues: function () {
35997        this.primaryCareZipCode = jQuery("#primary-care-zip-code").val();
35998        var dropdownText = jQuery(".dropdown-title-text").data("node-name");
35999        if (dropdownText === "care-type") {
36000            // TODO something to get all clinics?
36001        }
36002        this.primaryCareSelection = dropdownText;
36003    },
36004    resizeMap: function () {
36005        this.gmap.refresh();
36006        this.setAllBoundaries();
36007
36008    },
36009    makeAppointmentClickEvents: function() {
36010        const makeAppointmentModalButtonLinks = document.querySelectorAll('.clinic-l2-page .practice-locations-list .location-result [data-modalcontainer=".make-an-appt"]');
36011        if (makeAppointmentModalButtonLinks) {
36012            makeAppointmentModalButtonLinks.forEach((appLink) => {
36013                const btnText = appLink.innerText;
36014                appLink.addEventListener("click", function () {
36015                    stanford.analytics.send(stanford.analytics.createComponentClickButton(btnText, "button", 'Make An Appointment'));
36016                });
36017                }
36018            );
36019        }
36020    }
36021});
36022
36023var prevPageName = "";
36024SHC.Namespace(SHC, "SHC.ui.PresentationMode");
36025SHC.ui.PresentationMode = new SHC.Class();
36026SHC.ui.PresentationMode.include({
36027    /*
36028     * constructor
36029     *
36030     * @param handlePop Tells us whether or not to listen for pop state
36031     * @param suppressed if true, do not display.
36032     */
36033    init: function (parent, handlePop, suppressed) {
36034
36035        var isIE = SHC.util.msieVersion();
36036        if (isIE === 8 || isIE === 9) {
36037            return false;
36038        }
36039
36040        this.parent = jQuery(parent);
36041        this.presentation = jQuery("#presentation-mode");
36042
36043        // if browser history is not supported, stop everything
36044        var isSupportedBrowserHistory = function () {
36045            return !!(window.history && history.pushState);
36046        };
36047        if (!isSupportedBrowserHistory) {
36048            //console.log("Browser doesn't support history. Presentation mode disabled.");
36049            return;
36050        }
36051
36052        // if there is no #presentation-mode, stop everything
36053        if (this.presentation.length < 1) {
36054            //console.log("Cannot find #presentation-mode. Presentation mode disabled.");
36055            return;
36056        }
36057
36058        this.handlePop = handlePop;
36059        this.suppressed = suppressed;
36060        this.animationSpeed = 150;
36061        this.close = this.presentation.find(".close");
36062        this.dataPresentationContainerName = "presentation-container";
36063        this.defaultErrorMessage = "We're sorry. There was an error finding your requested content.";
36064        this.main = $("#main");
36065        this.pushUrl = "";
36066        this.inPageNav = $(".inline-nav #inline-nav-cp16");
36067        this.inPageNavMenu = $(".inline-nav #nav_list");
36068        this.inPageNavMobile = $('.small_inline_nav #small_inline_nav');
36069        this.myPlayer = null;
36070        this.presentationContent = this.presentation.find(".presentation-content");
36071        this.scrollPos = 0;
36072        this.urlSelector = ".presentation";
36073        this.urlSuffix = ".html";
36074        this.defaultTarget = ".article-presentation";
36075        this.transcriptLinkClass = ".transcript-trigger";
36076        this.revealBoxClass = ".reveal-box";
36077
36078        this.presentationShare = new SHC.ui.Share(".share");
36079
36080        this.rawUrl = window.location.href;
36081        this.splitUrl = this.rawUrl.split(".html");
36082        if (this.splitUrl.length > 1) {
36083            this.baseUrl = this.splitUrl[0] + ".html";
36084        } else {
36085            this.baseUrl = this.splitUrl[0] + HOME_PAGE_PATH.substring(1) + ".html";
36086        }
36087        this.baseTitle = document.title;
36088
36089        this.mainPageFocus = null;
36090        this.focusableElementsString = "a[href], area[href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), button:not([disabled]), iframe, object, embed, *[tabindex], *[contenteditable]";
36091
36092        // get started
36093        this.activate();
36094    },
36095    /*
36096     * activate the component
36097     */
36098    activate: function () {
36099        var _this = this;
36100
36101        if (typeof _satellite !== 'undefined' && typeof _satellite.getVar !== 'undefined') {
36102            prevPageName = _satellite.getVar('Page Name');
36103        }
36104        // handle .presentation-mode anchor clicks
36105        var handleOpenClick = function (e) {
36106            e.preventDefault();
36107            // get href from clicked link and check its validity
36108            // if it's invalid, stop here
36109            var url = jQuery(this).attr("data-href") || jQuery(this).attr("href");
36110            _this.pushUrl = "";
36111
36112            // save main page focus so we can pick up where we left off
36113            _this.mainPageFocus = $(document.activeElement);
36114
36115            // remove any hashtags... they don't let us fetch our content
36116            url = url.replace("#", "");
36117
36118            if (url === undefined || url === "#" || url === "" || url.indexOf(_this.urlSuffix, url.length - _this.urlSuffix.length) === -1) {
36119                //console.log("ERROR: Invalid href for presentation mode.");
36120                return;
36121            } else {
36122                // check for and remove any domain in the url
36123                url = url.replace(/^.*\/\/[^\/]+/, "");
36124
36125                // add selector to url
36126                url = url.substring(0, url.length - _this.urlSuffix.length);
36127                url = url + _this.urlSelector + _this.urlSuffix;
36128            }
36129
36130            // get target-container
36131            var target = jQuery(this).data(_this.dataPresentationContainerName);
36132
36133            // save current scroll position
36134            _this.scrollPos = $(window).scrollTop();
36135
36136            // show presentation mode
36137            _this.showPresentationMode(url, target);
36138
36139            // create new URL for window.history.pushState
36140            _this.rawUrl = window.location.href;
36141            pushUrl = _this.baseUrl + "/presentation-mode" + url;
36142            pushUrl = pushUrl.replace(".presentation.html", "");
36143
36144            // push new URL to history
36145            history.pushState({ "path": pushUrl }, "", pushUrl);
36146
36147            _this.presentationShare.updateShareHrefs({ enterPresentation: true });
36148
36149            //set the proper page name for SiteCat
36150            if (typeof dl !== "undefined") {
36151                dl.methods.setPageName();
36152                dl.methods.setSiteCatInfo(true);
36153            }
36154
36155            if (typeof _satellite !== 'undefined' && typeof _satellite.getVar !== 'undefined') {
36156                document.cookie = "presentationPageName=" + _satellite.getVar('Page Name') + "; path=/";
36157            }
36158
36159        };
36160
36161        // handle close button clicks
36162        var handleCloseClick = function (e) {
36163            e.preventDefault();
36164            _this.pushUrl = "";
36165
36166            if (_this.baseUrl.replace(/^.*\/\/[^\/]+/, "") === HOME_PAGE_PATH + ".html") {
36167                var path = _this.baseUrl.replace(HOME_PAGE_PATH + ".html", "/");
36168                path = path.replace(".presentation.html", "");
36169                history.pushState({ "path": path }, "", path);
36170            } else {
36171                var oldPath = window.location.href;
36172                oldPath = oldPath.replace(".presentation.html", "");
36173                history.pushState({ "path": oldPath }, "", _this.rawUrl);
36174            }
36175
36176            _this.presentationShare.updateShareHrefs({ enterPresentation: false });
36177
36178            _this.hidePresentationMode(true);
36179            _this.grantMainPageAccess();
36180            // null, undefined, 0 and ""
36181            if (_this.mainPageFocus) {
36182                _this.mainPageFocus.focus();
36183            }
36184            // refresh scrollspy upon exiting
36185            if (SHC.ui.InPageNavigation && typeof SHC.ui.InPageNavigation.scrollSpyRefresh === "function") {
36186                SHC.ui.InPageNavigation.scrollSpyRefresh();
36187            }
36188
36189            //Hides inpage-nav when presentation mode is closed
36190            if (_this.inPageNav.length > -1) {
36191                if (SHC.ui.screenMode !== 'small') {
36192                    _this.inPageNavMenu.css("display", "block");
36193                    _this.inPageNav.css("display", "block");
36194                } else {
36195                    _this.inPageNavMobile.css("display", "block");
36196                }
36197            }
36198            if(window.YTPlayer) {
36199                window.YTPlayer.onPlayerEnd();
36200            }
36201
36202        };
36203
36204        var handlePopState = function (e) {
36205            e.preventDefault();
36206            //to fix the anchor tags not working we do not want to set
36207            //the page behind presentation mode state at this time so we
36208            //pass it false to prevent this behavior
36209            if (window.location.href.indexOf("presentation-mode") === -1) {
36210                _this.hidePresentationMode(false);
36211            }
36212            var newUrl = window.location.href;
36213            _this.checkForRequestedPresentation(newUrl);
36214            _this.grantMainPageAccess();
36215            if (_this.mainPageFocus) {
36216                _this.mainPageFocus.focus();
36217            }
36218        };
36219
36220        // setup listeners
36221        _this.parent.off("click.openPresentationMode").on("click.openPresentationMode", handleOpenClick);
36222        _this.close.off("click.closePresentationMode").on("click.closePresentationMode", handleCloseClick);
36223        if (_this.handlePop) {
36224            $(window).off("popstate.presentationMode").on("popstate.presentationMode", handlePopState);
36225        }
36226
36227        // check for any presentation requests from URL
36228        _this.checkForRequestedPresentation(_this.rawUrl);
36229    },
36230    /*
36231     * check to see a presentation has been requested through url
36232     */
36233    checkForRequestedPresentation: function (url) {
36234
36235        // remove any hashtags... they don't let us fetch our content
36236        url = url.replace("#", "");
36237
36238        // BE SURE WE HAVE A VALID PATH
36239        var urlSplit = url.split(".html");
36240        if (urlSplit.length <= 1 || urlSplit[1].length <= 0) {
36241            //console.log("ERROR: Invalid path provided for presentation mode. (.html)");
36242            return;
36243        }
36244        urlSplit = urlSplit[1].split("/presentation-mode");
36245        if (urlSplit.length <= 1 || urlSplit[1].length <= 0) {
36246            //console.log("ERROR: Invalid path provided for presentation mode. (/presentation-mode)");
36247            return;
36248        }
36249
36250        var path = urlSplit[1];
36251
36252        // if suppressed == true, do not show.
36253        if (!this.suppressed) {
36254            this.showPresentationMode(path + ".presentation.html", this.defaultTarget);
36255        }
36256    },
36257    /*
36258     * show presentation mode
36259     */
36260    showPresentationMode: function (url, target) {
36261        //console.log("Function showPresentationMode() called.");
36262
36263        var _this = this;
36264
36265        // reset
36266        _this.reset();
36267
36268        this.main.hide();
36269
36270        // the fixed positon helps get rid of any jumpiness in animations and scrolling... leave it there
36271        _this.presentation.css("position", "fixed").fadeIn(_this.animationSpeed, function () {
36272
36273            // scroll to top
36274            $(window).scrollTop(0);
36275
36276            // remove the fixed position on the presentation
36277            // replace with absolute position
36278            _this.presentation.css("position", "absolute");
36279
36280            // go get the presentation data
36281            _this.getPresentationData(url, target);
36282        });
36283
36284        //Shows inpage-nav when presentation mode is opened
36285        if (_this.inPageNav.length > -1) {
36286            if (SHC.ui.screenMode !== 'small') {
36287                _this.inPageNavMenu.css("display", "none");
36288                _this.inPageNav.css("display", "none");
36289            } else {
36290                _this.inPageNavMobile.css("display", "none");
36291            }
36292        }
36293    },
36294    /*
36295     * close presentation mode
36296     * rememberPagePosition is for when presentation mode closes
36297     * the page behind it is shown at the previously left off spot
36298     * This option is a fix for the anchor tags not working.  
36299     */
36300    hidePresentationMode: function (rememberPagePosition) {
36301        // fade out presentation mode
36302        // hiding presentationContent eliminates some choppiness in the fadeOut... leave it there
36303        var presentationShareOnClose = new SHC.ui.Share('.share');
36304        var presentationInlineShareOnClose = new SHC.ui.InlineShare('.share-inline');
36305        this.reset();
36306        this.presentationContent.hide();
36307        this.presentation.fadeOut(this.animationSpeed);
36308        this.main.show();
36309
36310        // revert to saved scroll position if we choose to
36311        if (rememberPagePosition) {
36312            $(window).scrollTop(this.scrollPos);
36313        }
36314        $("body").removeClass("presenting");
36315
36316        document.title = this.baseTitle;
36317        //setting the proper page name for SiteCat
36318        if (typeof dl !== "undefined") {
36319            dl.methods.setPageName();
36320            if (typeof dl.methods.readCookie === 'function'
36321                && typeof (dl.methods.readCookie(dl.content.cookieName)) !== 'undefined') {
36322                dl.methods.deleteCookie(dl.content.cookieName);
36323                dl.content.currentCookie = null;
36324            }
36325        }
36326    },
36327    /*
36328     * get presentation mode content from targeted container of url
36329     */
36330    getPresentationData: function (url, target) {
36331        var _this = this;
36332        // if the page url has /content/shc/en but the path doesn't, add it
36333        if (_this.rawUrl.indexOf(HOME_PAGE_PATH) !== -1 && url.indexOf(HOME_PAGE_PATH) === -1) {
36334            url = HOME_PAGE_PATH + url;
36335        }
36336        var presentationSourceUrl = url.replace('.presentation', '');
36337
36338        // ajax the content
36339        jQuery.ajax({
36340            url: url,
36341            context: document.body
36342        }).error(function (data) {
36343            console.log("Error during ajax request." + url);
36344            _this.showErrorMessage();
36345        }).done(function (data) {
36346            // get targeted data
36347            var html = $("<div />").append(data).find(target);
36348
36349            // hide presentation content
36350            _this.presentationContent.fadeOut(_this.animationSpeed, function () {
36351
36352                // append targeted data
36353                _this.presentationContent.empty().append(html).each(function () {
36354                    if (typeof onYouTubeIframeAPIReady !== 'undefined' && jQuery.isFunction(onYouTubeIframeAPIReady) && window.YT && window.YT.Player) {
36355                        onYouTubeIframeAPIReady();
36356
36357                    }
36358                    var title = $(_this.defaultTarget).data("title"),
36359                        metaTwitterTitle = jQuery("meta[name='twitter:title']");
36360                    document.title = title;
36361                    metaTwitterTitle.attr("content", title);
36362
36363                    // imagewithcaption (show image on load)
36364                    $(".presentation-content div[data-picture]").each(function () {
36365                        var currentPicture = this;
36366                        var currentWidth = SHC.ui.viewportWidth;
36367                        var picImg = $(currentPicture).find("img").first();
36368                        var matches = [];
36369                        $("div[data-media]", currentPicture).each(function () {
36370                            var media = $(this).attr("data-media");
36371                            media = media.replace("(min-width:", "");
36372                            media = media.replace("px)", "");
36373
36374                            if (media < currentWidth) {
36375                                matches.push(this);
36376                            }
36377                        });
36378                        if (matches.length) {
36379                            if (picImg.size() === 0) {
36380                                var $currentPicture = $(currentPicture);
36381                                picImg = $("<img />").attr("alt", $currentPicture.attr("data-alt")).appendTo($currentPicture);
36382                            }
36383                            picImg.attr("src", matches.pop().getAttribute("data-src"));
36384                        } else {
36385                            picImg.remove();
36386                        }
36387                    });
36388
36389                    // retrieve source meta data
36390                    _this.copyRemoteMetaInfo(presentationSourceUrl + " meta");
36391                    // fade in new content
36392                    _this.presentationContent.fadeIn(_this.animationSpeed, function () {
36393                        //set focus after everything is visible
36394                        _this.setFocus();
36395                        window.initializeDownloadAssetButton();
36396                    });
36397
36398                    // initialize youtube only if there is a player in the presentation content
36399                    if(window.YTPlayer && $('.presentation-content #presentation-player').length > 0) {
36400                   		 window.YTPlayer.init(window.YTPlayer.$node, window.YTPlayer.options);
36401                    }
36402                });
36403            });
36404        });
36405    },
36406
36407    copyRemoteMetaInfo: function (selector) {
36408        $('<div/>').load(selector, function () {
36409            var filter = 'meta[name="twitter:description"],meta[name="twitter:name"]',
36410                matched = $(this).find(filter),
36411                shareData = $('#presentation-mode .share-data');
36412            shareData.append($(matched));
36413            var presentationShareOnOpen = new SHC.ui.Share('.share');
36414            var presentationInlineShareOnClose = new SHC.ui.InlineShare('.share-inline');
36415        });
36416    },
36417
36418    //limits focusable items to presentation mode (can't select main page with keys)
36419    restrictMainPageAccess: function () {
36420        this.main.attr('aria-hidden', 'true');
36421        this.presentation.attr('aria-hidden', 'false');
36422    },
36423
36424    //reinstates main page items as the focusable group
36425    grantMainPageAccess: function () {
36426        this.main.attr('aria-hidden', 'false');
36427        this.presentation.attr('aria-hidden', 'true');
36428    },
36429
36430    //used for AA compliance for people with disabilities
36431    //sets focus to the first focusable element in presentation mode
36432    setFocus: function () {
36433        this.restrictMainPageAccess();
36434        var objectList = this.presentation.find('*');
36435        objectList.filter(this.focusableElementsString).filter(':visible').first().focus();
36436    },
36437
36438    /*
36439     * reset presentation content with loader
36440     */
36441    reset: function () {
36442        delete this.myPlayer;
36443
36444        // empty presentationContent, create and append spinner
36445        var spinner = '<div class="spinner-container">' +
36446            '<div class="floatingBarsG">' +
36447            '<div class="blockG rotateG_01"></div>' +
36448            '<div class="blockG rotateG_02"></div>' +
36449            '<div class="blockG rotateG_03"></div>' +
36450            '<div class="blockG rotateG_04"></div>' +
36451            '<div class="blockG rotateG_05"></div>' +
36452            '<div class="blockG rotateG_06"></div>' +
36453            '<div class="blockG rotateG_07"></div>' +
36454            '<div class="blockG rotateG_08"></div>' +
36455            '</div>' +
36456            '</div>';
36457
36458        this.presentationContent.empty().append(spinner).show();
36459    },
36460    /*
36461     * display any error messages
36462     */
36463    showErrorMessage: function (message) {
36464        // get appropriate error message
36465        message = typeof message !== "undefined" ? message : this.defaultErrorMessage;
36466
36467        // display error message
36468        this.presentationContent.empty().append("<p class=\"error\">" + message + "</p>");
36469    }
36470});
36471
36472jQuery(function () {
36473    if (jQuery("#presentation-mode").length) {
36474        var presentationMode = new SHC.ui.PresentationMode(".presentation", true);
36475    }
36476});
36477
36478SHC.Namespace(SHC, "SHC.ui.Modal");
36479SHC.ui.FeedbackModal = new SHC.Class(SHC.ui.Modal);
36480
36481SHC.ui.FeedbackModal.include({
36482
36483    init: function (parent, initObject) {
36484        var that = this;
36485        this.feedbackToken = null;
36486        this.serviceUrl = "/bin/api/feedback.json";
36487        if (initObject) {
36488            this.messages = initObject;
36489        }
36490        this.messages.sendingText = "Sending your feedback . . .";
36491        this.messages.invalidFormText = "Please provide your email address and comment.";
36492        this.compiledTemplate = JST["handlebars/siteFeedbackTemplate.hbs"];
36493        this.setupFeedbackTab();
36494        // perform parent initialization
36495        SHC.ui.Modal.prototype.init.apply(this, arguments);
36496        return this;
36497    },
36498
36499    setupFeedbackTab: function() {
36500        var that = this,
36501            reviewCookie = SHC.util.getCookie("review"),
36502            feedbackDiv = $("#feedbackTab");
36503
36504        if (reviewCookie && feedbackDiv.length>0) {
36505            var feedbackTab = "<div class='feedbackTab'>"
36506                + "<a href='#' class='open-handlebar-modal'>Provide Feedback</a>"
36507                + "&nbsp;&nbsp;"
36508                + "[<a href='#' class='delete-review' title='Delete this Review ID cookie.'>delete</a>]"
36509                + "</div>";
36510
36511            feedbackDiv.append($(feedbackTab));
36512            var deleteHandler = function(e){
36513                e.preventDefault();
36514                // delete immediately
36515                // attribs must match path and domain in ReviewSessionFilter.java
36516                document.cookie='review=; Path=/; Domain=.stanfordhealthcare.org; Expires=Thu, 01 Jan 1970 00:00:01 GMT;';
36517                that.feedbackInfo = null;
36518                $(".feedbackTab").fadeOut();
36519                return false;
36520            };
36521            this.deleteButton = $(".delete-review");
36522            this.deleteButton.on("click", deleteHandler);
36523        }
36524    },
36525    // parent override: simply attach click handlers for scanned
36526    // .open-handlebar-modal links.
36527    setupModal: function (modal) {
36528        var modalLink = $(modal),
36529            that = this;
36530        modalLink.on('click', function(e){
36531            that.onLinkClickHandler(e);
36532        });
36533    },
36534
36535     validateToken: function(token) {
36536         // validate token.
36537         if (token && token.match(/\{[0-9a-fA-F]+\}/)) {
36538             this.feedbackToken = token;
36539         } else {
36540             this.feedbackToken = null;
36541         }
36542    },
36543
36544    validateForm: function() {
36545        var emailRegExp = /^\w+@[a-zA-Z0-9_]+?\.[a-zA-Z]{2,3}$/,
36546            email = $.trim($("#feedbackEmail").val()),
36547            comment = $.trim($("#feedbackComment").val());
36548        if (email.match(emailRegExp) && comment) {
36549            return true;
36550        } else {
36551            return false;
36552        }
36553    },
36554
36555    showFeedbackForm: function() {
36556        var that = this;
36557        if (!this.preventClickiness) {
36558            this.preventClickiness = true;
36559
36560            // static call
36561            try {
36562                if (SHC && SHC.ui.Masthead &&
36563                    typeof SHC.ui.Masthead.fn.closeMenu === 'function') {
36564                    SHC.ui.Masthead.fn.closeMenu();
36565                    this.positionModalOnResize();
36566                }
36567            } catch (e) {
36568            }
36569            this.clearModalContent();
36570            var defaultFormData = {
36571                "feedbackEnteredUrl" : window.location.href,
36572                "mainHeader": this.messages.mainHeader,
36573                "modalHeader": this.messages.modalHeader,
36574                "modalBody": this.messages.modalBody,
36575                "pageTitle": $("title").text()
36576            };
36577            if (this.feedbackInfo) {
36578                var fi = this.feedbackInfo;
36579                defaultFormData.reviewerName = fi.reviewerName;
36580                defaultFormData.reviewerEmail = fi.reviewerEmail;
36581                defaultFormData.requestorName = fi.requestorName;
36582                defaultFormData.requestorEmail = fi.requestorEmail;
36583            }
36584            var jqObject = $(this.compiledTemplate(defaultFormData));
36585            jqObject.find('form[name="feedbackform"]')
36586                .submit(function(){
36587                    if (that.validateForm()) {
36588                        that.submitForm();
36589                    } else {
36590                        jQuery("#feedbackErrorMessage").text(that.messages.invalidFormText);
36591                    }
36592                    return false;
36593                });
36594
36595            // is our token null?
36596            if (this.feedbackToken) {
36597                jqObject.appendTo(this.modalContent);
36598            } else {
36599                this.setContent(this.messages.serverDownText);
36600            }
36601            this.modalContainer.show();
36602            this.getWindowProperties();
36603            this.positionModalOffPage();
36604        }
36605    },
36606
36607    onLinkClickHandler: function(evt) {
36608        if (evt) {
36609            evt.preventDefault();
36610        }
36611        var that = this;
36612        if (!this.feedbackToken) {
36613            this.getToken(function(){
36614                that.showFeedbackForm();
36615            });
36616        } else {
36617            this.showFeedbackForm();
36618        }
36619    },
36620
36621    getToken: function(successCallback) {
36622        var that = this;
36623        var errorHandler = function(data) {
36624                that.setContent(that.messages.serverDownText);
36625                that.feedbackToken = null;
36626                that.showFeedbackForm();
36627        };
36628        $.ajax({
36629            type: "GET",
36630            url: that.serviceUrl,
36631            data: {"action":"getToken"},
36632            dataType: "json",
36633            cache: false,
36634            success: function (data) {
36635                if (data && data.success === "true") {
36636                    that.validateToken(data.userToken);
36637                    if (that.feedbackToken &&
36638                        successCallback &&
36639                        typeof successCallback === "function") {
36640                        that.feedbackInfo = {
36641                          reviewerName: data.reviewerName,
36642                          reviewerEmail: data.reviewerEmail,
36643                          requestorName: data.requestorName,
36644                          requestorEmail: data.requestorEmail
36645                        };
36646                        successCallback(data.userToken);
36647                    } else {
36648                        errorHandler(data);
36649                    }
36650                } else {
36651                    errorHandler(data);
36652                }
36653            },
36654            error: errorHandler
36655        });
36656    },
36657
36658    submitForm: function () {
36659        var that = this,
36660            feedbackData = {
36661            "feedbackEmail": $.trim($("#feedbackEmail").val()),
36662            "feedbackUsername": $("#feedbackUsername").val(),
36663            "feedbackComment": $.trim($("#feedbackComment").val()),
36664            "feedbackEnteredUrl": $("#feedbackEnteredUrl").val(),
36665            "feedbackBrowserUrl": (window.location.href || window.location.pathname),
36666            "feedbackUserAgent": navigator.userAgent,
36667            "feedbackToken" : that.feedbackToken,
36668            "review": SHC.util.getCookie("review"),
36669            "pageTitle": $("title").text(),
36670            "action": "postIssue"
36671        };
36672        var onSubmitFailed = function(data) {
36673            // console.log("failed", data);
36674            that.setContent(that.messages.submitFailedText);
36675            return false;
36676        };
36677
36678        this.setContent(this.messages.sendingText);
36679
36680        // send it out ..
36681        $.ajax({
36682            type: "POST",
36683            url: this.serviceUrl,
36684            data: feedbackData,
36685            dataType: "json",
36686            cache: false,
36687            success: function (data) {
36688                if (data && data.success === "true") {
36689                    that.setContent(that.messages.thankYouText);
36690                } else {
36691                    onSubmitFailed(data);
36692                }
36693                return false;
36694            },
36695            error: onSubmitFailed
36696        });
36697    },
36698
36699    setContent: function(content) {
36700        this.modalContent.html(content);
36701    }
36702});
36703SHC.Namespace(SHC, "SHC.ui.Disclaimer.Redirect");
36704SHC.ui.Disclaimer.Redirect = new SHC.Class();
36705
36706SHC.ui.Disclaimer.Redirect.include({
36707    /*
36708     constructor
36709     */
36710    init: function(disclaimerPath, currentPath) {
36711        this.disclaimerPath = disclaimerPath;
36712        this.currentPath = currentPath;
36713        this.checkDisclaimerCookie(); 
36714    },
36715    getDisclaimerCookie: function(disclaimerStatus) {
36716        var getStatus = disclaimerStatus + "=";
36717        var ca = document.cookie.split(';');
36718        for (var i = 0; i < ca.length; i++) {
36719            var c = $.trim(ca[i]);
36720            if (c.indexOf(getStatus) === 0) {
36721                return c.substring(getStatus.length, c.length);
36722            }
36723        }
36724        return "";
36725    },
36726    checkDisclaimerCookie: function() {
36727        var status = this.getDisclaimerCookie("disclaimer");
36728        if (status !== "true") {
36729            window.location.replace(this.disclaimerPath + "?url=" + this.currentPath);
36730        } else {
36731            $("body").removeClass("invisible");
36732        }
36733    }
36734});
36735/**
36736 *
36737 * Sitewide onLoad handler to replace previously inlined JavaScript.
36738 *
36739 * NOTE:
36740 * We need to wrap these sections with reasonable sanity checks
36741 * so that we only run the sections when we're sure the targeted
36742 * elements are really on the page.
36743 *
36744 * Dependencies:
36745 * SHC.util
36746 * SHC.ui.Map
36747 * SHC.ui.LocationPage
36748 *
36749 */
36750
36751jQuery(function(){
36752    // .multimapmodal. selector
36753    if (SHC.util.hasSelector("multimapmodal", window.location.pathname) &&
36754        jQuery(".clinic-multi-clinic-map").length>0) {
36755        var requestPath = jQuery(".clinic-multi-clinic-map").attr("requestPath");
36756        if (requestPath) {
36757            var subpaths = requestPath.split("/"),
36758                section = subpaths[subpaths.length-2],
36759                map = new SHC.ui.Map();
36760            map.doL3Request(section);
36761        }
36762    }
36763
36764    // .mapmodal. selector
36765    if (SHC.util.hasSelector("mapmodal", window.location.pathname) &&
36766        jQuery(".map-target").length>0) {
36767        var officeMarkerPath = jQuery(".clinic-mapmodalcontent").attr("officeMarkerPath");
36768        if (officeMarkerPath) {
36769            jQuery(".map-target").load(officeMarkerPath+".html #map-container", function(){
36770              var locationPage = new SHC.ui.LocationPage(true);
36771            });
36772        }
36773    }
36774});
36775SHC.Namespace(SHC, "SHC.ui.DrMakeAnAppt");
36776SHC.ui.DrMakeAnAppt = new SHC.Class();
36777
36778SHC.ui.DrMakeAnAppt.include({
36779
36780    init: function() {
36781        this.modalLoadedEvent = 'doctorMakeApptModalLoaded';
36782        this.setupModals();
36783        if(!(SHC.ui.DrMakeAnAppt.modalEventsBound)) {
36784            this.bindEvents();
36785        }
36786        this.selectTitle = null;
36787        this.modal = null;
36788    },
36789    setupModals: function() {
36790        // prevent multiple setups upon pagination in the directory
36791        SHC.ui.modalInstance = new SHC.ui.Modal('.search-results-list .make-appointment-btn.open-modal', this.modalLoadedEvent);
36792    },
36793    loadSelectedClinicContent: function(context) {
36794        var selectedVal;
36795        if(this.selectTitle.length > 0 && this.selectTitle !== null) {
36796            selectedVal = this.selectTitle.data("selectedOption");
36797        }
36798        else {
36799            selectedVal = '0';
36800        }
36801
36802        context.loadLeftSideContent(selectedVal);
36803        context.loadRightSideContent(selectedVal);
36804        if($('.google-maps').length === 0) {
36805            this.createVerticalRule();
36806        }
36807        context.loadBottomRowContent(selectedVal);
36808    },
36809    loadLeftSideContent: function(selectedVal) {
36810        // empty the current content and load the new content
36811        $('.selected-clinic-info-content').empty();
36812        $('.hidden-left-content .clinic-location-info.office-' + selectedVal).clone().appendTo( '.selected-clinic-info-content');
36813
36814        // get the div containing the selected map information (lattitude, longitude, etc.)
36815        var selectedMap = $('.hidden-left-content .clinic-map-info.office-' + selectedVal);
36816        // load the map into the left hand side
36817        if(selectedMap.length > 0) {
36818            var map = new SHC.ui.Map(function() {
36819                $('#dr-make-appt-modal #gmap').empty();
36820                map.createMap(selectedMap.attr('office-lat'), selectedMap.attr('office-long'));
36821
36822                var officeLoc = {latitude: selectedMap.attr('office-lat'), longitude: selectedMap.attr('office-long')};
36823                map.createSimpleMarkerAndShow(officeLoc);
36824            });
36825        }
36826    },
36827    loadRightSideContent: function(selectedVal) {
36828        // empty the current content and load the new content
36829        $('.selected-make-appt-content').empty();
36830        $('.hidden-right-content .clinic-appt-info.office-' + selectedVal).clone().appendTo( '.selected-make-appt-content');
36831    },
36832    loadBottomRowContent: function(selectedVal) {
36833        // empty the current content and load the new content
36834        $('.additional-phone-numbers-center').empty();
36835        $('.hidden-center-content .additional-phones-for-office-' + selectedVal).clone().appendTo('.additional-phone-numbers-center');
36836    },
36837    bindEvents: function() {
36838        var that = this;
36839        $(window).on(this.modalLoadedEvent, function() {
36840            var $selectBox = $('#dr-make-appt-modal .select-box');
36841            var $selectGroup = $('#dr-make-appt-modal .select-group');
36842            that.selectTitle = $('#dr-make-appt-modal .select-title');
36843            var selectedId = $('#dr-make-appt-modal .select-title').data("clinic-index");
36844            var selectedClinicName = $('#dr-make-appt-modal .select-title').text();
36845            var clinicPassThroughInfo = SHC.util.getClinicPassThroughInfo();
36846            if (clinicPassThroughInfo.clinicName) {
36847                var selectedVal = '0';
36848                $.each($('.clinic-select li'), function (i, elem){
36849                    if ($(elem).text() === clinicPassThroughInfo.clinicName){
36850                        selectedId = $(elem).data("clinic-index");
36851                        selectedClinicName = $(elem).text();
36852                        return false;
36853                    }
36854                });
36855                that.selectTitle.text(selectedClinicName);
36856            }
36857            that.selectTitle.data("selectedOption", selectedId);
36858            that.loadSelectedClinicContent(that);
36859            // opening/closing the dropdown
36860            $selectBox.click(function() {
36861                $selectGroup.toggleClass('visible');
36862            });
36863            // clicking on dropdown options
36864            $('.clinic-select li').click(function() {
36865                that.selectTitle.text($(this).text());
36866                that.selectTitle.data("selectedOption", $(this).data("clinic-index"));
36867                $selectGroup.toggleClass('visible');
36868                that.loadSelectedClinicContent(that);
36869            });
36870
36871            var $drMakeApptInfo = $('.dr-make-appt-info.row');
36872            var $drMakeApptCall = $('.dr-make-appt-call.row');
36873
36874            //clicking on "next" button
36875            $('.dr-appt-next-button-wrapper .dr-appt-next-button').click(function() {
36876                $drMakeApptInfo.css('display','none');
36877                $drMakeApptCall.css('display','block');
36878            });
36879
36880            //clicking on "change clinic" link
36881            $('.dr-make-appt-call .change-clinic-link').click(function() {
36882                $drMakeApptCall.css('display','none');
36883                $drMakeApptInfo.css('display','block');
36884            });
36885        });
36886
36887        $(window).on("gmapDivCreated", function() {
36888           that.createVerticalRule();
36889        });
36890
36891        SHC.ui.DrMakeAnAppt.modalEventsBound = true;
36892    },
36893    createVerticalRule: function() {
36894        var $leftHandCol = $('.make-an-appt-left');
36895        var $rightHandCol = $('.make-an-appt-right');
36896
36897        //remove old border if there is one
36898        $leftHandCol.removeClass('taller-column');
36899        $rightHandCol.removeClass('taller-column');
36900
36901        if($leftHandCol.height() > $rightHandCol.height()) {
36902            $leftHandCol.addClass('taller-column');
36903        }
36904        else {
36905            $rightHandCol.addClass('taller-column');
36906        }
36907    }
36908});
36909SHC.Namespace(SHC, "SHC.ui.ProcessCircles");
36910SHC.ui.ProcessCircles = new SHC.Class();
36911SHC.ui.ProcessCircles.include({
36912    /*
36913     * constructor
36914     */
36915    init: function(parent) {
36916        var that = this;
36917        this.parent = jQuery(parent);
36918        this.circlesList = this.parent.find('.process-circles-list-container .process-circles-list');
36919        this.calloutContent = this.parent.find('.process-circle-content-container .callout-content');
36920        this.calloutArrow = this.parent.find('.process-circle-content-container .callout-arrow');
36921        this.mobileTabs = this.parent.find('.process-circles-mobile .mobile-tab-list');
36922        this.mobileTabContainer = this.mobileTabs.find('.mobile-tab-container');
36923        this.navAnimateSpeed = 400;
36924        this.activate();
36925    },
36926    activate: function(){
36927        this.setProcessCircleClickListener();
36928        this.setMobileTabsListener();
36929        var that = this;
36930    },
36931    setProcessCircleClickListener: function(){
36932        var that = this;
36933        $(that.circlesList).find('li').on('click', function(e){
36934            //circle activation
36935            var circleTabClicked = $(this);
36936            var circleCurrentActive = $(this).siblings('.active');
36937            circleCurrentActive.removeClass('active');
36938            circleTabClicked.addClass('active');
36939
36940            //circle callout arrow
36941            var oldPositionClass = that.calloutArrow[0].className.split(' ')[1];
36942            var numberOfCircles = that.circlesList.attr('class').split(' ')[1].split('circles')[1];
36943            var newPositionClass = 'callout-pos-' + numberOfCircles + '-' +circleTabClicked.attr('class').substring(20,21);
36944
36945            that.calloutArrow.removeClass(oldPositionClass);
36946            that.calloutArrow.addClass(newPositionClass);
36947
36948            //circle content
36949            var showContentSelector = ".circle-content.circle_" + circleTabClicked.attr('name');
36950            that.calloutContent.find('.content-show').removeClass('content-show').addClass('content-hide');
36951            that.calloutContent.find(showContentSelector).removeClass('content-hide').addClass('content-show');
36952
36953            if($('.ease-of-access').size() > 0) {
36954                new SHC.ui.EaseOfAccess();
36955            }
36956        });
36957    },
36958    setMobileTabsListener: function(){
36959        var that = this;
36960
36961        that.mobileTabContainer.find('.circle_title').on('click',function(){
36962            MobileTabOpener(this);
36963        });
36964
36965        that.mobileTabContainer.find('.close-tab').on('click',function(){
36966            MobileTabCloser(this);
36967        });
36968
36969        //function for opening process circles on mobile
36970        MobileTabOpener = function(that){
36971            var clicked = $(that);
36972            var previousClicked = clicked.closest('.process-circles-mobile').find('.circle_title.active');
36973
36974            //check if the clicked object is already open
36975            if(clicked.attr('class').indexOf('active') === -1) {
36976                var tabCaratClass = 'tab-carat-circle-';
36977                if (clicked.find('.tab-carat').attr('class').indexOf('tab-carat-tab-') > -1){
36978                    tabCaratClass = 'tab-carat-tab-';
36979                }
36980
36981                // see if another circle is open
36982                if (previousClicked.length > 0){
36983                    MobileTabCloser(previousClicked.siblings().find('.close-tab'));
36984                }
36985                clicked.find('.tab-carat').removeClass(tabCaratClass + 'close').addClass(tabCaratClass + 'open');
36986
36987                clicked.siblings().slideDown(that.navAnimateSpeed, function() {
36988                    clicked.addClass('active');
36989                    $('html, body').animate({
36990                        scrollTop: clicked.offset().top
36991                    }, 500);
36992                });
36993            }
36994            else{
36995                MobileTabCloser(clicked.siblings().find('.close-tab'));
36996            }
36997
36998            if($('.ease-of-access').size() > 0) {
36999                new SHC.ui.EaseOfAccess();
37000            }
37001        };
37002
37003        //function for closing process circles on mobile
37004        MobileTabCloser= function(that){
37005            var clicked = $(that);
37006            var tabCaratClass = 'tab-carat-circle-';
37007            if (clicked.closest('.mobile-tab-container').find('span.tab-carat').attr('class').indexOf('tab-carat-tab-') > -1){
37008                tabCaratClass = 'tab-carat-tab-';
37009            }
37010            clicked.closest(".mobile-tab-container").find('.anchor-tab-link.active').siblings('.circle-content').hide();
37011            clicked.closest(".mobile-tab-container").find('.anchor-tab-link').removeClass('active');
37012            clicked.closest('.mobile-tab-container').find('span.tab-carat').removeClass(tabCaratClass + 'open').addClass(tabCaratClass + 'close');
37013
37014            $('html, body').animate({
37015                scrollTop: clicked.closest('.process_circles').offset().top
37016            }, 500);
37017        };
37018    }
37019});
37020
37021SHC.Namespace(SHC, "SHC.ui.ExternalOutageAlert");
37022SHC.ui.ExternalOutageAlert = new SHC.Class();
37023SHC.ui.ExternalOutageAlert.include({
37024    /*
37025     * constructor
37026     */
37027    init: function(parent) {
37028        var that = this;
37029        SHC.outageAlertClosed = 0;
37030        this.parent = jQuery(parent);
37031        $(window).on('load', function(){
37032            if(window.location.href.indexOf('/presentation-mode/') > -1) {
37033                $('#presentation-mode .close').on('click', function(e) {
37034                    that.makeAjaxCall();
37035                });
37036            } else {
37037                that.makeAjaxCall();
37038            }
37039        });
37040    },
37041    activate: function(){
37042        var that = this;
37043        if(SHC.util.getCookie('sp_outage_alert_closed') !== 'closed'){
37044            this.desktopLogoArea = $('.masthead-affixed.hidden-xs.affix').not('.mobile');
37045            this.desktopMenuBarArea = $('#header').find('div.masthead').not('#drawers');
37046            this.desktopHamburgerMenu = $('#menu.static-menu .menu-content .home-icon-container');
37047            this.mobileMenuArea = $('.masthead').not('.large-only');
37048            this.alertContainer = $('#external-outage-alert');
37049            this.alertContentContainer = $('#external-outage-alert .outage-alert-content');
37050            this.alertContentText = this.alertContentContainer.find('.outage-alert-text');
37051            this.alertCloseContainer = this.alertContentContainer.find('.outage-alert-close');
37052            this.alertContainer.removeClass('hide-alert');
37053            that.resizeBasedOnTextContentHeight();
37054
37055            $(window).resize(function() {
37056                if(!that.alertContainer.hasClass('hide-alert')){
37057                    that.resizeBasedOnTextContentHeight();
37058                }
37059            });
37060
37061            $('#main').on('click', '#external-outage-alert .alert-x-close', function(){
37062                if(SHC.outageAlertClosed === 0){
37063                    that.closeAlertListener();
37064                }
37065            });
37066        }
37067    },
37068    resizeBasedOnTextContentHeight: function(){
37069        var here = this;
37070        if(SHC.util.getCookie('sp_outage_alert_closed') !== 'closed'){
37071            var newContentHeight = here.alertContentText.height();
37072            this.alertContainer.addClass('adjusted-zindex');
37073            here.alertCloseContainer.height(newContentHeight);
37074            here.alertContentContainer.height(newContentHeight);
37075            here.alertContainer.height(newContentHeight + 50);
37076
37077            var alertHeight = newContentHeight + 50;
37078            var emergencyAlert = $('#new-emergency-alert');
37079            if(SHC.util.getCookie('new_emergency_closed') !== 'closed'){
37080                alertHeight += emergencyAlert.height();
37081                here.alertContainer.css('top', emergencyAlert.height() + 'px');
37082                here.alertContainer.addClass('top-alert-divider');
37083            }
37084
37085            var alertHeightToMenu = alertHeight + 130;
37086            here.desktopLogoArea.css('top', alertHeight + 'px');
37087            here.desktopMenuBarArea.css('margin-top', alertHeightToMenu + 'px');
37088            here.desktopHamburgerMenu.css('margin-top', alertHeight + 'px');
37089
37090            if(SHC.ui.screenMode === 'small'){
37091                here.mobileMenuArea.css('margin-top', alertHeight + 'px');
37092            }else{
37093                here.mobileMenuArea.css('margin-top', alertHeightToMenu + 'px');
37094            }
37095        }
37096    },
37097    closeAlertListener: function(){
37098        var here = this;
37099        var cookieTimeToLive = 600; //10 minutes
37100        var alertHeight = here.alertContainer.height();
37101        var emergencyAlert = $('#new-emergency-alert');
37102        var newDesktopLogoTop = parseInt(here.desktopLogoArea.css('top').replace('px','') - alertHeight);
37103        var newDesktopMenuMargin = parseInt(here.desktopMenuBarArea.css('margin-top').replace('px','') - alertHeight - 130);
37104        var newDesktopHamburgerMargin = parseInt(here.desktopHamburgerMenu.css('margin-top').replace('px', '') - alertHeight);
37105        var mobileMenuMargin = 0;
37106
37107        here.alertContainer.parent().remove();
37108
37109        if(emergencyAlert.length > 0 && emergencyAlert.is(":visible")){
37110            newDesktopLogoTop -= 1;
37111            newDesktopMenuMargin = emergencyAlert.height() + 130;
37112            mobileMenuMargin = emergencyAlert.height();
37113        }
37114
37115        here.desktopLogoArea.css('top', newDesktopLogoTop + 'px');
37116        here.desktopMenuBarArea.css('margin-top', newDesktopMenuMargin + 'px');
37117        here.desktopHamburgerMenu.css('margin-top', newDesktopHamburgerMargin + 'px');
37118        if(SHC.ui.screenMode === 'small'){
37119            here.mobileMenuArea.css('margin-top', mobileMenuMargin + 'px');
37120        }
37121
37122        SHC.util.setCookieWithTimeInSeconds('sp_outage_alert_closed', 'closed', cookieTimeToLive, "/");
37123        SHC.outageAlertClosed = 1;
37124    },
37125    makeAjaxCall: function(){
37126        var that = this;
37127        $.ajax({
37128            url: '/bin/api/v1/content/externaldependencieshealthcheck.json',
37129            dataType: 'json',
37130            contentType: 'application/json',
37131            success: function(data){
37132                if(data.status[0] === 'down'){
37133                    that.activate();
37134                }
37135            }
37136        });
37137    }
37138});
37139SHC.Namespace(SHC, "SHC.ui.NewEmergencyAlert");
37140SHC.ui.NewEmergencyAlert = new SHC.Class();
37141SHC.ui.NewEmergencyAlert.include({
37142    /*
37143     * constructor
37144     */
37145    init: function(parent) {
37146        var that = this;
37147        SHC.emergencyAlertClosed = 0;
37148        this.parent = jQuery(parent);
37149        if(typeof SHC.emergencyAlerts === 'undefined' || SHC.emergencyAlerts == null){
37150            SHC.emergencyAlerts = {};
37151        }
37152        SHC.emergencyAlerts.emergencyHeight = 0;
37153        if(window.location.href.indexOf('/presentation-mode/') === -1) {
37154            that.activate();
37155        }
37156    },
37157    activate: function(){
37158        var that = this;
37159        if(SHC.util.getCookie('new_emergency_closed') !== 'closed'){
37160            this.desktopLogoArea = $('.masthead-affixed.hidden-xs.affix').not('.mobile');
37161            this.desktopMenuBarArea = $('#header').find('div.masthead').not('#drawers');
37162            this.searchResultsFilters = $('.search-results-filters');
37163            this.desktopHamburgerMenu = $('#menu.static-menu .menu-content .home-icon-container');
37164            this.mobileMenuArea = $('.masthead').not('.large-only').not('#drawers');
37165            this.alertContainer = $('#new-emergency-alert');
37166            this.alertContentContainer = $('#new-emergency-alert .new-emergency-alert-content');
37167            this.alertContentText = this.alertContentContainer.find('.new-emergency-alert-text');
37168            this.alertCloseContainer = this.alertContentContainer.find('.new-alert-close');
37169            this.firstScroll = true;
37170
37171            if(this.alertContainer.length === 1){
37172                this.alertContainer.find('.new-alert-spacer').addClass('set-height');
37173                $('#masthead-wrapper, .masthead-affixed, #masthead').addClass('alert-initialized');
37174
37175                $(window).resize(function() {
37176                    if (that.firstScroll) {
37177                        that.firstScroll = false;
37178                        $('#new-emergency-alert, #masthead-wrapper, .masthead-affixed, #masthead').addClass('loaded');
37179                    }
37180                    that.resizeBasedOnTextContentHeight();
37181                });
37182
37183                $('#main').on('click', '#new-emergency-alert .new-alert-x-close', function(){
37184                    if(SHC.emergencyAlertClosed === 0){
37185                        that.closeAlertListener();
37186                    }
37187                });
37188                $(window).on('scroll', function(){
37189                    if (that.firstScroll) {
37190                        that.firstScroll = false;
37191                        $('#new-emergency-alert, #masthead-wrapper, .masthead-affixed, #masthead').addClass('loaded');
37192                        that.resizeBasedOnTextContentHeight();
37193                    }
37194                });
37195                $('.menu-toggle, #search-container, .search-button').on('click', function(){
37196                    if (that.firstScroll) {
37197                        that.firstScroll = false;
37198                        $('#new-emergency-alert, #masthead-wrapper, .masthead-affixed, #masthead').addClass('loaded');
37199                        that.resizeBasedOnTextContentHeight();
37200                    }
37201                });
37202            }
37203        }else{
37204            if($('#new-emergency-alert').length === 1){
37205                $('#new-emergency-alert').addClass('hide-alert');
37206                $('.search-results-filters').removeClass('alert');
37207            }
37208        }
37209    },
37210    resizeBasedOnTextContentHeight: function(){
37211        var here = this;
37212        if(SHC.util.getCookie('new_emergency_closed') !== 'closed'){
37213            var newContentHeight = here.alertContentText.height();
37214            this.alertContainer.addClass('adjusted-zindex');
37215            SHC.emergencyAlerts.emergencyHeight = newContentHeight;
37216            here.alertCloseContainer.height(newContentHeight);
37217            here.alertContentContainer.height(newContentHeight);
37218            here.alertContainer.height(newContentHeight + 50);
37219
37220            var alertHeight = newContentHeight + 50;
37221            var alertHeightToMenu = alertHeight + 130;
37222            here.desktopHamburgerMenu.css('margin-top', alertHeight + 'px');
37223            here.searchResultsFilters.addClass('alert');
37224            here.desktopLogoArea.css('top', alertHeight + 'px');
37225            
37226            if(SHC.ui.screenMode === 'small'){
37227                here.desktopMenuBarArea.css('margin-top', alertHeight + 'px');
37228                here.searchResultsFilters.addClass('mobile');
37229                here.searchResultsFilters.addClass('alert');
37230                here.searchResultsFilters.css('top', '');
37231            }else{
37232                here.mobileMenuArea.css('margin-top', alertHeightToMenu + 'px');
37233                here.searchResultsFilters.removeClass('mobile');
37234                here.searchResultsFilters.css('top', here.alertContainer.height() + 75 + 'px');
37235            }
37236        }
37237    },
37238    closeAlertListener: function(){
37239        var here = this;
37240        var alertHeight = here.alertContainer.height();
37241        var externalOutage = $('#external-outage-alert');
37242        var newDesktopLogoTop = parseInt(here.desktopLogoArea.css('top').replace('px',''));
37243        var newDesktopMenuMargin = parseInt(here.desktopMenuBarArea.css('margin-top').replace('px', ''));
37244        var newDesktopHamburgerMargin = parseInt(here.desktopHamburgerMenu.css('margin-top').replace('px', ''));
37245        var mobileMenuMargin = 0;
37246
37247        if (newDesktopLogoTop > 0 && newDesktopMenuMargin > 0 && newDesktopHamburgerMargin > 0) {
37248            newDesktopLogoTop = newDesktopLogoTop - alertHeight;
37249            newDesktopMenuMargin = newDesktopMenuMargin - alertHeight - 130;
37250            newDesktopHamburgerMargin = newDesktopHamburgerMargin - alertHeight;
37251        }
37252
37253        here.alertContainer.parent().remove();
37254
37255        if(externalOutage.length > 0 && externalOutage.is(":visible")){
37256            externalOutage.removeClass('top-alert-divider');
37257            externalOutage.css('top', '0px');
37258            newDesktopMenuMargin = externalOutage.height() + 130;
37259            mobileMenuMargin = externalOutage.height();
37260        }
37261
37262        here.desktopLogoArea.css('top', newDesktopLogoTop + 'px');
37263        here.searchResultsFilters.removeClass('alert');
37264        here.desktopMenuBarArea.css('margin-top', newDesktopMenuMargin + 'px');
37265        here.desktopHamburgerMenu.css('margin-top', newDesktopHamburgerMargin + 'px');
37266
37267        if(SHC.ui.screenMode === 'small'){
37268            here.searchResultsFilters.css('top', '');
37269            here.mobileMenuArea.css('margin-top', mobileMenuMargin + 'px');
37270        } else {
37271            here.searchResultsFilters.css('top', '75px');
37272        }
37273
37274        var cookieTimeToLive = parseInt(here.alertContainer.attr('data-attr-cookie'));
37275        if(cookieTimeToLive < 1){
37276            cookieTimeToLive = 43200;
37277        }
37278        SHC.util.setCookieWithTimeInSeconds('new_emergency_closed', 'closed', cookieTimeToLive, "/");
37279        SHC.emergencyAlertClosed = 1;
37280    }
37281});
37282//////////////////////////////////////////////////////////////////////////////////////////
37283// Handle Anchors
37284//   - Loading a page with a hash should scroll the user to the correct spot
37285//   - Clicking a link on a page that has an anchor should also scroll to the correct spot
37286//////////////////////////////////////////////////////////////////////////////////////////
37287
37288var nestedAnchorExpand = function () {
37289var hash = location.hash.replace('#', '');
37290    if (hash && hash.indexOf('&') === -1 && hash.indexOf('=') === -1 ) {
37291        var anchorElem = $('[name=' + hash + '], #' + hash);
37292        if (anchorElem.length > 1) {
37293            var anchorElemInstance;
37294            //We are assuming tabs and circles are not nested (only revealBoxes should be nested)
37295            //Here we are selecting the appropriate Element based on screen size (necessary since current code clones content).
37296            for (var i = 0; i < anchorElem.length; i++) {
37297                anchorElemInstance = $(anchorElem[i]);
37298                if (((anchorElemInstance.closest(".mobile-tab-details-container, .process-circles-mobile").length === 1 && SHC.ui.screenMode === "small") ||
37299                    (anchorElemInstance.closest(".desktop-tab-details-container, .process-circles-desktop").length === 1 && SHC.ui.screenMode !== "small")) &&
37300                    (anchorElemInstance.closest(".clone-content").length === 0)) {
37301                    anchorElem = anchorElemInstance;
37302                    break;
37303                }
37304            }
37305        }
37306        var focusedElem = anchorElem.closest('.reveal-box-expert, .revealbox_faq, .tab-content, .circle-content');
37307        //initializing circle and tab variables used in while loop
37308        var circleElemClasses;
37309        var circleClass;
37310        var circleList;
37311        var clickableCircle;
37312        var dataTabIndex;
37313        var tabNavContent;
37314        while (focusedElem && focusedElem.length === 1) {
37315            if(focusedElem.hasClass('reveal-box-expert')) {
37316                SHC.ui.RevealBoxExpert.hashScroll = 25;
37317                focusedElem.addClass('box-active');
37318                focusedElem.find(".reveal-arrow-expert").addClass("active");
37319                focusedElem.find(".reveal-content-expert").show();
37320            }
37321            else if(focusedElem.hasClass('revealbox_faq')) {
37322                SHC.ui.RevealBoxExpert.hashScroll = 25;
37323                focusedElem.find(".reveal-arrow").addClass("active");
37324                focusedElem.find(".reveal-content").show();
37325            }
37326            else if(focusedElem.hasClass('tab-content') ) {
37327                dataTabIndex = focusedElem.attr('data-tab-index').trim();
37328                tabNavContent = focusedElem.closest(".care-team-tab-container, .treatment-box-container").find(".tab-nav-content[data-tab-index=" + dataTabIndex + "]");
37329                if (tabNavContent.length === 1) {
37330                    if (tabNavContent.hasClass('tab-nav-content') && !tabNavContent.hasClass('active')) {
37331                        SHC.inPageNavClick = 'true';
37332                        tabNavContent.click();
37333                    }
37334                }
37335            }
37336            else if(focusedElem.hasClass('circle-content')) {
37337                circleElemClasses = focusedElem.attr('class').split(" ");
37338                /* jshint ignore:start */
37339                circleClass = circleElemClasses.filter(function (classElem) {
37340                    //"circle_".length === 7
37341                    return classElem.indexOf("circle_") === 0 && SHC.util.regexIndexOf(classElem, "^[0-9]*$", 7) === 7;
37342                });
37343                /* jshint ignore:end */
37344                if (circleClass.length === 1) {
37345                    if (SHC.ui.screenMode !== "small") {
37346                        clickableCircle = focusedElem.closest(".process-circle-content-container").siblings(".process-circles-list-container").find("." + circleClass[0]);
37347                    } else if (SHC.ui.screenMode === "small") {
37348                        clickableCircle = focusedElem.siblings(".circle_title." + circleClass[0]);
37349                    }
37350                    if (!clickableCircle.hasClass("active")) {
37351                        SHC.inPageNavClick = 'true';
37352                        clickableCircle.click();
37353                    }
37354                }
37355            }
37356            focusedElem = focusedElem.parent().closest('.reveal-box-expert,  .revealbox_faq, .tab-content, .circle-content');
37357        }
37358    }
37359};
37360
37361jQuery(window).on('hashchange debouncedresize anchorclick', function() {
37362    if (!$('.stanford-now-tabs').length) {
37363        nestedAnchorExpand();
37364        SHC.util.hashScroll();
37365    }
37366});
37367
37368(() => {
37369
37370	function handleClick(link, locationContainer) {
37371		const location = locationContainer.dataset.cmpLocation;
37372		const primary = link.dataset.cmpCategoryPrimary ? link.dataset.cmpCategoryPrimary : 'featured content';
37373		const contentCategory = link.dataset.cmpContentCategory ? link.dataset.cmpContentCategory : '';
37374
37375		stanford.analytics.send(stanford.analytics.createHomepageComponentClickLocation(location, link.href, primary, contentCategory));
37376	}
37377
37378	function onDocumentReady() {
37379		const locationElems = Array.from(document.querySelectorAll('[data-cmp-location]'));
37380		const locations = locationElems.filter((el) => {
37381			const locationName = el.dataset.cmpLocation;
37382			return locationName === 'features' || locationName === 'news' || locationName === 'SHC Now';
37383		});
37384		locations.forEach((locationContainer) => {
37385			const links = locationContainer.querySelectorAll('a');
37386			links.forEach((link) => {
37387				link.addEventListener('click', () => {
37388					handleClick(link, locationContainer);
37389				});
37390			});
37391		});
37392	}
37393
37394	if (document.readyState !== 'loading') {
37395		const template = document.querySelector('meta[name="template"]').content;
37396		if (template === '/apps/shc/templates/home') {
37397			onDocumentReady();
37398		}
37399	} else {
37400		document.addEventListener('DOMContentLoaded', onDocumentReady);
37401	}
37402})();
37403
37404
37405SHC.Namespace(SHC, "SHC.util.ObjectList");
37406/**
37407 * Utility list class.
37408 * @type {SHC.Class}
37409 */
37410SHC.util.ObjectList = new SHC.Class();
37411SHC.util.ObjectList.include({
37412
37413    init: function() {
37414        "use strict";
37415        this.list = [];
37416        return this;
37417    },
37418
37419    forEach: function(callback) {
37420        if (!callback) {
37421            return;
37422        } else if (typeof callback === 'function' && this.list.length) {
37423            for (var i= 0, n=this.list.length; i<n; i++){
37424                callback(this.list[i]);
37425            }
37426        }
37427    },
37428
37429    push: function(obj) {
37430        if (obj) {
37431            this.list.push(obj);
37432        }
37433    },
37434
37435    remove: function(index) {
37436        this.list.splice(index,1);
37437    },
37438
37439    /**
37440     * Remove an item whose property
37441     * matches a value.
37442     * @param propertyName
37443     * @param value
37444     */
37445    removeByKeyValue: function(key, value) {
37446        if (!this.list) {
37447            return;
37448        }
37449        for (var i=this.list.length-1; i>=0; i--) {
37450            if (this.list[i][key] === value) {
37451                this.remove(i);
37452            }
37453        }
37454    },
37455
37456    findByKeyValue: function(key, value) {
37457        if (!key || !this.list) {
37458            return -1;
37459        }
37460        for(var i= 0,n=this.list.length; i<n; i++) {
37461            if (this.list[i][key]===value) {
37462                return i;
37463            }
37464        }
37465        return -1;
37466    },
37467
37468    sortByKey: function(key) {
37469        this.list.sort(function(a,b){
37470           if (a[key] === b[key]) {
37471               return 0;
37472           } else if (a[key] > b[key]) {
37473               return 1;
37474           } else {
37475               return -1;
37476           }
37477        });
37478    }
37479
37480});
37481shcDOMContentLoaded(function() {
37482    var jqHtml = jQuery('html');
37483    if (jqHtml.hasClass('no-csstransforms') || jqHtml.hasClass('no-cssanimations')) {
37484        jQuery('#spinner-container').simpleSpinner();
37485    }
37486});
37487shcDOMContentLoaded(function() {
37488    //exact match view more button
37489    $('#main-container').on('click', '.clinical-trials-directory .trials_view_more_btn', function(){
37490        var nextPageQ = $(this).attr('data-attr-pagination');
37491        $(this).remove();
37492        if(nextPageQ && nextPageQ.length > 1){
37493            var searchResultsBinder = new SHC.ui.Search.ResultsBinder('#search-results-page');
37494            SHC.clinicalTrialsFilter.paginationClick = true;
37495            SHC.clinicalTrialsFilter.paginationClickCounter += 1;
37496            searchResultsBinder.paginate(nextPageQ);
37497        }
37498    });
37499
37500    //non-exact match view more button
37501    $('#main-container').on('click', '.clinical-trials-directory .trials_cond_view_more_btn', function(){
37502        var currentlyDisplayed = parseInt(SHC.trialsConditionData.groupDisplayed);
37503        var totalGroups = parseInt(SHC.trialsConditionData.groupTotal);
37504        trialVisibilityChange(currentlyDisplayed, totalGroups);
37505        SHC.trialsConditionData.groupDisplayed  = SHC.trialsConditionData.groupDisplayed + 1;
37506    });
37507
37508    function trialVisibilityChange(currentlyDisplayed, totalGroupsLimit){
37509        if(currentlyDisplayed < totalGroupsLimit + 1){
37510            $('.ct_grp_' + (currentlyDisplayed + 1) + '.hidden').removeClass('hidden');
37511        }
37512
37513        if(currentlyDisplayed + 1 ===  totalGroupsLimit){
37514            $('.clinical-trials-directory .trials_view_more_btn.btn').addClass('hidden');
37515            $('.clinical-trials-directory .trials_cond_view_more_btn.btn').addClass('hidden');
37516        }
37517    }
37518
37519    //when clicking a link use the filter rails to make a new request
37520    $('#main-container').on('click', '.clinical-trials-directory.non-exact-match .cond-result a', function(e){
37521        e.preventDefault();
37522        var conditionText = this.text;
37523        $('.search-results-filters.trials-filter-rail #trials-condition-filter-target input').val(conditionText);
37524        var filterFields = $('input.select-auto-complete.ui-autocomplete-input');
37525        SHC.clinicalTrialsFilter.nonExactClick = true;
37526        SHC.clinicalTrialsFilter.filter.prepareAutoCompleteFilterRequest(filterFields);
37527    });
37528});
37529$(function(){
37530
37531    if ($('#newsroom-collection-page').length) {
37532        var collectionName = SHC.util.getURLSearchTerm(window.location.pathname);    
37533        var $collectionType = $('#newsroom-collection-page .collection-type');
37534        var $collectionName = $('#newsroom-collection-page .collection-name');
37535        var itemPerPage = 12;
37536        var query = "?do=organic_newsroom&sp_s=sp_date&sp_c=" + itemPerPage + "&x1=sp_tags&q1=" + collectionName;
37537        var searchVer = document.querySelector('meta[name="shc-search-version"]').content || "v1";
37538        var url = "/bin/api/"+searchVer+"/search.json";
37539    
37540        var getJSON = function(url){
37541            SHC.searchRequest = $.ajax({
37542                url: url,
37543                dataType: "jsonp",
37544                jsonp: 'callback',
37545                contentType: "application/json",
37546                success: function (data) {
37547                    if (data.results.data.length > 0) {
37548                        collectionCallback(data);
37549                    }
37550                },
37551                error: function() {
37552                },
37553                complete: function () {
37554                }
37555            });
37556        };
37557        var collectionCallback = function(data){
37558            var type;
37559            if (data.results.data[0].mediaType === "image"){
37560            type = "Image Collection";
37561            } else if (data.results.data[0].mediaType === "video"){
37562            type = "Video Collection";
37563            }
37564            $collectionType.text(type);
37565            var name = collectionName.toLowerCase().split('_');
37566            collectionName = "";
37567            name.forEach(function(element){
37568                if (element !== 'collection') {
37569                    collectionName += element.charAt(0).toUpperCase() + element.slice(1) + " ";
37570                }
37571            });
37572            $collectionName.text(collectionName.trim());
37573    
37574            data.isCollectionTemplate = true;
37575            $('.newsroom-grid-handlebar-target').html(JST["handlebars/newsroom-landing-grid-template.hbs"](data));
37576    
37577            $(".search-pagination li a").each(function () {
37578            $(this).on("click", paginationClick);
37579            });
37580    
37581        };
37582    
37583        var paginationClick = function(){
37584            //reload hbs and reattach click event
37585            var pageQuery = $(this).attr('data-request').replace(new RegExp(";", "g"), "&");
37586            getJSON(url + pageQuery);
37587        };
37588    
37589        if (collectionName != '') {
37590            getJSON(url + query);
37591        }
37592    }
37593});
37594
37595shcDOMContentLoaded(function() {
37596    $(".subnav .subnav-object").click(function(e){
37597        $(this).find(".level3pages").toggle();
37598        $(this).find("span.carat-gray").toggleClass("open");
37599        $(this).find("div.level2page").toggleClass("open");
37600        $(this).siblings().children(".open").removeClass("open");
37601        $(this).siblings().children(".level3pages").hide();
37602        e.stopPropagation();
37603    });
37604    $(".subnav-items.mobile .subnav-hubpage").click(function(e){
37605        $(this).siblings(".level2pages").toggle();
37606        $(".level3pages").hide();
37607        $(this).find("span.carat-white").toggleClass("open");
37608        e.stopPropagation();
37609    });
37610    $(document).click(function(){
37611        $(".level3pages").hide();
37612        $(".subnav-items.mobile .level2pages").hide();
37613        $(".subnav-items span.carat-gray").removeClass("open");
37614        $(".subnav-items.mobile span.carat-white").removeClass("open");
37615        $(".subnav-items .level2page").removeClass("open");
37616    });
37617    $("#main").on('click', '#side-nav', function(){
37618        var $activeLink = $(".subnav .active");
37619        var path = window.location.pathname;
37620        if (path.indexOf("/content/shc/en") < 0){
37621            path = "/content/shc/en" + path;
37622        }
37623        if ($activeLink.data("path") != path){
37624            $activeLink.removeClass("active");
37625            $(".subnav .subnav-object").find("[data-path='"+path+"']").addClass("active");
37626        }
37627    });
37628
37629    var tabletBreakPoint = function() {
37630        $('.subnav-items.desktop .subnav-object').each(function () {
37631            $(this).css('width', 'auto')
37632            $(this).width($(this).width() + 4);
37633        });
37634
37635        if ($(window).width() >= 768 && $(window).width() <= 1023){
37636            var pixelsNeeded = 0;
37637            $('.subnav-items.desktop .subnav-object').each(function () {
37638                pixelsNeeded += $(this).width() + 42;
37639            });
37640            if (pixelsNeeded > $(window).width()){
37641                $(".subnav .subnav-items.desktop").css({'overflow':'hidden','height':'0'});
37642                $(".subnav .subnav-items.mobile").show();
37643            }
37644            else{
37645                $(".subnav .subnav-items.desktop").css({'overflow':'inherit','height':'35px'});
37646                $(".subnav .subnav-items.mobile").hide();
37647            }
37648        }
37649        else if ($(window).width() > 1023){
37650            $(".subnav .subnav-items.desktop").css({'overflow':'inherit','height':'35px'});
37651            $(".subnav .subnav-items.mobile").hide();
37652        }
37653        else{
37654            $(".subnav .subnav-items.desktop").css({'overflow':'hidden','height':'0'});
37655            $(".subnav .subnav-items.mobile").show();
37656        }
37657    }
37658
37659    tabletBreakPoint();
37660
37661    $(window).resize(function (e) {
37662        tabletBreakPoint();
37663    });
37664});
37665shcDOMContentLoaded(function () {
37666    if (jQuery("#listing-page").length) {
37667        var listingResults = new SHC.ui.Listing.Results('#listing-page');
37668        listingResults.startSearch("organic_newsroom");
37669    }
37670});
37671
37672$(function() {
37673    if (jQuery(".stanford-now-tabs").length) {
37674        var eventCollection = new SHC.ui.Stanford.Now.Tabs('.stanford-now-tabs');
37675    }
37676});
37677
37678
37679jQuery(function($) {
37680    var jqHtml = $('html');
37681    if (jqHtml.hasClass('no-csstransforms') || jqHtml.hasClass('no-cssanimations')) {
37682        $('.spinner-container').simpleSpinner();
37683    }
37684});
37685/*jslint newcap: true, nomen: true, plusplus: true, white: true, browser: true, devel: true */
37686/*
37687 * /sm/components/commons/video/clientlibs/js/video-resize.js
37688 */
37689(function($, window, document, undefined) {
37690  "use strict";
37691
37692  function setVideoHeight() {
37693    $('.video-fluid:visible').each(function() {
37694      var videoContainer = $(this);
37695      var getSkin = $(this).data('playerid');
37696      resizePlayer(videoContainer, getSkin);
37697    });
37698  }
37699
37700  function setHiddenVideoHeights() {
37701    $('.video-fluid:hidden').each(function() {
37702      var videoContainer = $(this);
37703      videoContainer.parents(".panel-collapse").each(function() {
37704        $(this).on("shown.bs.collapse", function() {
37705          var container = $(this);
37706          var getSkin = $(this).data('playerid');
37707          resizePlayer(container, getSkin);
37708        });
37709      });
37710    });
37711  }
37712
37713  function resizePlayer(container, playerid) {
37714    var multiplier;
37715    if (playerid == 48788683) {
37716      multiplier = .219;
37717    } else {
37718      multiplier = 0.562130;
37719    }
37720    var player = container.find('.kp-player'),
37721      newHeight = Math.ceil(player.width() * multiplier) + 1;
37722    player.height(newHeight);
37723  }
37724  $(document).ready(function() {
37725    setVideoHeight();
37726    setHiddenVideoHeights();
37727    $(window).resize(function() {
37728      setVideoHeight();
37729    });
37730  });
37731}(jQuery, window, document));
37732/*jslint newcap: true, nomen: true, plusplus: true, white: true, browser: true, devel: true */
37733
37734/*
37735 * /sm/components/commons/video/clientlibs/js/embed.js
37736 */
37737(function($, window, document, undefined) {
37738    "use strict";
37739    $(document).ready(function() {
37740        $('.sm-kp-embed').each(function(idx,elem){
37741            var $vid = $(elem);
37742            var flashVars = {
37743                "autoPlay": $vid.attr('data-auto-play'),
37744                "streamerType": "auto",
37745                'requiredMetadataFields' : true
37746            };
37747            kWidget.embed({
37748                "targetId": $vid.attr('id'),
37749                "wid": "_1392761",
37750                "uiconf_id": $vid.attr('data-player-skin'),
37751                "flashvars": flashVars,
37752                "cache_st": "main_video",
37753                "entry_id": $vid.attr('data-entry-id'),
37754                'readyCallback': function( playerId ){
37755                    var kdp = $( '#' + playerId )[0];
37756                    var kpPlayer = $('.kp-player')[0];
37757                    kdp.addJsListener( 'metadataReceived', function (){
37758                        var videoMetadata = kdp.evaluate('{mediaProxy.entry}');
37759                        $(kpPlayer).attr('duration', videoMetadata.duration || 0);
37760                        $(kpPlayer).attr('name', videoMetadata.name || '');
37761                    });
37762                }
37763
37764            });
37765        });
37766
37767    });
37768
37769}(jQuery, window, document));
37770
37771(function ($) {
37772  "use strict";
37773
37774  var $document = $(document);
37775
37776  // load data from old format
37777  $document.on('dialog-ready', function() {
37778    var $videoDialog = $('.video-dialog');
37779
37780    if (!$videoDialog.length) {
37781      return;      
37782    }
37783
37784    var $captionLayout = $videoDialog.find('[name="./layout"]'),
37785        captionLayoutValue = $captionLayout.val();
37786    if (captionLayoutValue !== null 
37787        && captionLayoutValue !== '' 
37788        && captionLayoutValue !== 'noCaption') {
37789      $videoDialog.find('[name="./addCaption"]').prop('checked', true).trigger('change');
37790    }
37791  });
37792
37793  $document.on('click', '.cq-dialog-submit', function() {
37794    var $videoDialog = $('.video-dialog');
37795
37796    if (!$videoDialog.length) {
37797      return;
37798    }
37799
37800    if (!$videoDialog.find('[name="./addCaption"]').prop('checked')) {
37801      $videoDialog.find('[name="./layout"]').val('noCaption');
37802    }
37803  });
37804
37805})(jQuery);

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.