window.ju_123_seo = document.getElementById("ju_123_seo");
if(ju_123_seo){
	ju_123_seo.style.display="none";
}

window.ju_inIframeLoaded = function() {
    try {
        return window.self !== window.top && typeof(window.top.ju_alreadyloaded) == 'boolean';
    } catch (e) {
        return false;
    }
}

if (typeof (ju_onboarding_display) === 'undefined') {
	window.ju_onboarding_display = -1;
}

if (typeof (ju_onboarding_steps) === 'undefined') {
	window.ju_onboarding_steps = -1;
}

if (typeof(window.ju_alreadyloaded) == 'boolean' && typeof(window.ju_init_fired) == 'undefined' && typeof(ju_init) === 'function' && window.ju_config && window.ju_config.profileExists) {
  setTimeout(function(){
    ju_init();
    jju.each(ju_config.initFunc,function(i,v){
      v();
    });
  },1000);
};

window.fetchWindowHref = function(){
  var temp = window.location.href;
  if (temp.indexOf('http')!=-1){
    return temp;
  } else {
    return top.window.location.href;
  }
}

window.ju_isPreview = fetchWindowHref().indexOf("preview-popup")!=-1;

// I block tons of useragents via cloudflare's firewall.
var ju_isBot = false //navigator.userAgent.match(/(Google Web Preview|Googlebot)/gi);

if (!ju_isBot && typeof (window.ju_alreadyloaded) != 'boolean' && fetchWindowHref().indexOf("#ju_preview")==-1 && ju_num.length == 36 && (!ju_inIframeLoaded() || ju_onboarding_display >= 0)){
	/* promise */
	(function(f){function p(){}function q(a,c){return function(){a.apply(c,arguments)}}function b(a){if("object"!==typeof this)throw new TypeError("Promises must be constructed via new");if("function"!==typeof a)throw new TypeError("not a function");this.a=0;this.h=!1;this.b=void 0;this.c=[];m(a,this)}function n(a,c){for(;3===a.a;)a=a.b;0===a.a?a.c.push(c):(a.h=!0,b.f(function(){var e=1===a.a?c.l:c.m;if(null===e)(1===a.a?k:d)(c.g,a.b);else{var b;try{b=e(a.b)}catch(r){d(c.g,r);return}k(c.g,b)}}))}function k(a,c){try{if(c===a)throw new TypeError("A promise cannot be resolved with itself.");if(c&&("object"===typeof c||"function"===typeof c)){var e=c.then;if(c instanceof b){a.a=3;a.b=c;l(a);return}if("function"===typeof e){m(q(e,c),a);return}}a.a=1;a.b=c;l(a)}catch(h){d(a,h)}}function d(a,c){a.a=2;a.b=c;l(a)}function l(a){2===a.a&&0===a.c.length&&b.f(function(){a.h||b.i(a.b)});for(var c=0,e=a.c.length;c<e;c++)n(a,a.c[c]);a.c=null}function t(a,c,b){this.l="function"===typeof a?a:null;this.m="function"===typeof c?c:null;this.g=b}function m(a,c){var b=!1;try{a(function(a){b||(b=!0,k(c,a))},function(a){b||(b=!0,d(c,a))})}catch(h){b||(b=!0,d(c,h))}}var u=setTimeout;b.prototype["catch"]=function(a){return this.then(null,a)};b.prototype.then=function(a,c){var b=new this.constructor(p);n(this,new t(a,c,b));return b};b.all=function(a){var c=Array.prototype.slice.call(a);return new b(function(a,b){function e(d,g){try{if(g&&("object"===typeof g||"function"===typeof g)){var f=g.then;if("function"===typeof f){f.call(g,function(a){e(d,a)},b);return}}c[d]=g;0===--h&&a(c)}catch(v){b(v)}}if(0===c.length)return a([]);for(var h=c.length,d=0;d<c.length;d++)e(d,c[d])})};b.resolve=function(a){return a&&"object"===typeof a&&a.constructor===b?a:new b(function(c){c(a)})};b.reject=function(a){return new b(function(c,b){b(a)})};b.race=function(a){return new b(function(c,b){for(var d=0,e=a.length;d<e;d++)a[d].then(c,b)})};b.f="function"===typeof setImmediate&&function(a){setImmediate(a)}||function(a){u(a,0)};b.i=function(a){"undefined"!==typeof console&&console&&console.warn("Possible Unhandled Promise Rejection:",a)};b.o=function(a){b.f=a};b.s=function(a){b.i=a};"undefined"!==typeof module&&module.j?module.j=b:f.Promise?f.Promise.all||(f.Promise.all=b.all):f.Promise=b})(this);

  /* md5 hash */
	window.ju_md5=function(){for(var m=[],l=0;64>l;)m[l]=0|4294967296*Math.abs(Math.sin(++l));return function(c){var e,g,f,a,h=[];c=unescape(encodeURI(c));for(var b=c.length,k=[e=1732584193,g=-271733879,~e,~g],d=0;d<=b;)h[d>>2]|=(c.charCodeAt(d)||128)<<8*(d++%4);h[c=16*(b+8>>6)+14]=8*b;for(d=0;d<c;d+=16){b=k;for(a=0;64>a;)b=[f=b[3],(e=b[1]|0)+((f=b[0]+[e&(g=b[2])|~e&f,f&e|~f&g,e^g^f,g^(e|~f)][b=a>>4]+(m[a]+(h[[a,5*a+1,3*a+5,7*a][b]%16+d]|0)))<<(b=[7,12,17,22,5,9,14,20,4,11,16,23,6,10,15,21][4*b+a++%4])|f>>>32-b),e,g];for(a=4;a;)k[--a]=k[a]+b[a]}for(c="";32>a;)c+=(k[a>>3]>>4*(1^a++&7)&15).toString(16);return c}}();

	/* sha1 */
	window.ju_sha1=function(d){var l=0,a=0,f=[],b,c,g,h,p,e,m=[b=1732584193,c=4023233417,~b,~c,3285377520],n=[],k=unescape(encodeURI(d));for(b=k.length;a<=b;)n[a>>2]|=(k.charCodeAt(a)||128)<<8*(3-a++%4);for(n[d=b+8>>2|15]=b<<3;l<=d;l+=16){b=m;for(a=0;80>a;b=[[(e=((k=b[0])<<5|k>>>27)+b[4]+(f[a]=16>a?~~n[l+a]:e<<1|e>>>31)+1518500249)+((c=b[1])&(g=b[2])|~c&(h=b[3])),p=e+(c^g^h)+341275144,e+(c&g|c&h|g&h)+882459459,p+1535694389][0|a++/20]|0,k,c<<30|c>>>2,g,h])e=f[a-3]^f[a-8]^f[a-14]^f[a-16];for(a=5;a;)m[--a]=m[a]+b[a]|0}for(d="";40>a;)d+=(m[a>>3]>>4*(7-a++%8)&15).toString(16);return d};

	/* sha256 */
	window.ju_sha256=function(){function e(a,b){return a>>>b|a<<32-b}for(var b=1,a,m=[],n=[];18>++b;)for(a=b*b;312>a;a+=b)m[a]=1;b=1;for(a=0;313>b;)m[++b]||(n[a]=Math.pow(b,.5)%1*4294967296|0,m[a++]=Math.pow(b,1/3)%1*4294967296|0);return function(g){for(var l=n.slice(b=0),c=unescape(encodeURI(g)),h=[],d=c.length,k=[],f,p;b<d;)k[b>>2]|=(c.charCodeAt(b)&255)<<8*(3-b++%4);d*=8;k[d>>5]|=128<<24-d%32;k[p=d+64>>5|15]=d;for(b=0;b<p;b+=16){for(c=l.slice(a=0,8);64>a;c[4]+=f)h[a]=16>a?k[a+b]:(e(f=h[a-2],17)^e(f,19)^f>>>10)+(h[a-7]|0)+(e(f=h[a-15],7)^e(f,18)^f>>>3)+(h[a-16]|0),c.unshift((f=(c.pop()+(e(g=c[4],6)^e(g,11)^e(g,25))+((g&c[5]^~g&c[6])+m[a])|0)+(h[a++]|0))+(e(d=c[0],2)^e(d,13)^e(d,22))+(d&c[1]^c[1]&c[2]^c[2]&d));for(a=8;a--;)l[a]=c[a]+l[a]}for(c="";63>a;)c+=(l[++a>>3]>>4*(7-a%8)&15).toString(16);return c}}();

	/* cookie tracking */
	var ju_Cookie=function(){window.ju_errors=window.ju_errors||[];var e={httpCookie:void 0,localStorCookie:void 0,sessionStorCookie:void 0},o=function(e,o){for(var t=e+"=",n=document.cookie.split(";"),i=0;i<n.length;i++){for(var r=n[i];" "==r.charAt(0);)r=r.substring(1);if(0==r.indexOf(t))return o?Promise.resolve({key:e,value:r.substring(t.length,r.length)}):r.substring(t.length,r.length)}return o?Promise.resolve(void 0):""},t=function(e,o){return new Promise(function(t,n){try{if("localStorage"in window)if(o)window.localStorage.setItem(e,o),void 0!==window.localStorage.getItem(e)?t({key:e,value:window.localStorage.getItem(e)}):t(void 0);else{var i=window.localStorage.getItem(e);t(i?{key:e,value:i}:void 0)}else t(void 0)}catch(e){t(void 0)}})},n=function(e,o){return new Promise(function(t,n){try{if("sessionStorage"in window)if(o)window.sessionStorage.setItem(e,o),void 0!==window.sessionStorage.getItem(e)?t({key:e,value:window.sessionStorage.getItem(e)}):t(void 0);else{var i=window.sessionStorage.getItem(e);t(i?{key:e,value:i}:void 0)}else t(void 0)}catch(e){t(void 0)}})},i=function(i,r,s,u,l){return function(e,t,n,i,r){try{var s=new Date;s.setTime(s.getTime()+24*n*60*60*1e3);var u="expires="+s.toUTCString();return document.cookie=e+"="+t+"; "+u+(i?";path="+i:"")+(r?";domain="+r:""),o(e).length>0?Promise.resolve(o(e)):Promise.resolve(void 0)}catch(e){return Promise.resolve(void 0)}}(i,r,s,u,l).then(function(o){return e.httpCookie=o,t(i,r)}).then(function(o){return e.localStorCookie=o,n(i,r)}).then(function(o){return e.sessionStorCookie=o,e})},r=function(i){return o(i,!0).then(function(o){return e.httpCookie=o,t(i)}).then(function(o){return e.localStorCookie=o,n(i)}).then(function(t){return e.sessionStorCookie=t,Promise.resolve(o(i))}).then(function(o){return 0===o.length?e:(e.httpCookie={key:i,value:o},e)})};return{setCookies:i,getCookies:r,restoreCookies:function(e,o,t,n){return r(e).then(function(r){for(var s in r)if(void 0!==r[s]&&null!==r[s]&&"undefined"!==r[s])return i(e,r[s].value,o,t,n),r[s]})},foundCookies:e}}();

  /* ouibounce library */
	function ouibounce(e,n){"use strict";function t(e,n){return"undefined"==typeof e?n:e}function i(){y.addEventListener("mouseleave",u),y.addEventListener("mouseenter",o),y.addEventListener("keydown",c)}function u(e){e.clientY>r||(m=setTimeout(d,a))}function o(){m&&(clearTimeout(m),m=null)}function c(e){v||e.metaKey&&76===e.keyCode&&(v=!0,m=setTimeout(d,a))}function d(){e&&(e.style.display="block"),f()}var l=n||{},r=t(l.sensitivity,20),s=t(l.timer,1e3),a=t(l.delay,0),f=l.callback||function(){},m=null,y=document.documentElement;setTimeout(i,s);var v=!1;return{fire:d}}

	/* zlib library */
	!function(t){("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).pako=t()}(function(){return function t(e,a,n){function r(s,h){if(!a[s]){if(!e[s]){var l="function"==typeof require&&require;if(!h&&l)return l(s,!0);if(i)return i(s,!0);var o=new Error("Cannot find module '"+s+"'");throw o.code="MODULE_NOT_FOUND",o}var _=a[s]={exports:{}};e[s][0].call(_.exports,function(t){var a=e[s][1][t];return r(a||t)},_,_.exports,t,e,a,n)}return a[s].exports}for(var i="function"==typeof require&&require,s=0;s<n.length;s++)r(n[s]);return r}({1:[function(t,e,a){"use strict";function n(t,e){return Object.prototype.hasOwnProperty.call(t,e)}var r="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Int32Array;a.assign=function(t){for(var e=Array.prototype.slice.call(arguments,1);e.length;){var a=e.shift();if(a){if("object"!=typeof a)throw new TypeError(a+"must be non-object");for(var r in a)n(a,r)&&(t[r]=a[r])}}return t},a.shrinkBuf=function(t,e){return t.length===e?t:t.subarray?t.subarray(0,e):(t.length=e,t)};var i={arraySet:function(t,e,a,n,r){if(e.subarray&&t.subarray)t.set(e.subarray(a,a+n),r);else for(var i=0;i<n;i++)t[r+i]=e[a+i]},flattenChunks:function(t){var e,a,n,r,i,s;for(n=0,e=0,a=t.length;e<a;e++)n+=t[e].length;for(s=new Uint8Array(n),r=0,e=0,a=t.length;e<a;e++)i=t[e],s.set(i,r),r+=i.length;return s}},s={arraySet:function(t,e,a,n,r){for(var i=0;i<n;i++)t[r+i]=e[a+i]},flattenChunks:function(t){return[].concat.apply([],t)}};a.setTyped=function(t){t?(a.Buf8=Uint8Array,a.Buf16=Uint16Array,a.Buf32=Int32Array,a.assign(a,i)):(a.Buf8=Array,a.Buf16=Array,a.Buf32=Array,a.assign(a,s))},a.setTyped(r)},{}],2:[function(t,e,a){"use strict";function n(t,e){if(e<65537&&(t.subarray&&s||!t.subarray&&i))return String.fromCharCode.apply(null,r.shrinkBuf(t,e));for(var a="",n=0;n<e;n++)a+=String.fromCharCode(t[n]);return a}var r=t("./common"),i=!0,s=!0;try{String.fromCharCode.apply(null,[0])}catch(t){i=!1}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(t){s=!1}for(var h=new r.Buf8(256),l=0;l<256;l++)h[l]=l>=252?6:l>=248?5:l>=240?4:l>=224?3:l>=192?2:1;h[254]=h[254]=1,a.string2buf=function(t){var e,a,n,i,s,h=t.length,l=0;for(i=0;i<h;i++)55296==(64512&(a=t.charCodeAt(i)))&&i+1<h&&56320==(64512&(n=t.charCodeAt(i+1)))&&(a=65536+(a-55296<<10)+(n-56320),i++),l+=a<128?1:a<2048?2:a<65536?3:4;for(e=new r.Buf8(l),s=0,i=0;s<l;i++)55296==(64512&(a=t.charCodeAt(i)))&&i+1<h&&56320==(64512&(n=t.charCodeAt(i+1)))&&(a=65536+(a-55296<<10)+(n-56320),i++),a<128?e[s++]=a:a<2048?(e[s++]=192|a>>>6,e[s++]=128|63&a):a<65536?(e[s++]=224|a>>>12,e[s++]=128|a>>>6&63,e[s++]=128|63&a):(e[s++]=240|a>>>18,e[s++]=128|a>>>12&63,e[s++]=128|a>>>6&63,e[s++]=128|63&a);return e},a.buf2binstring=function(t){return n(t,t.length)},a.binstring2buf=function(t){for(var e=new r.Buf8(t.length),a=0,n=e.length;a<n;a++)e[a]=t.charCodeAt(a);return e},a.buf2string=function(t,e){var a,r,i,s,l=e||t.length,o=new Array(2*l);for(r=0,a=0;a<l;)if((i=t[a++])<128)o[r++]=i;else if((s=h[i])>4)o[r++]=65533,a+=s-1;else{for(i&=2===s?31:3===s?15:7;s>1&&a<l;)i=i<<6|63&t[a++],s--;s>1?o[r++]=65533:i<65536?o[r++]=i:(i-=65536,o[r++]=55296|i>>10&1023,o[r++]=56320|1023&i)}return n(o,r)},a.utf8border=function(t,e){var a;for((e=e||t.length)>t.length&&(e=t.length),a=e-1;a>=0&&128==(192&t[a]);)a--;return a<0?e:0===a?e:a+h[t[a]]>e?a:e}},{"./common":1}],3:[function(t,e,a){"use strict";e.exports=function(t,e,a,n){for(var r=65535&t|0,i=t>>>16&65535|0,s=0;0!==a;){a-=s=a>2e3?2e3:a;do{i=i+(r=r+e[n++]|0)|0}while(--s);r%=65521,i%=65521}return r|i<<16|0}},{}],4:[function(t,e,a){"use strict";var n=function(){for(var t,e=[],a=0;a<256;a++){t=a;for(var n=0;n<8;n++)t=1&t?3988292384^t>>>1:t>>>1;e[a]=t}return e}();e.exports=function(t,e,a,r){var i=n,s=r+a;t^=-1;for(var h=r;h<s;h++)t=t>>>8^i[255&(t^e[h])];return-1^t}},{}],5:[function(t,e,a){"use strict";function n(t,e){return t.msg=S[e],e}function r(t){return(t<<1)-(t>4?9:0)}function i(t){for(var e=t.length;--e>=0;)t[e]=0}function s(t){var e=t.state,a=e.pending;a>t.avail_out&&(a=t.avail_out),0!==a&&(x.arraySet(t.output,e.pending_buf,e.pending_out,a,t.next_out),t.next_out+=a,e.pending_out+=a,t.total_out+=a,t.avail_out-=a,e.pending-=a,0===e.pending&&(e.pending_out=0))}function h(t,e){B._tr_flush_block(t,t.block_start>=0?t.block_start:-1,t.strstart-t.block_start,e),t.block_start=t.strstart,s(t.strm)}function l(t,e){t.pending_buf[t.pending++]=e}function o(t,e){t.pending_buf[t.pending++]=e>>>8&255,t.pending_buf[t.pending++]=255&e}function _(t,e,a,n){var r=t.avail_in;return r>n&&(r=n),0===r?0:(t.avail_in-=r,x.arraySet(e,t.input,t.next_in,r,a),1===t.state.wrap?t.adler=A(t.adler,e,r,a):2===t.state.wrap&&(t.adler=C(t.adler,e,r,a)),t.next_in+=r,t.total_in+=r,r)}function d(t,e){var a,n,r=t.max_chain_length,i=t.strstart,s=t.prev_length,h=t.nice_match,l=t.strstart>t.w_size-nt?t.strstart-(t.w_size-nt):0,o=t.window,_=t.w_mask,d=t.prev,u=t.strstart+at,f=o[i+s-1],c=o[i+s];t.prev_length>=t.good_match&&(r>>=2),h>t.lookahead&&(h=t.lookahead);do{if(a=e,o[a+s]===c&&o[a+s-1]===f&&o[a]===o[i]&&o[++a]===o[i+1]){i+=2,a++;do{}while(o[++i]===o[++a]&&o[++i]===o[++a]&&o[++i]===o[++a]&&o[++i]===o[++a]&&o[++i]===o[++a]&&o[++i]===o[++a]&&o[++i]===o[++a]&&o[++i]===o[++a]&&i<u);if(n=at-(u-i),i=u-at,n>s){if(t.match_start=e,s=n,n>=h)break;f=o[i+s-1],c=o[i+s]}}}while((e=d[e&_])>l&&0!=--r);return s<=t.lookahead?s:t.lookahead}function u(t){var e,a,n,r,i,s=t.w_size;do{if(r=t.window_size-t.lookahead-t.strstart,t.strstart>=s+(s-nt)){x.arraySet(t.window,t.window,s,s,0),t.match_start-=s,t.strstart-=s,t.block_start-=s,e=a=t.hash_size;do{n=t.head[--e],t.head[e]=n>=s?n-s:0}while(--a);e=a=s;do{n=t.prev[--e],t.prev[e]=n>=s?n-s:0}while(--a);r+=s}if(0===t.strm.avail_in)break;if(a=_(t.strm,t.window,t.strstart+t.lookahead,r),t.lookahead+=a,t.lookahead+t.insert>=et)for(i=t.strstart-t.insert,t.ins_h=t.window[i],t.ins_h=(t.ins_h<<t.hash_shift^t.window[i+1])&t.hash_mask;t.insert&&(t.ins_h=(t.ins_h<<t.hash_shift^t.window[i+et-1])&t.hash_mask,t.prev[i&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=i,i++,t.insert--,!(t.lookahead+t.insert<et)););}while(t.lookahead<nt&&0!==t.strm.avail_in)}function f(t,e){for(var a,n;;){if(t.lookahead<nt){if(u(t),t.lookahead<nt&&e===j)return ut;if(0===t.lookahead)break}if(a=0,t.lookahead>=et&&(t.ins_h=(t.ins_h<<t.hash_shift^t.window[t.strstart+et-1])&t.hash_mask,a=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart),0!==a&&t.strstart-a<=t.w_size-nt&&(t.match_length=d(t,a)),t.match_length>=et)if(n=B._tr_tally(t,t.strstart-t.match_start,t.match_length-et),t.lookahead-=t.match_length,t.match_length<=t.max_lazy_match&&t.lookahead>=et){t.match_length--;do{t.strstart++,t.ins_h=(t.ins_h<<t.hash_shift^t.window[t.strstart+et-1])&t.hash_mask,a=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart}while(0!=--t.match_length);t.strstart++}else t.strstart+=t.match_length,t.match_length=0,t.ins_h=t.window[t.strstart],t.ins_h=(t.ins_h<<t.hash_shift^t.window[t.strstart+1])&t.hash_mask;else n=B._tr_tally(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++;if(n&&(h(t,!1),0===t.strm.avail_out))return ut}return t.insert=t.strstart<et-1?t.strstart:et-1,e===D?(h(t,!0),0===t.strm.avail_out?ct:pt):t.last_lit&&(h(t,!1),0===t.strm.avail_out)?ut:ft}function c(t,e){for(var a,n,r;;){if(t.lookahead<nt){if(u(t),t.lookahead<nt&&e===j)return ut;if(0===t.lookahead)break}if(a=0,t.lookahead>=et&&(t.ins_h=(t.ins_h<<t.hash_shift^t.window[t.strstart+et-1])&t.hash_mask,a=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart),t.prev_length=t.match_length,t.prev_match=t.match_start,t.match_length=et-1,0!==a&&t.prev_length<t.max_lazy_match&&t.strstart-a<=t.w_size-nt&&(t.match_length=d(t,a),t.match_length<=5&&(t.strategy===H||t.match_length===et&&t.strstart-t.match_start>4096)&&(t.match_length=et-1)),t.prev_length>=et&&t.match_length<=t.prev_length){r=t.strstart+t.lookahead-et,n=B._tr_tally(t,t.strstart-1-t.prev_match,t.prev_length-et),t.lookahead-=t.prev_length-1,t.prev_length-=2;do{++t.strstart<=r&&(t.ins_h=(t.ins_h<<t.hash_shift^t.window[t.strstart+et-1])&t.hash_mask,a=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart)}while(0!=--t.prev_length);if(t.match_available=0,t.match_length=et-1,t.strstart++,n&&(h(t,!1),0===t.strm.avail_out))return ut}else if(t.match_available){if((n=B._tr_tally(t,0,t.window[t.strstart-1]))&&h(t,!1),t.strstart++,t.lookahead--,0===t.strm.avail_out)return ut}else t.match_available=1,t.strstart++,t.lookahead--}return t.match_available&&(n=B._tr_tally(t,0,t.window[t.strstart-1]),t.match_available=0),t.insert=t.strstart<et-1?t.strstart:et-1,e===D?(h(t,!0),0===t.strm.avail_out?ct:pt):t.last_lit&&(h(t,!1),0===t.strm.avail_out)?ut:ft}function p(t,e){for(var a,n,r,i,s=t.window;;){if(t.lookahead<=at){if(u(t),t.lookahead<=at&&e===j)return ut;if(0===t.lookahead)break}if(t.match_length=0,t.lookahead>=et&&t.strstart>0&&(r=t.strstart-1,(n=s[r])===s[++r]&&n===s[++r]&&n===s[++r])){i=t.strstart+at;do{}while(n===s[++r]&&n===s[++r]&&n===s[++r]&&n===s[++r]&&n===s[++r]&&n===s[++r]&&n===s[++r]&&n===s[++r]&&r<i);t.match_length=at-(i-r),t.match_length>t.lookahead&&(t.match_length=t.lookahead)}if(t.match_length>=et?(a=B._tr_tally(t,1,t.match_length-et),t.lookahead-=t.match_length,t.strstart+=t.match_length,t.match_length=0):(a=B._tr_tally(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++),a&&(h(t,!1),0===t.strm.avail_out))return ut}return t.insert=0,e===D?(h(t,!0),0===t.strm.avail_out?ct:pt):t.last_lit&&(h(t,!1),0===t.strm.avail_out)?ut:ft}function g(t,e){for(var a;;){if(0===t.lookahead&&(u(t),0===t.lookahead)){if(e===j)return ut;break}if(t.match_length=0,a=B._tr_tally(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++,a&&(h(t,!1),0===t.strm.avail_out))return ut}return t.insert=0,e===D?(h(t,!0),0===t.strm.avail_out?ct:pt):t.last_lit&&(h(t,!1),0===t.strm.avail_out)?ut:ft}function m(t,e,a,n,r){this.good_length=t,this.max_lazy=e,this.nice_length=a,this.max_chain=n,this.func=r}function b(t){t.window_size=2*t.w_size,i(t.head),t.max_lazy_match=z[t.level].max_lazy,t.good_match=z[t.level].good_length,t.nice_match=z[t.level].nice_length,t.max_chain_length=z[t.level].max_chain,t.strstart=0,t.block_start=0,t.lookahead=0,t.insert=0,t.match_length=t.prev_length=et-1,t.match_available=0,t.ins_h=0}function w(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=J,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new x.Buf16(2*$),this.dyn_dtree=new x.Buf16(2*(2*Y+1)),this.bl_tree=new x.Buf16(2*(2*Z+1)),i(this.dyn_ltree),i(this.dyn_dtree),i(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new x.Buf16(tt+1),this.heap=new x.Buf16(2*X+1),i(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new x.Buf16(2*X+1),i(this.depth),this.l_buf=0,this.lit_bufsize=0,this.last_lit=0,this.d_buf=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}function v(t){var e;return t&&t.state?(t.total_in=t.total_out=0,t.data_type=G,e=t.state,e.pending=0,e.pending_out=0,e.wrap<0&&(e.wrap=-e.wrap),e.status=e.wrap?it:_t,t.adler=2===e.wrap?0:1,e.last_flush=j,B._tr_init(e),O):n(t,T)}function y(t){var e=v(t);return e===O&&b(t.state),e}function k(t,e,a,r,i,s){if(!t)return T;var h=1;if(e===R&&(e=6),r<0?(h=0,r=-r):r>15&&(h=2,r-=16),i<1||i>Q||a!==J||r<8||r>15||e<0||e>9||s<0||s>M)return n(t,T);8===r&&(r=9);var l=new w;return t.state=l,l.strm=t,l.wrap=h,l.gzhead=null,l.w_bits=r,l.w_size=1<<l.w_bits,l.w_mask=l.w_size-1,l.hash_bits=i+7,l.hash_size=1<<l.hash_bits,l.hash_mask=l.hash_size-1,l.hash_shift=~~((l.hash_bits+et-1)/et),l.window=new x.Buf8(2*l.w_size),l.head=new x.Buf16(l.hash_size),l.prev=new x.Buf16(l.w_size),l.lit_bufsize=1<<i+6,l.pending_buf_size=4*l.lit_bufsize,l.pending_buf=new x.Buf8(l.pending_buf_size),l.d_buf=1*l.lit_bufsize,l.l_buf=3*l.lit_bufsize,l.level=e,l.strategy=s,l.method=a,y(t)}var z,x=t("../utils/common"),B=t("./trees"),A=t("./adler32"),C=t("./crc32"),S=t("./messages"),j=0,E=1,U=3,D=4,I=5,O=0,q=1,T=-2,L=-3,N=-5,R=-1,H=1,F=2,K=3,M=4,P=0,G=2,J=8,Q=9,V=15,W=8,X=286,Y=30,Z=19,$=2*X+1,tt=15,et=3,at=258,nt=at+et+1,rt=32,it=42,st=69,ht=73,lt=91,ot=103,_t=113,dt=666,ut=1,ft=2,ct=3,pt=4,gt=3;z=[new m(0,0,0,0,function(t,e){var a=65535;for(a>t.pending_buf_size-5&&(a=t.pending_buf_size-5);;){if(t.lookahead<=1){if(u(t),0===t.lookahead&&e===j)return ut;if(0===t.lookahead)break}t.strstart+=t.lookahead,t.lookahead=0;var n=t.block_start+a;if((0===t.strstart||t.strstart>=n)&&(t.lookahead=t.strstart-n,t.strstart=n,h(t,!1),0===t.strm.avail_out))return ut;if(t.strstart-t.block_start>=t.w_size-nt&&(h(t,!1),0===t.strm.avail_out))return ut}return t.insert=0,e===D?(h(t,!0),0===t.strm.avail_out?ct:pt):(t.strstart>t.block_start&&(h(t,!1),t.strm.avail_out),ut)}),new m(4,4,8,4,f),new m(4,5,16,8,f),new m(4,6,32,32,f),new m(4,4,16,16,c),new m(8,16,32,32,c),new m(8,16,128,128,c),new m(8,32,128,256,c),new m(32,128,258,1024,c),new m(32,258,258,4096,c)],a.deflateInit=function(t,e){return k(t,e,J,V,W,P)},a.deflateInit2=k,a.deflateReset=y,a.deflateResetKeep=v,a.deflateSetHeader=function(t,e){return t&&t.state?2!==t.state.wrap?T:(t.state.gzhead=e,O):T},a.deflate=function(t,e){var a,h,_,d;if(!t||!t.state||e>I||e<0)return t?n(t,T):T;if(h=t.state,!t.output||!t.input&&0!==t.avail_in||h.status===dt&&e!==D)return n(t,0===t.avail_out?N:T);if(h.strm=t,a=h.last_flush,h.last_flush=e,h.status===it)if(2===h.wrap)t.adler=0,l(h,31),l(h,139),l(h,8),h.gzhead?(l(h,(h.gzhead.text?1:0)+(h.gzhead.hcrc?2:0)+(h.gzhead.extra?4:0)+(h.gzhead.name?8:0)+(h.gzhead.comment?16:0)),l(h,255&h.gzhead.time),l(h,h.gzhead.time>>8&255),l(h,h.gzhead.time>>16&255),l(h,h.gzhead.time>>24&255),l(h,9===h.level?2:h.strategy>=F||h.level<2?4:0),l(h,255&h.gzhead.os),h.gzhead.extra&&h.gzhead.extra.length&&(l(h,255&h.gzhead.extra.length),l(h,h.gzhead.extra.length>>8&255)),h.gzhead.hcrc&&(t.adler=C(t.adler,h.pending_buf,h.pending,0)),h.gzindex=0,h.status=st):(l(h,0),l(h,0),l(h,0),l(h,0),l(h,0),l(h,9===h.level?2:h.strategy>=F||h.level<2?4:0),l(h,gt),h.status=_t);else{var u=J+(h.w_bits-8<<4)<<8;u|=(h.strategy>=F||h.level<2?0:h.level<6?1:6===h.level?2:3)<<6,0!==h.strstart&&(u|=rt),u+=31-u%31,h.status=_t,o(h,u),0!==h.strstart&&(o(h,t.adler>>>16),o(h,65535&t.adler)),t.adler=1}if(h.status===st)if(h.gzhead.extra){for(_=h.pending;h.gzindex<(65535&h.gzhead.extra.length)&&(h.pending!==h.pending_buf_size||(h.gzhead.hcrc&&h.pending>_&&(t.adler=C(t.adler,h.pending_buf,h.pending-_,_)),s(t),_=h.pending,h.pending!==h.pending_buf_size));)l(h,255&h.gzhead.extra[h.gzindex]),h.gzindex++;h.gzhead.hcrc&&h.pending>_&&(t.adler=C(t.adler,h.pending_buf,h.pending-_,_)),h.gzindex===h.gzhead.extra.length&&(h.gzindex=0,h.status=ht)}else h.status=ht;if(h.status===ht)if(h.gzhead.name){_=h.pending;do{if(h.pending===h.pending_buf_size&&(h.gzhead.hcrc&&h.pending>_&&(t.adler=C(t.adler,h.pending_buf,h.pending-_,_)),s(t),_=h.pending,h.pending===h.pending_buf_size)){d=1;break}d=h.gzindex<h.gzhead.name.length?255&h.gzhead.name.charCodeAt(h.gzindex++):0,l(h,d)}while(0!==d);h.gzhead.hcrc&&h.pending>_&&(t.adler=C(t.adler,h.pending_buf,h.pending-_,_)),0===d&&(h.gzindex=0,h.status=lt)}else h.status=lt;if(h.status===lt)if(h.gzhead.comment){_=h.pending;do{if(h.pending===h.pending_buf_size&&(h.gzhead.hcrc&&h.pending>_&&(t.adler=C(t.adler,h.pending_buf,h.pending-_,_)),s(t),_=h.pending,h.pending===h.pending_buf_size)){d=1;break}d=h.gzindex<h.gzhead.comment.length?255&h.gzhead.comment.charCodeAt(h.gzindex++):0,l(h,d)}while(0!==d);h.gzhead.hcrc&&h.pending>_&&(t.adler=C(t.adler,h.pending_buf,h.pending-_,_)),0===d&&(h.status=ot)}else h.status=ot;if(h.status===ot&&(h.gzhead.hcrc?(h.pending+2>h.pending_buf_size&&s(t),h.pending+2<=h.pending_buf_size&&(l(h,255&t.adler),l(h,t.adler>>8&255),t.adler=0,h.status=_t)):h.status=_t),0!==h.pending){if(s(t),0===t.avail_out)return h.last_flush=-1,O}else if(0===t.avail_in&&r(e)<=r(a)&&e!==D)return n(t,N);if(h.status===dt&&0!==t.avail_in)return n(t,N);if(0!==t.avail_in||0!==h.lookahead||e!==j&&h.status!==dt){var f=h.strategy===F?g(h,e):h.strategy===K?p(h,e):z[h.level].func(h,e);if(f!==ct&&f!==pt||(h.status=dt),f===ut||f===ct)return 0===t.avail_out&&(h.last_flush=-1),O;if(f===ft&&(e===E?B._tr_align(h):e!==I&&(B._tr_stored_block(h,0,0,!1),e===U&&(i(h.head),0===h.lookahead&&(h.strstart=0,h.block_start=0,h.insert=0))),s(t),0===t.avail_out))return h.last_flush=-1,O}return e!==D?O:h.wrap<=0?q:(2===h.wrap?(l(h,255&t.adler),l(h,t.adler>>8&255),l(h,t.adler>>16&255),l(h,t.adler>>24&255),l(h,255&t.total_in),l(h,t.total_in>>8&255),l(h,t.total_in>>16&255),l(h,t.total_in>>24&255)):(o(h,t.adler>>>16),o(h,65535&t.adler)),s(t),h.wrap>0&&(h.wrap=-h.wrap),0!==h.pending?O:q)},a.deflateEnd=function(t){var e;return t&&t.state?(e=t.state.status)!==it&&e!==st&&e!==ht&&e!==lt&&e!==ot&&e!==_t&&e!==dt?n(t,T):(t.state=null,e===_t?n(t,L):O):T},a.deflateSetDictionary=function(t,e){var a,n,r,s,h,l,o,_,d=e.length;if(!t||!t.state)return T;if(a=t.state,2===(s=a.wrap)||1===s&&a.status!==it||a.lookahead)return T;for(1===s&&(t.adler=A(t.adler,e,d,0)),a.wrap=0,d>=a.w_size&&(0===s&&(i(a.head),a.strstart=0,a.block_start=0,a.insert=0),_=new x.Buf8(a.w_size),x.arraySet(_,e,d-a.w_size,a.w_size,0),e=_,d=a.w_size),h=t.avail_in,l=t.next_in,o=t.input,t.avail_in=d,t.next_in=0,t.input=e,u(a);a.lookahead>=et;){n=a.strstart,r=a.lookahead-(et-1);do{a.ins_h=(a.ins_h<<a.hash_shift^a.window[n+et-1])&a.hash_mask,a.prev[n&a.w_mask]=a.head[a.ins_h],a.head[a.ins_h]=n,n++}while(--r);a.strstart=n,a.lookahead=et-1,u(a)}return a.strstart+=a.lookahead,a.block_start=a.strstart,a.insert=a.lookahead,a.lookahead=0,a.match_length=a.prev_length=et-1,a.match_available=0,t.next_in=l,t.input=o,t.avail_in=h,a.wrap=s,O},a.deflateInfo="pako deflate (from Nodeca project)"},{"../utils/common":1,"./adler32":3,"./crc32":4,"./messages":6,"./trees":7}],6:[function(t,e,a){"use strict";e.exports={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"}},{}],7:[function(t,e,a){"use strict";function n(t){for(var e=t.length;--e>=0;)t[e]=0}function r(t,e,a,n,r){this.static_tree=t,this.extra_bits=e,this.extra_base=a,this.elems=n,this.max_length=r,this.has_stree=t&&t.length}function i(t,e){this.dyn_tree=t,this.max_code=0,this.stat_desc=e}function s(t){return t<256?et[t]:et[256+(t>>>7)]}function h(t,e){t.pending_buf[t.pending++]=255&e,t.pending_buf[t.pending++]=e>>>8&255}function l(t,e,a){t.bi_valid>M-a?(t.bi_buf|=e<<t.bi_valid&65535,h(t,t.bi_buf),t.bi_buf=e>>M-t.bi_valid,t.bi_valid+=a-M):(t.bi_buf|=e<<t.bi_valid&65535,t.bi_valid+=a)}function o(t,e,a){l(t,a[2*e],a[2*e+1])}function _(t,e){var a=0;do{a|=1&t,t>>>=1,a<<=1}while(--e>0);return a>>>1}function d(t){16===t.bi_valid?(h(t,t.bi_buf),t.bi_buf=0,t.bi_valid=0):t.bi_valid>=8&&(t.pending_buf[t.pending++]=255&t.bi_buf,t.bi_buf>>=8,t.bi_valid-=8)}function u(t,e){var a,n,r,i,s,h,l=e.dyn_tree,o=e.max_code,_=e.stat_desc.static_tree,d=e.stat_desc.has_stree,u=e.stat_desc.extra_bits,f=e.stat_desc.extra_base,c=e.stat_desc.max_length,p=0;for(i=0;i<=K;i++)t.bl_count[i]=0;for(l[2*t.heap[t.heap_max]+1]=0,a=t.heap_max+1;a<F;a++)(i=l[2*l[2*(n=t.heap[a])+1]+1]+1)>c&&(i=c,p++),l[2*n+1]=i,n>o||(t.bl_count[i]++,s=0,n>=f&&(s=u[n-f]),h=l[2*n],t.opt_len+=h*(i+s),d&&(t.static_len+=h*(_[2*n+1]+s)));if(0!==p){do{for(i=c-1;0===t.bl_count[i];)i--;t.bl_count[i]--,t.bl_count[i+1]+=2,t.bl_count[c]--,p-=2}while(p>0);for(i=c;0!==i;i--)for(n=t.bl_count[i];0!==n;)(r=t.heap[--a])>o||(l[2*r+1]!==i&&(t.opt_len+=(i-l[2*r+1])*l[2*r],l[2*r+1]=i),n--)}}function f(t,e,a){var n,r,i=new Array(K+1),s=0;for(n=1;n<=K;n++)i[n]=s=s+a[n-1]<<1;for(r=0;r<=e;r++){var h=t[2*r+1];0!==h&&(t[2*r]=_(i[h]++,h))}}function c(){var t,e,a,n,i,s=new Array(K+1);for(a=0,n=0;n<T-1;n++)for(nt[n]=a,t=0;t<1<<W[n];t++)at[a++]=n;for(at[a-1]=n,i=0,n=0;n<16;n++)for(rt[n]=i,t=0;t<1<<X[n];t++)et[i++]=n;for(i>>=7;n<R;n++)for(rt[n]=i<<7,t=0;t<1<<X[n]-7;t++)et[256+i++]=n;for(e=0;e<=K;e++)s[e]=0;for(t=0;t<=143;)$[2*t+1]=8,t++,s[8]++;for(;t<=255;)$[2*t+1]=9,t++,s[9]++;for(;t<=279;)$[2*t+1]=7,t++,s[7]++;for(;t<=287;)$[2*t+1]=8,t++,s[8]++;for(f($,N+1,s),t=0;t<R;t++)tt[2*t+1]=5,tt[2*t]=_(t,5);it=new r($,W,L+1,N,K),st=new r(tt,X,0,R,K),ht=new r(new Array(0),Y,0,H,P)}function p(t){var e;for(e=0;e<N;e++)t.dyn_ltree[2*e]=0;for(e=0;e<R;e++)t.dyn_dtree[2*e]=0;for(e=0;e<H;e++)t.bl_tree[2*e]=0;t.dyn_ltree[2*G]=1,t.opt_len=t.static_len=0,t.last_lit=t.matches=0}function g(t){t.bi_valid>8?h(t,t.bi_buf):t.bi_valid>0&&(t.pending_buf[t.pending++]=t.bi_buf),t.bi_buf=0,t.bi_valid=0}function m(t,e,a,n){g(t),n&&(h(t,a),h(t,~a)),S.arraySet(t.pending_buf,t.window,e,a,t.pending),t.pending+=a}function b(t,e,a,n){var r=2*e,i=2*a;return t[r]<t[i]||t[r]===t[i]&&n[e]<=n[a]}function w(t,e,a){for(var n=t.heap[a],r=a<<1;r<=t.heap_len&&(r<t.heap_len&&b(e,t.heap[r+1],t.heap[r],t.depth)&&r++,!b(e,n,t.heap[r],t.depth));)t.heap[a]=t.heap[r],a=r,r<<=1;t.heap[a]=n}function v(t,e,a){var n,r,i,h,_=0;if(0!==t.last_lit)do{n=t.pending_buf[t.d_buf+2*_]<<8|t.pending_buf[t.d_buf+2*_+1],r=t.pending_buf[t.l_buf+_],_++,0===n?o(t,r,e):(o(t,(i=at[r])+L+1,e),0!==(h=W[i])&&l(t,r-=nt[i],h),o(t,i=s(--n),a),0!==(h=X[i])&&l(t,n-=rt[i],h))}while(_<t.last_lit);o(t,G,e)}function y(t,e){var a,n,r,i=e.dyn_tree,s=e.stat_desc.static_tree,h=e.stat_desc.has_stree,l=e.stat_desc.elems,o=-1;for(t.heap_len=0,t.heap_max=F,a=0;a<l;a++)0!==i[2*a]?(t.heap[++t.heap_len]=o=a,t.depth[a]=0):i[2*a+1]=0;for(;t.heap_len<2;)i[2*(r=t.heap[++t.heap_len]=o<2?++o:0)]=1,t.depth[r]=0,t.opt_len--,h&&(t.static_len-=s[2*r+1]);for(e.max_code=o,a=t.heap_len>>1;a>=1;a--)w(t,i,a);r=l;do{a=t.heap[1],t.heap[1]=t.heap[t.heap_len--],w(t,i,1),n=t.heap[1],t.heap[--t.heap_max]=a,t.heap[--t.heap_max]=n,i[2*r]=i[2*a]+i[2*n],t.depth[r]=(t.depth[a]>=t.depth[n]?t.depth[a]:t.depth[n])+1,i[2*a+1]=i[2*n+1]=r,t.heap[1]=r++,w(t,i,1)}while(t.heap_len>=2);t.heap[--t.heap_max]=t.heap[1],u(t,e),f(i,o,t.bl_count)}function k(t,e,a){var n,r,i=-1,s=e[1],h=0,l=7,o=4;for(0===s&&(l=138,o=3),e[2*(a+1)+1]=65535,n=0;n<=a;n++)r=s,s=e[2*(n+1)+1],++h<l&&r===s||(h<o?t.bl_tree[2*r]+=h:0!==r?(r!==i&&t.bl_tree[2*r]++,t.bl_tree[2*J]++):h<=10?t.bl_tree[2*Q]++:t.bl_tree[2*V]++,h=0,i=r,0===s?(l=138,o=3):r===s?(l=6,o=3):(l=7,o=4))}function z(t,e,a){var n,r,i=-1,s=e[1],h=0,_=7,d=4;for(0===s&&(_=138,d=3),n=0;n<=a;n++)if(r=s,s=e[2*(n+1)+1],!(++h<_&&r===s)){if(h<d)do{o(t,r,t.bl_tree)}while(0!=--h);else 0!==r?(r!==i&&(o(t,r,t.bl_tree),h--),o(t,J,t.bl_tree),l(t,h-3,2)):h<=10?(o(t,Q,t.bl_tree),l(t,h-3,3)):(o(t,V,t.bl_tree),l(t,h-11,7));h=0,i=r,0===s?(_=138,d=3):r===s?(_=6,d=3):(_=7,d=4)}}function x(t){var e;for(k(t,t.dyn_ltree,t.l_desc.max_code),k(t,t.dyn_dtree,t.d_desc.max_code),y(t,t.bl_desc),e=H-1;e>=3&&0===t.bl_tree[2*Z[e]+1];e--);return t.opt_len+=3*(e+1)+5+5+4,e}function B(t,e,a,n){var r;for(l(t,e-257,5),l(t,a-1,5),l(t,n-4,4),r=0;r<n;r++)l(t,t.bl_tree[2*Z[r]+1],3);z(t,t.dyn_ltree,e-1),z(t,t.dyn_dtree,a-1)}function A(t){var e,a=4093624447;for(e=0;e<=31;e++,a>>>=1)if(1&a&&0!==t.dyn_ltree[2*e])return E;if(0!==t.dyn_ltree[18]||0!==t.dyn_ltree[20]||0!==t.dyn_ltree[26])return U;for(e=32;e<L;e++)if(0!==t.dyn_ltree[2*e])return U;return E}function C(t,e,a,n){l(t,(I<<1)+(n?1:0),3),m(t,e,a,!0)}var S=t("../utils/common"),j=4,E=0,U=1,D=2,I=0,O=1,q=2,T=29,L=256,N=L+1+T,R=30,H=19,F=2*N+1,K=15,M=16,P=7,G=256,J=16,Q=17,V=18,W=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],X=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],Y=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],Z=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],$=new Array(2*(N+2));n($);var tt=new Array(2*R);n(tt);var et=new Array(512);n(et);var at=new Array(256);n(at);var nt=new Array(T);n(nt);var rt=new Array(R);n(rt);var it,st,ht,lt=!1;a._tr_init=function(t){lt||(c(),lt=!0),t.l_desc=new i(t.dyn_ltree,it),t.d_desc=new i(t.dyn_dtree,st),t.bl_desc=new i(t.bl_tree,ht),t.bi_buf=0,t.bi_valid=0,p(t)},a._tr_stored_block=C,a._tr_flush_block=function(t,e,a,n){var r,i,s=0;t.level>0?(t.strm.data_type===D&&(t.strm.data_type=A(t)),y(t,t.l_desc),y(t,t.d_desc),s=x(t),r=t.opt_len+3+7>>>3,(i=t.static_len+3+7>>>3)<=r&&(r=i)):r=i=a+5,a+4<=r&&-1!==e?C(t,e,a,n):t.strategy===j||i===r?(l(t,(O<<1)+(n?1:0),3),v(t,$,tt)):(l(t,(q<<1)+(n?1:0),3),B(t,t.l_desc.max_code+1,t.d_desc.max_code+1,s+1),v(t,t.dyn_ltree,t.dyn_dtree)),p(t),n&&g(t)},a._tr_tally=function(t,e,a){return t.pending_buf[t.d_buf+2*t.last_lit]=e>>>8&255,t.pending_buf[t.d_buf+2*t.last_lit+1]=255&e,t.pending_buf[t.l_buf+t.last_lit]=255&a,t.last_lit++,0===e?t.dyn_ltree[2*a]++:(t.matches++,e--,t.dyn_ltree[2*(at[a]+L+1)]++,t.dyn_dtree[2*s(e)]++),t.last_lit===t.lit_bufsize-1},a._tr_align=function(t){l(t,O<<1,3),o(t,G,$),d(t)}},{"../utils/common":1}],8:[function(t,e,a){"use strict";e.exports=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}},{}],"/lib/deflate.js":[function(t,e,a){"use strict";function n(t){if(!(this instanceof n))return new n(t);this.options=s.assign({level:u,method:c,chunkSize:16384,windowBits:15,memLevel:8,strategy:f,to:""},t||{});var e=this.options;e.raw&&e.windowBits>0?e.windowBits=-e.windowBits:e.gzip&&e.windowBits>0&&e.windowBits<16&&(e.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new o,this.strm.avail_out=0;var a=i.deflateInit2(this.strm,e.level,e.method,e.windowBits,e.memLevel,e.strategy);if(a!==d)throw new Error(l[a]);if(e.header&&i.deflateSetHeader(this.strm,e.header),e.dictionary){var r;if(r="string"==typeof e.dictionary?h.string2buf(e.dictionary):"[object ArrayBuffer]"===_.call(e.dictionary)?new Uint8Array(e.dictionary):e.dictionary,(a=i.deflateSetDictionary(this.strm,r))!==d)throw new Error(l[a]);this._dict_set=!0}}function r(t,e){var a=new n(e);if(a.push(t,!0),a.err)throw a.msg||l[a.err];return a.result}var i=t("./zlib/deflate"),s=t("./utils/common"),h=t("./utils/strings"),l=t("./zlib/messages"),o=t("./zlib/zstream"),_=Object.prototype.toString,d=0,u=-1,f=0,c=8;n.prototype.push=function(t,e){var a,n,r=this.strm,l=this.options.chunkSize;if(this.ended)return!1;n=e===~~e?e:!0===e?4:0,"string"==typeof t?r.input=h.string2buf(t):"[object ArrayBuffer]"===_.call(t)?r.input=new Uint8Array(t):r.input=t,r.next_in=0,r.avail_in=r.input.length;do{if(0===r.avail_out&&(r.output=new s.Buf8(l),r.next_out=0,r.avail_out=l),1!==(a=i.deflate(r,n))&&a!==d)return this.onEnd(a),this.ended=!0,!1;0!==r.avail_out&&(0!==r.avail_in||4!==n&&2!==n)||("string"===this.options.to?this.onData(h.buf2binstring(s.shrinkBuf(r.output,r.next_out))):this.onData(s.shrinkBuf(r.output,r.next_out)))}while((r.avail_in>0||0===r.avail_out)&&1!==a);return 4===n?(a=i.deflateEnd(this.strm),this.onEnd(a),this.ended=!0,a===d):2!==n||(this.onEnd(d),r.avail_out=0,!0)},n.prototype.onData=function(t){this.chunks.push(t)},n.prototype.onEnd=function(t){t===d&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=s.flattenChunks(this.chunks)),this.chunks=[],this.err=t,this.msg=this.strm.msg},a.Deflate=n,a.deflate=r,a.deflateRaw=function(t,e){return e=e||{},e.raw=!0,r(t,e)},a.gzip=function(t,e){return e=e||{},e.gzip=!0,r(t,e)}},{"./utils/common":1,"./utils/strings":2,"./zlib/deflate":5,"./zlib/messages":6,"./zlib/zstream":8}]},{},[])("/lib/deflate.js")});

	/* mobile device detection */
	var ju_MobileEsp={initCompleted:!1,isWebkit:!1,isIphone:!1,isAndroid:!1,isAndroidPhone:!1,isTierIphone:!1,engineWebKit:"webkit",deviceIphone:"iphone",deviceIpod:"ipod",deviceIpad:"ipad",deviceAndroid:"android",deviceGoogleTV:"googletv",deviceWinPhone7:"windows phone os 7",deviceWinPhone8:"windows phone 8",deviceWinPhone10:"windows phone 10",deviceBB:"blackberry",deviceBB10:"bb10",vndRIM:"vnd.rim",deviceBBStorm:"blackberry95",deviceBBBold:"blackberry97",deviceBBBoldTouch:"blackberry 99",deviceBBCurve:"blackberry89",deviceBBCurveTouch:"blackberry 938",deviceBBTorch:"blackberry 98",deviceWebOS:"webos",deviceBada:"bada",deviceTizen:"tizen",deviceMeego:"meego",deviceSailfish:"sailfish",deviceUbuntu:"ubuntu",devicePlaystation:"playstation",devicePlaystationVita:"vita",engineFirefox:"firefox",engineOpera:"opera",devicePda:"pda",mini:"mini",mobile:"mobile",mobi:"mobi",uagent:"",InitDeviceScan:function(){this.initCompleted=!1,navigator&&navigator.userAgent&&(this.uagent=navigator.userAgent.toLowerCase()),this.isWebkit=this.DetectWebkit(),this.isIphone=this.DetectIphone(),this.isAndroid=this.DetectAndroid(),this.isAndroidPhone=this.DetectAndroidPhone(),this.isTierIphone=this.DetectTierIphone(),this.initCompleted=!0},DetectIphone:function(){return this.initCompleted||this.isIphone?this.isIphone:-1<this.uagent.search(this.deviceIphone)&&(!this.DetectIpad()&&!this.DetectIpod())},DetectIpod:function(){return-1<this.uagent.search(this.deviceIpod)},DetectIphoneOrIpod:function(){return!(!this.DetectIphone()&&!this.DetectIpod())},DetectIos:function(){return!(!this.DetectIphoneOrIpod()&&!this.DetectIpad())},DetectAndroid:function(){return this.initCompleted||this.isAndroid?this.isAndroid:!!(-1<this.uagent.search(this.deviceAndroid)||this.DetectGoogleTV())},DetectAndroidPhone:function(){return this.initCompleted||this.isAndroidPhone?this.isAndroidPhone:!!this.DetectAndroid()&&(-1<this.uagent.search(this.mobile)||!!this.DetectOperaMobile())},DetectGoogleTV:function(){return-1<this.uagent.search(this.deviceGoogleTV)},DetectIpad:function(){return!!(-1<this.uagent.search(this.deviceIpad)&&this.DetectWebkit())},DetectWebkit:function(){return this.initCompleted||this.isWebkit?this.isWebkit:-1<this.uagent.search(this.engineWebKit)},DetectWindowsPhone:function(){return!!(this.DetectWindowsPhone7()||this.DetectWindowsPhone8()||this.DetectWindowsPhone10())},DetectWindowsPhone7:function(){return-1<this.uagent.search(this.deviceWinPhone7)},DetectWindowsPhone8:function(){return-1<this.uagent.search(this.deviceWinPhone8)},DetectWindowsPhone10:function(){return-1<this.uagent.search(this.deviceWinPhone10)},DetectBlackBerry:function(){return-1<this.uagent.search(this.deviceBB)||-1<this.uagent.search(this.vndRIM)||!!this.DetectBlackBerry10Phone()},DetectBlackBerry10Phone:function(){return-1<this.uagent.search(this.deviceBB10)&&-1<this.uagent.search(this.mobile)},DetectBlackBerryWebKit:function(){return!!(this.DetectBlackBerry()&&-1<this.uagent.search(this.engineWebKit))},DetectBlackBerryTouch:function(){return!(!this.DetectBlackBerry()||!(-1<this.uagent.search(this.deviceBBStorm)||-1<this.uagent.search(this.deviceBBTorch)||-1<this.uagent.search(this.deviceBBBoldTouch)||-1<this.uagent.search(this.deviceBBCurveTouch)))},DetectPalmWebOS:function(){return-1<this.uagent.search(this.deviceWebOS)},DetectBada:function(){return-1<this.uagent.search(this.deviceBada)},DetectTizen:function(){return-1<this.uagent.search(this.deviceTizen)&&-1<this.uagent.search(this.mobile)},DetectFirefoxOSPhone:function(){return!(this.DetectIos()||this.DetectAndroid()||this.DetectSailfish())&&(-1<this.uagent.search(this.engineFirefox)&&-1<this.uagent.search(this.mobile))},DetectSailfish:function(){return-1<this.uagent.search(this.deviceSailfish)},DetectSailfishPhone:function(){return!!(this.DetectSailfish()&&-1<this.uagent.search(this.mobile))},DetectUbuntuPhone:function(){return-1<this.uagent.search(this.deviceUbuntu)&&-1<this.uagent.search(this.mobile)},DetectOperaMobile:function(){return-1<this.uagent.search(this.engineOpera)&&(-1<this.uagent.search(this.mini)||-1<this.uagent.search(this.mobi))},DetectGamingHandheld:function(){return-1<this.uagent.search(this.devicePlaystation)&&-1<this.uagent.search(this.devicePlaystationVita)},DetectTierIphone:function(){return this.initCompleted||this.isTierIphone?this.isTierIphone:!!(this.DetectIphoneOrIpod()||this.DetectAndroidPhone()||this.DetectWindowsPhone()||this.DetectBlackBerry10Phone()||this.DetectPalmWebOS()||this.DetectBada()||this.DetectTizen()||this.DetectFirefoxOSPhone()||this.DetectSailfishPhone()||this.DetectUbuntuPhone()||this.DetectGamingHandheld())||!(!this.DetectBlackBerryWebKit()||!this.DetectBlackBerryTouch())}};ju_MobileEsp.InitDeviceScan();

	/* bilitite - used for typing */
	!function(){var s="onfocusin"in document.createElement("input")?"focusin":"focus",t=document.createElement("div");t.appendChild(document.createTextNode("x-")),t.appendChild(document.createTextNode("x")),t.normalize();var n=3==t.firstChild.length;function e(){}function l(){}function u(){}function c(){}function h(t,e){if(t.firstChild)return t.firstChild;if(t.nextSibling)return t.nextSibling;if(t===e)return null;for(;t.parentNode;){if((t=t.parentNode)==e)return null;if(t.nextSibling)return t.nextSibling}return null}function i(t,e,n,i){if(!(e<=0)){var o=t[n?"startContainer":"endContainer"];for(3==o.nodeType&&(e+=t[n?"startOffset":"endOffset"]);o;){if(3==o.nodeType){var r=o.nodeValue.length;if(e<=r){if(t[n?"setStart":"setEnd"](o,e),e==r){for(var a=h(o,i);a&&3==a.nodeType&&0==a.nodeValue.length;a=h(a,i))t[n?"setStartAfter":"setEndAfter"](a);a&&1==a.nodeType&&"BR"==a.nodeName&&t[n?"setStartAfter":"setEndAfter"](a)}return}t[n?"setStartAfter":"setEndAfter"](o),e-=r}o=h(o,i)}}}bililiteRange=function(e,t){var n,i;if(t)n=new v;else if(window.getSelection&&e.setSelectionRange)try{e.selectionStart,n=new u}catch(t){n=new v}else n=window.getSelection?new c:document.selection?new l:new v;if(n._el=e,n._doc=e.ownerDocument,n._win="defaultView"in n._doc?n._doc.defaultView:n._doc.parentWindow,n._textProp=void 0!==(i=e).value?"value":void 0!==i.text?"text":void 0!==i.textContent?"textContent":"innerText",n._bounds=[0,n.length()],!("bililiteRangeMouseDown"in n._doc)){var o={_el:n._doc};n._doc.bililiteRangeMouseDown=!1,bililiteRange.fn.listen.call(o,"mousedown",function(){n._doc.bililiteRangeMouseDown=!0}),bililiteRange.fn.listen.call(o,"mouseup",function(){n._doc.bililiteRangeMouseDown=!1})}if(!("bililiteRangeSelection"in e)){function r(t){t&&9==t.which?n._nativeSelect(n._nativeRange(e.bililiteRangeSelection)):e.bililiteRangeSelection=n._nativeSelection()}r(),"onbeforedeactivate"in e?n.listen("beforedeactivate",r):n.listen("mouseup",r).listen("keyup",r),n.listen(s,function(){n._doc.bililiteRangeMouseDown||n._nativeSelect(n._nativeRange(e.bililiteRangeSelection))})}if(!("oninput"in e)){var a=function(){n.dispatch({type:"input",bubbles:!0})};n.listen("keyup",a),n.listen("cut",a),n.listen("paste",a),n.listen("drop",a),e.oninput="patched"}return n},e.prototype={length:function(){return this._el[this._textProp].replace(/\r/g,"").length},bounds:function(t){if(bililiteRange.bounds[t])this._bounds=bililiteRange.bounds[t].apply(this);else{if(!t){var e=[Math.max(0,Math.min(this.length(),this._bounds[0])),Math.max(0,Math.min(this.length(),this._bounds[1]))];return e[1]=Math.max(e[0],e[1]),e}this._bounds=t}return this},select:function(){var t=this._el.bililiteRangeSelection=this.bounds();return this._el===this._doc.activeElement&&this._nativeSelect(this._nativeRange(t)),this.dispatch({type:"select",bubbles:!0}),this},text:function(t,e){if(arguments.length){var n=this.bounds();this._el;return this.dispatch({type:"beforeinput",bubbles:!0,data:t,bounds:n}),this._nativeSetText(t,this._nativeRange(n)),"start"==e?this.bounds([n[0],n[0]]):"end"==e?this.bounds([n[0]+t.length,n[0]+t.length]):"all"==e&&this.bounds([n[0],n[0]+t.length]),this.dispatch({type:"input",bubbles:!0,data:t,bounds:n}),this}return this._nativeGetText(this._nativeRange(this.bounds())).replace(/\r/g,"")},insertEOL:function(){return this._nativeEOL(),this._bounds=[this._bounds[0]+1,this._bounds[0]+1],this},sendkeys:function(t){var e=this;function n(t,e){/^{[^}]*}$/.test(e)&&(e=e.slice(1,-1));for(var n=0;n<e.length;++n){var i=e.charCodeAt(n);t.dispatch({type:"keypress",bubbles:!0,keyCode:i,which:i,charCode:i})}t.text(e,"end")}return this.data().sendkeysOriginalText=this.text(),this.data().sendkeysBounds=void 0,t.replace(/{[^}]*}|[^{]+|{/g,function(t){(bililiteRange.sendkeys[t]||n)(e,t,n)}),this.bounds(this.data().sendkeysBounds),this.dispatch({type:"sendkeys",which:t}),this},top:function(){return this._nativeTop(this._nativeRange(this.bounds()))},scrollIntoView:function(t){var e=this.top();return(this._el.scrollTop>e||this._el.scrollTop+this._el.clientHeight<e)&&(t?t.call(this._el,e):this._el.scrollTop=e),this},wrap:function(t){return this._nativeWrap(t,this._nativeRange(this.bounds())),this},selection:function(t){return arguments.length?this.bounds("selection").text(t,"end").select():this.bounds("selection").text()},clone:function(){return bililiteRange(this._el).bounds(this.bounds())},all:function(t){return arguments.length?(this.dispatch({type:"beforeinput",bubbles:!0,data:t}),this._el[this._textProp]=t,this.dispatch({type:"input",bubbles:!0,data:t}),this):this._el[this._textProp].replace(/\r/g,"")},element:function(){return this._el},dispatch:function(i){i=i||{};var o=document.createEvent?document.createEvent("CustomEvent"):this._doc.createEventObject();for(var t in o.initCustomEvent&&o.initCustomEvent(i.type,!!i.bubbles,!!i.cancelable,i.detail),i)o[t]=i[t];var r=this._el;return setTimeout(function(){try{r.dispatchEvent?r.dispatchEvent(o):r.fireEvent("on"+i.type,document.createEventObject())}catch(t){var e=r["listen"+i.type];if(e)for(var n=0;n<e.length;++n)e[n].call(r,o)}},0),this},listen:function(t,e){var n=this._el;n.addEventListener?n.addEventListener(t,e):(n.attachEvent("on"+t,e),(n["listen"+t]=n["listen"+t]||[]).push(e));return this},dontlisten:function(e,n){var i=this._el;if(i.removeEventListener)i.removeEventListener(e,n);else try{i.detachEvent("on"+e,n)}catch(t){var o=i["listen"+e];if(o)for(var r=0;r<o.length;++r)o[r]===n&&(o[r]=function(){})}return this}},bililiteRange.fn=e.prototype,bililiteRange.extend=function(t){for(fn in t)e.prototype[fn]=t[fn]},bililiteRange.bounds={all:function(){return[0,this.length()]},start:function(){return[0,0]},end:function(){return[this.length(),this.length()]},selection:function(){return this._el===this._doc.activeElement?(this.bounds("all"),this._nativeSelection()):this._el.bililiteRangeSelection}},bililiteRange.sendkeys={"{enter}":function(t){t.dispatch({type:"keypress",bubbles:!0,keyCode:"\n",which:"\n",charCode:"\n"}),t.insertEOL()},"{tab}":function(t,e,n){n(t,"\t")},"{newline}":function(t,e,n){n(t,"\n")},"{backspace}":function(t){var e=t.bounds();e[0]==e[1]&&t.bounds([e[0]-1,e[0]]),t.text("","end")},"{del}":function(t){var e=t.bounds();e[0]==e[1]&&t.bounds([e[0],e[0]+1]),t.text("","end")},"{rightarrow}":function(t){var e=t.bounds();e[0]==e[1]&&++e[1],t.bounds([e[1],e[1]])},"{leftarrow}":function(t){var e=t.bounds();e[0]==e[1]&&--e[0],t.bounds([e[0],e[0]])},"{selectall}":function(t){t.bounds("all")},"{selection}":function(t){for(var e=t.data().sendkeysOriginalText,n=0;n<e.length;++n){var i=e.charCodeAt(n);t.dispatch({type:"keypress",bubbles:!0,keyCode:i,which:i,charCode:i})}t.text(e,"end")},"{mark}":function(t){t.data().sendkeysBounds=t.bounds()}},bililiteRange.sendkeys["{Enter}"]=bililiteRange.sendkeys["{enter}"],bililiteRange.sendkeys["{Backspace}"]=bililiteRange.sendkeys["{backspace}"],bililiteRange.sendkeys["{Delete}"]=bililiteRange.sendkeys["{del}"],bililiteRange.sendkeys["{ArrowRight}"]=bililiteRange.sendkeys["{rightarrow}"],bililiteRange.sendkeys["{ArrowLeft}"]=bililiteRange.sendkeys["{leftarrow}"],(l.prototype=new e)._nativeRange=function(t){var e;return"INPUT"==this._el.tagName?e=this._el.createTextRange():(e=this._doc.body.createTextRange()).moveToElementText(this._el),t&&(t[1]<0&&(t[1]=0),t[0]>this.length()&&(t[0]=this.length()),t[1]<e.text.replace(/\r/g,"").length&&(e.moveEnd("character",-1),e.moveEnd("character",t[1]-e.text.replace(/\r/g,"").length)),0<t[0]&&e.moveStart("character",t[0])),e},l.prototype._nativeSelect=function(t){t.select()},l.prototype._nativeSelection=function(){var t=this._nativeRange(),e=this.length(),n=this._doc.selection.createRange();try{return[function(t,e){var n=e.text.replace(/\r/g,"").length;if(t.compareEndPoints("StartToStart",e)<=0)return 0;if(0<=t.compareEndPoints("StartToEnd",e))return n;for(var i=0;0<t.compareEndPoints("StartToStart",e);++i,t.moveStart("character",-1));return i}(n,t),function(t,e){var n=e.text.replace(/\r/g,"").length;if(0<=t.compareEndPoints("EndToEnd",e))return n;if(t.compareEndPoints("EndToStart",e)<=0)return 0;for(var i=0;0<t.compareEndPoints("EndToStart",e);++i,t.moveEnd("character",-1));return i}(n,t)]}catch(t){return n.parentElement().sourceIndex<this._el.sourceIndex?[0,0]:[e,e]}},l.prototype._nativeGetText=function(t){return t.text},l.prototype._nativeSetText=function(t,e){e.text=t},l.prototype._nativeEOL=function(){"value"in this._el?this.text("\n"):this._nativeRange(this.bounds()).pasteHTML("\n<br/>")},l.prototype._nativeTop=function(t){var e=this._nativeRange([0,0]);return t.boundingTop-e.boundingTop},l.prototype._nativeWrap=function(t,e){var n=document.createElement("div");n.appendChild(t);var i=n.innerHTML.replace("><",">"+e.htmlText+"<");e.pasteHTML(i)},(u.prototype=new e)._nativeRange=function(t){return t||[0,this.length()]},u.prototype._nativeSelect=function(t){this._el.setSelectionRange(t[0],t[1])},u.prototype._nativeSelection=function(){return[this._el.selectionStart,this._el.selectionEnd]},u.prototype._nativeGetText=function(t){return this._el.value.substring(t[0],t[1])},u.prototype._nativeSetText=function(t,e){var n=this._el.value;this._el.value=n.substring(0,e[0])+t+n.substring(e[1])},u.prototype._nativeEOL=function(){this.text("\n")},u.prototype._nativeTop=function(t){var e=this._el.cloneNode(!0);e.style.visibility="hidden",e.style.position="absolute",this._el.parentNode.insertBefore(e,this._el),e.style.height="1px",e.value=this._el.value.slice(0,t[0]);var n=e.scrollHeight;return e.value="X",n-=e.scrollHeight,e.parentNode.removeChild(e),n},u.prototype._nativeWrap=function(){throw new Error("Cannot wrap in a text element")},(c.prototype=new e)._nativeRange=function(t){var e=this._doc.createRange();return e.selectNodeContents(this._el),t&&(i(e,t[0],!0,this._el),e.collapse(!0),i(e,t[1]-t[0],!1,this._el)),e},c.prototype._nativeSelect=function(t){this._win.getSelection().removeAllRanges(),this._win.getSelection().addRange(t)},c.prototype._nativeSelection=function(){var t=this._nativeRange();if(0==this._win.getSelection().rangeCount)return[this.length(),this.length()];var e,n,i,o,r=this._win.getSelection().getRangeAt(0);return[(i=r,o=t,i.compareBoundaryPoints(a,o)<=0?0:0<=i.compareBoundaryPoints(f,o)?o.toString().length:((i=i.cloneRange()).setEnd(o.endContainer,o.endOffset),o.toString().replace(/\r/g,"").length-i.toString().replace(/\r/g,"").length)),(e=r,n=t,0<=e.compareBoundaryPoints(p,n)?n.toString().length:e.compareBoundaryPoints(d,n)<=0?0:((e=e.cloneRange()).setStart(n.startContainer,n.startOffset),e.toString().replace(/\r/g,"").length))]},c.prototype._nativeGetText=function(t){return String.prototype.slice.apply(this._el.textContent,this.bounds())},c.prototype._nativeSetText=function(t,e){e.deleteContents(),e.insertNode(this._doc.createTextNode(t)),n&&this._el.normalize()},c.prototype._nativeEOL=function(){var t=this._nativeRange(this.bounds());t.deleteContents();var e=this._doc.createElement("br");e.setAttribute("_moz_dirty",""),t.insertNode(e),t.insertNode(this._doc.createTextNode("\n")),t.collapse(!1)},c.prototype._nativeTop=function(t){if(0==this.length)return 0;if(""==t.toString()){var e=this._doc.createTextNode("X");t.insertNode(e)}var n=this._nativeRange([0,1]),i=t.getBoundingClientRect().top-n.getBoundingClientRect().top;return e&&e.parentNode.removeChild(e),i},c.prototype._nativeWrap=function(t,e){e.surroundContents(t)};var a=0,d=1,p=2,f=3;function v(){}(v.prototype=new e)._nativeRange=function(t){return t||[0,this.length()]},v.prototype._nativeSelect=function(t){},v.prototype._nativeSelection=function(){return[0,0]},v.prototype._nativeGetText=function(t){return this._el[this._textProp].substring(t[0],t[1])},v.prototype._nativeSetText=function(t,e){var n=this._el[this._textProp];this._el[this._textProp]=n.substring(0,e[0])+t+n.substring(e[1])},v.prototype._nativeEOL=function(){this.text("\n")},v.prototype._nativeTop=function(){return 0},v.prototype._nativeWrap=function(){throw new Error("Wrapping not implemented")};var o=[];bililiteRange.fn.data=function(){var t=this.element().bililiteRangeData;return null==t&&(t=this.element().bililiteRangeData=o.length,o[t]=new r(this)),o[t]};try{Object.defineProperty({},"foo",{});var r=function(t){Object.defineProperty(this,"values",{value:{}}),Object.defineProperty(this,"sourceRange",{value:t}),Object.defineProperty(this,"toJSON",{value:function(){var t={};for(var e in r.prototype)e in this.values&&(t[e]=this.values[e]);return t}}),Object.defineProperty(this,"all",{get:function(){var t={};for(var e in r.prototype)t[e]=this[e];return t}})};r.prototype={},Object.defineProperty(r.prototype,"values",{value:{}}),Object.defineProperty(r.prototype,"monitored",{value:{}}),bililiteRange.data=function(e,t){t=t||{};var n=Object.getOwnPropertyDescriptor(r.prototype,e)||{};"enumerable"in t&&(n.enumerable=!!t.enumerable),"enumerable"in n||(n.enumerable=!0),"value"in t&&(r.prototype.values[e]=t.value),"monitored"in t&&(r.prototype.monitored[e]=t.monitored),n.configurable=!0,n.get=function(){return e in this.values?this.values[e]:r.prototype.values[e]},n.set=function(t){this.values[e]=t,r.prototype.monitored[e]&&this.sourceRange.dispatch({type:"bililiteRangeData",bubbles:!0,detail:{name:e,value:t}})},Object.defineProperty(r.prototype,e,n)}}catch(t){(r=function(t){this.sourceRange=t}).prototype={},bililiteRange.data=function(t,e){"value"in e&&(r.prototype[t]=e.value)}}}(),Array.prototype.forEach||(Array.prototype.forEach=function(t){"use strict";if(null==this)throw new TypeError;var e=Object(this),n=e.length>>>0;if("function"!=typeof t)throw new TypeError;for(var i=2<=arguments.length?arguments[1]:void 0,o=0;o<n;o++)o in e&&t.call(i,e[o],o,e)});

	/* language detection */
	window.ju_language = navigator.language || navigator.userLanguage || navigator.browserLanguage || navigator.systemLanguage || "en-US";

  function ju_debounce(fn, delay, allowcooldown) {
    allowcooldown = allowcooldown.toLowerCase()
    var cooldown = null
    var multiple = null

    return function () {
      var self = this
      var args = arguments

      if (cooldown) {
        multiple = true
        clearTimeout(cooldown)
      } else if (allowcooldown == 'both' || allowcooldown == 'start') {
        fn.apply(self, args)
      }

      cooldown = setTimeout(function () {
        if (allowcooldown == 'end' || (multiple && allowcooldown == 'both')) {
          fn.apply(self, args)
        }

        cooldown = null
        multiple = null
      }, delay)
    }
  }

  window.juApplyCouponDebounced = ju_debounce(function () {
    // try to auto apply coupon
    ju_autoapplycoupon();
  }, 2000, 'End');

	window.ju_alreadyloaded = true;

  if(typeof(ju_v) != 'string'){
    window.ju_widget_v = "4.1";
  } else {
    window.ju_widget_v = ju_v;
	}
	//window.ju_showcoupon = "0";
	window.ju_target_starttime = null; // will be used later when we don't want to grab the config from server on every page load
	window.ju_target_interval = null; // stores the setInterval event for targeting
	window.jju=""; // stores the jquery library instead of $
	window.ju_data_page = {}; // session/cookie handler for per page
	window.ju_data_session = {}; // session/cookie handler for per visitor session
	window.ju_data_all = {}; // session/cookie handler for per visitor cookie lifetime
	window.juDp = ju_data_page;
	window.juDs = ju_data_session;
  window.juDa = ju_data_all;
  var juTempConfig = window.ju_config || {};
  window.ju_config = {loadGoogleFonts:true,acow:false,alertMsg:'',totalIdleTime:0,totalPctScrolled:0,totalClicked:0,ju_status:"0",prodId:'',pageType:'',custId:'',trackFunc:[],initFunc:[],root:jju_getDomain(),topZ:0}; // stores global config data retrieved from ajax request
  if (window.juPlatform && window.juPlatform=='wordpress'){
    ju_config.swPath = '/wp-content/plugins/wp-justuno/service-worker.js';
  } else if (window.BCData){
    ju_config.swPath = '/content/justuno/service-worker.js';
  } else {
    ju_config.swPath = '/apps/justuno/service-worker.js';
  }
  for (var arr in juTempConfig) { window.ju_config[arr] = juTempConfig[arr]; }
	window.ju_current_domain = "";
	window.ju_current_url = "";
  window.ju_current_url_protocol = "";
	window.ju_camefrom_domain = "";
	window.ju_camefrom_url = "";
  window.ju_camefrom_url_protocol = "";
	window.ju_triggerred = false;
	window.ju_show_button = false;
	window.ju_show_coupon = false;
	//window.ju_show_coupon_id = -1;
	window.ju_show_campaign_id = -1;
	window.ju_show_tab_campaign_id = -1;
	window.ju_haveseen = false;
	window.ju_custom_button_width = 0;
	window.ju_conversion = "";
	window.ju_il_activated_exit = false; // for intent to leave
  window.ju_il_activated_back = false; // for intent to leave
	window.ju_targetruncount = 0;
	window.ju_mobile = false;
	window.ju_initialized_button = false;
	window.ju_new_visit = 0;
  window.ju_new_user = 0;
  window.ju_new_user_ever = 0;
	window.ju_active_ju_num = ju_num;
	window.ju_svgmode = false;
	window.juHeight = null;
	window.juWidth = null;
	window.juBorder = null;
	window.juStartingPosition = null;
	window.juFinalPosition = null;
	window.ju_scroll_check = null;
	window.ju_ajaxDebounce = null;
	window.ju_cv_timer_check = null;
	window.ju_stoptop = false;
	window.ju_successfocused = 0;
	window.ju_lastopenedcoupon = -10;
	window.ju_timer = null;
	window.ju_timer2 = null;
	window.ju_matched_cm = null;
	window.ju_Tracker = {};
	window.ju_promo_title = "";
	//window.ju_popup_active = false;
	window.ju_iframe_url = "";
	window.ju_initialized = false;
	window.ju_resize_tracker = null;
	window.show_preview_tab = 'yes';
	window.fixed_supported = true;
	window.fixed_push_interval = null;
	window.pushdown_distance = 0;
	window.fixed_push_type = null;
  window.ju_idleStateTime = 0;
  window.ju_stopupdating = false;
	window.ie9 = !-[1,];
	window.ju_cm = 0;
	window.touchPresent = ju_hasTouch();
	window.ju_googlefonttimer = null;
	window.ju_promo_options = {};
	window.ju_exitback = false;
	window.ju_setupexitintent = false;
	window.ju_setupbackintent = false;
  window.ju_setupclickintent = [];
  window.ju_setuphoverintent = [];
  window.ju_setupclickintent_el = '';
  window.ju_setuphoverintent_el = '';
  window.ju_allow_again = false;
	window.ju_cnt = '';
	window.ju_reg = '';
	window.ju_cty = '';
	window.ju_zip = '';
	window._ju_dt = '';
	window.ju_config_timeout = null;
	window.ju_ct_timer_check = null;
  window.ju_lg_timer_check = null;
  window.ju_lg_array = [0,0,0,0];
	if(typeof(asset_host) != 'string') window.asset_host = 'https://cdn.us8.co/';
  if(window.asset_host.substring(0, 2)=='//') window.asset_host = 'https:'+window.asset_host;
  if (window.asset_host.substring(window.asset_host.length-1) != "/") window.asset_host = window.asset_host+'/';
  window.ju_host = window.asset_host.split('.')[1]+'.'+window.asset_host.split('.')[2].replace('/','');
  window.ju_profileUrl = "aly."+window.ju_host;
  window.ju_domain = 'https://my.'+window.ju_host;
  window.ju_pushDomain = 'https://push.'+window.ju_host; //'https://bhs-push-stage-alpha.justuno.com'
	window.ju_pst = {};
	window.ju_useBeacon = false;
	window.ju_visible = true;
  window.ju_jqLoaded_once = false;
  window.ju_fetchconfig_once = false;
  window.ju_lastKeyDown = 0;
  window.ju_orderid = window.ju_orderid || '';
  window.ju_referrer_url = '';
  window.ju_referrer_url_protocol = '';
  window.ju_plastsaved = (new Date()).getTime();
	window.ju_cookieonly = window.ju_cookieonly || false;
	window.ju_eu_countries = ['BE', 'EL', 'LT', 'PT', 'BG', 'ES', 'LU', 'RO', 'CZ', 'FR', 'HU', 'SI', 'DK', 'HR', 'MT', 'SK', 'DE', 'IT', 'NL', 'FI', 'EE', 'CY', 'AT', 'SE', 'IE', 'LV', 'PL', 'UK','GB','CH'];
	window.ju_gaTracker = window.ju_gaTracker || '';
  window.ju_cartDirty = false;
  window.ju_v = window.ju_v || 0;
  window.ju_vr = window.ju_vr || 0;
  window.ju_pns = ju_pushSupport();
	window.ju_todayDate = function(){
		return Math.floor((new Date())/8.64e7);
	}
  if(typeof(ju_pageid) != 'string'){
    window.ju_pageid = "";
    ju_genPageId();
  }

  window.ju_tmpCartObj = {};


	ju_current_domain = fetchWindowHref().match(/:\/\/(.[^/]+)/)[1];
	ju_current_url = fetchWindowHref();
	if (!ju_current_url) ju_current_url = '';
	ju_current_url = (ju_current_url.substring(ju_current_url.length-1) == "/") ? ju_current_url.substring(0, ju_current_url.length-1) : ju_current_url;
	if (ju_current_url.indexOf('http://')>-1){
    ju_current_url = ju_current_url.replace('http://','');
    ju_current_url_protocol = "http://";
  } else {
    ju_current_url = ju_current_url.replace('https://','');
    ju_current_url_protocol = "https://";
  }

  window.urlvalidmatch = {"0":ju_current_url};

  window.ju_qstr = ju_parseQuery(window.location.search);

	if (document.referrer!=''){
		ju_camefrom_domain = document.referrer.match(/:\/\/(.[^/]+)/)[1];
		if (ju_camefrom_domain!=ju_current_domain){
			ju_camefrom_url = document.referrer.match(/:\/\/(.+)/)[1];
		}
    if (document.referrer.indexOf('http://')>-1){
      ju_camefrom_url_protocol = "http://";
    } else {
			ju_camefrom_url_protocol = "https://";
		}
	};

	if (!ju_camefrom_domain) ju_camefrom_domain = '';
	if (!ju_camefrom_url) ju_camefrom_url = '';

	if('sendBeacon' in window.navigator) {
	  ju_useBeacon = true;
	}


	/* end of session tracking code */



	if (typeof(ju_options) !== 'object'){
		window.ju_options = {};
	}

	if(typeof(ju_customvar) != 'string'){
		window.ju_customvar = ""
	}
	if(typeof(ju_custom1) != 'string' && typeof(ju_custom1) != 'number'){
		window.ju_custom1 = ""
	}
	if(typeof(ju_custom2) != 'string' && typeof(ju_custom2) != 'number'){
		window.ju_custom2 = ""
	}
	if(typeof(ju_custom3) != 'string' && typeof(ju_custom3) != 'number'){
		window.ju_custom3 = ""
	}
	if (typeof(ju_loadcm) != 'number'){
		window.ju_loadcm = 0;
	} else {
		ju_cm = ju_loadcm;
	}

	window.ju_windowHeight = 0;
  window.ju_windowWidth = 0;

	function juDetectPlatform() {
		document = window.document;
		var platforms = [
			["/frontend/", "15"],
			[".wp-", "33"],
			["wp-content", "33"],
			["/sites/default/files/", "11"],
			["bigcommerce", "6"],
			["woocommerce", "40"],
			["magento", "15"],
			["shopify", "25"],
			["demandware", "10"],
		];
		var platform;
		platforms.forEach(function (arr) {
			if (
				(
					document.documentElement.textContent ||
					document.documentElement.innerText
				).indexOf(arr[0]) > -1
			) {
				platform = arr[1];
			}
		});
		return platform || '';
	}

  function ju_parseQuery(str){
    if(typeof str != "string" || str.length == 0) return {};
    str = str.replace('?','');
    var s = str.split("&");
    var s_length = s.length;
    var bit, query = {}, first, second;
    for(var i = 0; i < s_length; i++)
        {
        bit = s[i].split("=");
        first = decodeURIComponent(bit[0]);
        if(first.length == 0) continue;
        second = decodeURIComponent(bit[1]);
        if(typeof query[first] == "undefined") query[first] = second;
        else if(query[first] instanceof Array) query[first].push(second);
        else query[first] = [query[first], second];
        }
    return query;
  }

	window.ju_assumejq = function(){
		var ju_domstate = document.readyState;
		if (ju_domstate == "interactive" || ju_domstate == "complete") {
			if (document.getElementsByTagName("body").length != 0) {
				clearInterval(ju_timer);

				if (!ju_options.forcejquery && ju_options.hasOwnProperty("forcejquery")) {
					if (window.jQuery) {
						jju = jQuery
						ju_jqLoaded(jju);
						//console.log('force loaded existing jquery')
					} else {
						window.ju_timer = setInterval(ju_assumejq, 30);
						//console.log('waiting for force loaded jquery')
					}
				} else if (ju_check() && !ju_options.forcejquery) {
					jju = jQuery
					ju_jqLoaded(jju);
					//console.log('compatible jquery loaded already')
				} else {
					var script = document.createElement('script')
					script.src = window.asset_host+'jquery-3.3.1.min.js';
					if (document.querySelector('script[nonce]') && document.querySelector('script[nonce]')?.nonce!="null" && document.querySelector('script[nonce]')?.nonce!="") script.nonce = document.querySelector('script[nonce]')?.nonce;
					document.getElementsByTagName("body")[0].appendChild(script);
					var ju_timer2 = setInterval(function () {
						if (ju_check()) {
							//console.log($.fn.jquery)
							if (jQuery.fn.jquery == '3.3.1') {
								clearInterval(ju_timer2);
								jju = jQuery.noConflict(true);
								ju_jqLoaded(jju);
							}
						}
					}, 30);
					//console.log('loading our own jquery')
				}
			}
		}
	}

	window.ju_launch = function(){
		window.ju_timer = setInterval(ju_assumejq, 30);
	}

	var _ju_dn = jju_getCookie("_ju_dn");
	if (_ju_dn != '-1' && _ju_dn != undefined && (typeof (ju_autolaunch) != 'boolean' || ju_autolaunch != false || _ju_dn == '1' || ju_loadcm > 0)) {
		ju_Cookie.setCookies("_ju_dn", '1', 30, '/', '.' + ju_config.root);
		ju_launch();
	};

  function ju_fadeinoverlay(cmid){
    var overlay_opacity = 1;
    jju.each(ju_config.ju_campaigns,function(ci, citem) {
        if (cmid==ju_config.ju_campaigns[ci].cmid){
          if (ju_config.ju_campaigns[ci].tab.design.overlay.hasOwnProperty("overlay_opacity")){
            overlay_opacity = ju_config.ju_campaigns[ci].tab.design.overlay.overlay_opacity;
          } else {
            overlay_opacity = 1;
        };
				if (ju_onboarding_display==0){
					overlay_opacity = .5;
					jju('#ju_overlay').css({'background-image':'none'});
				}
        return false;
        };
    });
  	jju('#ju_overlay').fadeTo(50,overlay_opacity);
  	jju('#ju_overlay').data('cmid',cmid);
  }

  function ju_fadeoutoverlay(cmid){
    if (ju_onboarding_display>=0) return false;
  	if (cmid==jju('#ju_overlay').data('cmid')){
  		jju('#ju_overlay').css('filter', 'alpha(opacity=50)');
  		jju('#ju_overlay').fadeOut(100);
  	}
  }

  function ju_fadein(cmid,send_resize){
  	//jju('#ju_iframe_'+cmid).css({'opacity':0});
  	if (!jju('#ju_iframe_'+cmid+'.ju_inpage').length){
      jju('#ju_Con_'+cmid).css({'display':'block'});
      resizejucon(cmid,send_resize,false);
    }
  	if (typeof(ju_windowevent) === 'function') {
  		ju_windowevent('load',cmid);
  	};
  	//resizejucon(cmid,send_resize,false);
  }

  function ju_fadeout(cmid){
    if (ju_onboarding_display>=0) return false;
  	jju('#ju_Con_'+cmid).fadeOut(100,function(){
			jju('#ju_Con_'+cmid).css({'left':'0px','top':'0px','height':'100%','width':'100%'});
			jju('.ju_CSSJS_' + cmid).remove();
  	});
  	// need to look for other uno bars still being shown and readjust
  	if (!jju('.ju_Con[data-position="9"][id!="ju_Con_'+cmid+'"]:visible').length){
      var ju_orig_marg = jju('body').attr('ju_orig_marg');
      if (ju_orig_marg){
        jju('body').animate({
  				marginTop: ju_orig_marg
  			},{duration:300,queue:false});
  		  jju('body').removeAttr('ju_orig_marg');
      }
  		clearInterval(fixed_push_interval);
  		jju('[ju_orig_top]').each(function(){
        orig_top = jju(this).css('top').replace('px','');
        var ju_orig_top = jju(this).attr('ju_orig_top');
        if (isNaN(orig_top) || jju(this).hasClass('ju_alternativepush')){
    			jju(this).animate({
    				marginTop: ju_orig_top
    			},{duration:300,queue:false});
        } else {
          jju(this).animate({
            top: ju_orig_top
          },{duration:300,queue:false});
        }
  			jju(this).removeAttr('ju_orig_top');
  		});
  	}

  	//ju_popup_active = false;
  	if (typeof(ju_windowevent) === 'function') {
  		ju_windowevent('unload',cmid);
  	};
  	//resizejucon();
  }

  function setwidthheight(){
    if(navigator.platform == 'iPad' || navigator.platform == 'iPhone' || navigator.platform == 'iPod'){
      ju_windowHeight = window.innerHeight;
      ju_windowWidth = window.innerWidth;
    } else {
      ju_windowHeight = (document.documentElement.clientHeight<window.innerHeight ? (window.innerHeight-document.documentElement.clientHeight < 30 ? document.documentElement.clientHeight : window.innerHeight) : window.innerHeight);
      ju_windowWidth = (document.documentElement.clientWidth<window.innerWidth ? document.documentElement.clientWidth : window.innerWidth);
    }
    window.ju_ratio = document.body.clientWidth / window.innerWidth;
  }

	function resizejucon(cmid,send_resize,orientation){
    ju_inPageVisCheck();
  	setwidthheight();

  	// if ((ju_mobile && !fixed_supported) || orientation) {
  	// 	jju((cmid>0 ? '#ju_Con_'+cmid : '')+'.ju_Con').css({'left':'0px','height':ju_windowHeight+'px','width':'100%'});
  	// } else {
  	// 	jju((cmid>0 ? '#ju_Con_'+cmid : '')+'.ju_Con').css({'height':ju_windowHeight+'px','width':'100%'});
		// }
		//debugger

		if (send_resize){
			jju((cmid>0 ? '#ju_iframe_'+cmid : '')+'.ju_iframe').each(function(){
				if (!jju(this).hasClass('ju_inpage')){
					jju(this).css({'width':jju(this).closest('.ju_Con').width()});
				}
				var pass_data = {
					'resize_event': true
				};
        var thisConWin = document.getElementById(jju(this).attr('id')).contentWindow;
        if (typeof(thisConWin.jju_receiveMessage)==='function'){
          tryCatch(thisConWin.jju_receiveMessage(pass_data));
        }
			})
		}
	}

	window.ju_postMessage = function(data,src,el){
		var popup = el;
		popup.postMessage(data, src);
	}

  function ju_targeting_data(){

		if (!ju_visible) {
			//console.log('not visible')
			return false;
    }

		juDs.spentsite++;
		juDa.spentsite++;
		juDp.spentsite++;
		ju_targetruncount++;
    ju_idleStateTime++;
    if (ju_idleStateTime>1) ju_config.totalIdleTime++;

		if (ju_idleStateTime > 1800 || (new Date().getTime() - ju_plastsaved > 1800000)){
			ju_stopupdating = true;
		}

    if (ju_stopupdating) return false;

    ju_inPageVisCheck();

  	if (juDp.spentsite % 10 == 0 && juDs.spentsite<55 && !ju_useBeacon) {
  		//console.log('every 10 seconds')
  	 	write_data_cookies(false,300,false);
    }

    if (Math.round((new Date()).getTime() / 1000)-ju_lastKeyDown<2){
      return false
    }

  	if (ju_config.ju_status=="1"){
  		test_targets();
  	}

  }



  function write_data_cookies(reset,time,usebeacon){
  	// check to make sure another window/tab has reverted these

  	if (ju_loadcm>0) return false;

  	var ju_setcookie = true;

  	if (!reset){
  		var _ju_pn = jju_getCookie("_ju_pn");
  		if (_ju_pn!="" && _ju_pn!=null && !ju_inIframeLoaded()){
  			if (_ju_pn>juDs.pagecount){
          ju_setcookie = false;
  			};
  		}
  	} else {
      jju_setCookie("_ju_pn", juDs.pagecount,.0208, '/', '.'+ju_config.root, '');
    }

  	if (ju_setcookie){

			// let's fix some things here
			if (!Array.isArray(juDa.cartTotals)){
				juDa.cartTotals = [jju.extend(true, {}, ju_tmpCartObj)];
			}

  		clearTimeout(ju_ct_timer_check);
  		ju_ct_timer_check = setTimeout(function(){
			localStorage.setItem("juDa", JSON.stringify(juDa));
			localStorage.setItem("juDs", JSON.stringify(juDs));
			localStorage.setItem("juSession", ju_config.ju_sessionkey);
			localStorage.setItem("juNum", ju_active_ju_num);
			ju_config.ju_sessionkey
  			ju_savetodb(usebeacon);
  		},time);
  	};
  }

  function evaltype(v1,v2,et){
  	if (typeof v1 == 'string' || v1 instanceof String || typeof v1 == 'boolean' || v1 instanceof Boolean) {
  		v1 = jju.trim(String(v1)).toLowerCase();
  	}
  	if (typeof v2 == 'string' || v2 instanceof String || typeof v2 == 'boolean' || v2 instanceof Boolean) {
  		v2 = jju.trim(String(v2)).toLowerCase();
  	}
  	switch (parseFloat(et)){
  		case 1:
      case 5:
      case 9:
      case 11:
      case 12:
  			return v1==v2;
  			break;
  		case 2:
      case 6:
      case 10:
      case 13:
  			return v1!=v2;
  			break;
  		case 3:
      case 16:
  			return (v1 || '').indexOf(v2) > -1;
  			break;
  		case 4:
      case 17:
  			return (v1 || '').indexOf(v2) < 0;
  			break;
  		case 7:
  			return v1>v2;
  			break;
  		case 8:
  			return v1<v2;
  			break;
  		case 14:
  			return ((isNaN(v1)) ? v1 : parseInt(v1))>((isNaN(v2)) ? v2 : parseInt(v2));
  			break;
  		case 15:
  			return ((isNaN(v1)) ? v1 : parseInt(v1))<((isNaN(v2)) ? v2 : parseInt(v2));
  			break;
  		case 18:
  			return v1>0;
  			break;
  		case 19:
  			return v1==0;
  			break;
  		case 20:
  			return (v1 || '').substring(0, v2.length) == v2;
  			break;
  		case 21:
  			return (v1 || '').substring(0, v2.length) != v2;
  			break;
  		case 22:
  			// regex
        try{
          var regex = new RegExp(v2, "gi");
          return regex.test(v1)
        } catch(er){
          return false
        }
  			break;
  		case 23:
  			// wildcard
        try{
          v2 = v2.replace(/\*/g, "[^]*");
          var regex = new RegExp(v2, "gi");
          return regex.test(v1)
        } catch(er){
          return false
        }
  			break;
      case 24:
        // exists
        return v1 != null && v1 != '';
        break;
      case 25:
        // exists
        return v1 == null || v1 == '';
        break;
  	}
	}

	function ju_pageChange(reset){
		clearTimeout(ju_ajaxDebounce);
		clearInterval(ju_target_interval);
		ju_ajaxDebounce = setTimeout(function(){
			// need call a new page load
			ju_genPageId();
			ju_fetchconfig_once = false;
			if (!jju('#ju_bbox').length) ju_initialized_button = false; // we reset this incase they have cleared their dom.
			ju_fetchconfig(reset);

			setTimeout(function () {
				ju_target_interval = setInterval(ju_targeting_data, 1000);
				ju_targeting_data();
				resizejucon(0, true, false);
				// try to auto set email
				if (juDs.config.email_sel) ju_autosetemail();

				// try to auto apply coupon
				ju_autoapplycoupon();
			}, 2000);
			return false;
		},2000)
	}

  function test_targets(){

    if (ju_stopupdating) return false;

  	//if (ju_popup_active) return false;

  	// need to get this info again incase of hash changes or other url changes on the same page

  	ju_current_url = fetchWindowHref();
  	if (!ju_current_url) ju_current_url = '';
  	ju_current_url = (ju_current_url.substring(ju_current_url.length-1) == "/") ? ju_current_url.substring(0, ju_current_url.length-1) : ju_current_url;
  	if (ju_current_url.indexOf('https://')>-1){
      ju_current_url = ju_current_url.replace('https://','');
      ju_current_url_protocol = "https://";
    } else {
      ju_current_url = ju_current_url.replace('http://','');
      ju_current_url_protocol = "http://";
    }

    if (urlvalidmatch["0"].split('#')[0]!=ju_current_url.split('#')[0]){
			ju_pageChange(false);
    }

  	try {
  		ju_referrer_url = document.referrer;
  	} catch(err){};
  	if (!ju_referrer_url) ju_referrer_url = '';
  	ju_referrer_url = (ju_referrer_url.substring(ju_referrer_url.length-1) == "/") ? ju_referrer_url.substring(0, ju_referrer_url.length-1) : ju_referrer_url;
    if (ju_referrer_url.indexOf('https://')>-1){
      ju_referrer_url = ju_referrer_url.replace('https://','');
      ju_referrer_url_protocol = "https://";
    } else {
      ju_referrer_url = ju_referrer_url.replace('http://','');
      ju_referrer_url_protocol = "http://";
    }

  	if (ju_loadcm>0){
  		clearInterval(ju_target_interval);
  		var cm_ID = ju_loadcm;

  		juDs.spentsite=5;
  		juDa.spentsite=5;
  		juDp.spentsite=5;

      run_target_action(3,0,cm_ID,0,cm_ID,99999998,'',{ruleId:0,exit:0})
  		return false
  	}

  	var ju_il_activated_temp = false;

  	jju.each(ju_config.ju_targeting, function(entryIndex, entry) {

  		ju_triggerred = false;
  		var sTrig = false;

  		var tg_ID = this.rule.id;
  		var cm_ID = this.rule.cmid;
  		var ex_ID = this.rule.exid;
  		var ex_cm_IDs = this.rule.excmids;
  		var tg_main_con = this.rule.data.rule.triggers["condition-group"].logic_type; // 1 = any, 2 = all
  		var tg_action = parseInt(this.rule.data.rule.actions); // 1 = popopen, 2 = show tab, 3 = both, 4 = in page, 5 = tag
      var tg_element = (tg_action=='4' ? this.rule.data.rule.action_inpage_element : '');
      var tg_location = this.rule.data.rule.action_inpage_location || 5;
  		var tg_tags = this.rule.data.rule.action_audience_tags;
      var tg_frequency = this.rule.data.rule.frequency; // 1 = visit, 2 = page
      var tg_push = this.rule.push;
  		var seen_this_days = -1;
  		var seen_any_days = -1;
  		var engaged_this_days = -1;
  		var engaged_any_days = -1;
  		var matched_this_rule_days = -1;
  		var seen_this_sessions = -1;
  		var seen_any_sessions = -1;
  		var engaged_this_sessions = -1;
  		var engaged_any_sessions = -1;
  		var matched_this_rule_sessions = -1;
  		var this_coupon = 0;
  		var this_seen_this_visit = 0;
  		var this_engaged_this_visit = 0;
  		var this_ever_closed = 0;
  		var this_closed_this_visit = 0;
  		var this_ever_seen = 0;
  		var this_ever_engaged = 0;
  		var this_seen_x_times = 0;
      var this_engaged_x_times = 0;
      var this_engaged_types = [];
      var this_seen_x_times_ever = 0;
      var this_engaged_x_times_ever = 0;
      var this_engaged_types_ever = [];
      var zindex = 999998 - entryIndex;

      if (tg_push==1 && (ju_pns=='none' || (ju_current_url_protocol=="https://" && window.Notification && window.Notification.permission=='denied') || juDa.notif.perm=='denied')) return true;

  		jju.each(juDa.offers_seen, function(entryIndex, entry) {
  			var thisgrepid = this.ID;
  			seen_any_days = (ju_todayDate()-parseInt(this.dt) < seen_any_days || seen_any_days == -1) ? ju_todayDate()-parseInt(this.dt) : seen_any_days;
  			seen_any_sessions = (juDa.visits - parseInt(this.se) < seen_any_sessions || seen_any_sessions == -1) ? juDa.visits - parseInt(this.se) : seen_any_sessions;
  			if (existArrayObj(ex_cm_IDs,'cmid',thisgrepid) || ex_ID+'_0' == thisgrepid){
  				seen_this_days = ju_todayDate()-parseInt(this.dt);
  				seen_this_sessions = juDa.visits - parseInt(this.se);
					this_ever_seen = 1;
					this_seen_x_times_ever = (this.hasOwnProperty("ct")) ? this.ct : 0;
  			}
			})

			jju.each(juDs.offers_seen, function(entryIndex, entry) {
				var thisgrepid = this.ID;
				if (existArrayObj(ex_cm_IDs,'cmid',thisgrepid) || ex_ID+'_0' == thisgrepid){
          this_seen_this_visit = 1;
          this_seen_x_times = (this.hasOwnProperty("ct")) ? this.ct : 0;
        }
      })

  		jju.each(juDa.offers_engaged, function(entryIndex, entry) {
        var thisgrepid = this.ID;
				engaged_any_days = (ju_todayDate()-parseInt(this.dt) < engaged_any_days || engaged_any_days == -1) ? ju_todayDate()-parseInt(this.dt) : engaged_any_days;
				engaged_any_sessions = (juDa.visits - parseInt(this.se) < engaged_any_sessions || engaged_any_sessions == -1) ? juDa.visits - parseInt(this.se) : engaged_any_sessions;
				if (existArrayObj(ex_cm_IDs,'cmid',thisgrepid)){
  				engaged_this_days = ju_todayDate()-parseInt(this.dt);
  				engaged_this_sessions = juDa.visits - parseInt(this.se);
					this_ever_engaged = 1;
          this_engaged_x_times_ever = (this.hasOwnProperty("ct")) ? this.ct : 0;
          this_engaged_types_ever = this.ty;
        }
        if (this.ty && Array.isArray(this.ty)){
          jju.each(this.ty, function(entryIndex2, v) {
            if (v=='4') juDa.offers_engaged[entryIndex].ty[entryIndex2]='10';
          })
        }
			})

			jju.each(juDs.offers_engaged, function(entryIndex, entry) {
        var thisgrepid = this.ID;
				if (existArrayObj(ex_cm_IDs,'cmid',thisgrepid)){
					this_engaged_this_visit = 1;
          this_engaged_x_times = (this.hasOwnProperty("ct")) ? this.ct : 0;
          this_engaged_types = this.ty;
        }
        if (this.ty && Array.isArray(this.ty)){
          jju.each(this.ty, function(entryIndex2, v) {
            if (v=='4') juDs.offers_engaged[entryIndex].ty[entryIndex2]='10';
          })
        }
      })

  		jju.each(juDa.closed, function(entryIndex, entry) {
				var thisgrepid = this.ID;
				if (existArrayObj(ex_cm_IDs,'cmid',thisgrepid)){
  				this_ever_closed = 1;
  			}
  		})

  		jju.each(juDs.closed, function(entryIndex, entry) {
				var thisgrepid = this.ID;
				if (existArrayObj(ex_cm_IDs,'cmid',thisgrepid)){
  				this_closed_this_visit = 1;
  			}
  		})

  		jju.each(juDa.rules_matched, function(entryIndex, entry) {
  			if (this.ID==tg_ID){
  				matched_this_rule_days = ju_todayDate()-parseInt(this.dt);
  				matched_this_rule_sessions = juDa.visits - parseInt(this.se);
  			}
  		})

      var is_exitintent = 0;

  		if (!ju_il_activated_exit && !ju_il_activated_back && ju_targetruncount<=1){
  			var assign_history_value = false;
  			jju.each(this.rule.data.rule.triggers["condition-group"].conditions, function(entryIndex, entry) {
  				jju.each(this["condition-group"].conditions, function(entryIndex, entry) {
  					if (this.condition.type=="31"){
  						ju_setupexitintent = true;
						if (!window.ju_stopPreload){
							is_exitintent = 1;
						}
  					}
  					if (this.condition.type=="60"){
  						ju_setupbackintent = true;
  						if (!window.ju_stopPreload){
							is_exitintent = 1;
						}
  					}
            if (this.condition.type=="73" && jju.inArray(this.condition.val1,ju_setupclickintent)==-1){
              ju_setupclickintent.push(this.condition.val1);
              //is_exitintent = 1; not sure we want to preload for this condition
            }
            if (this.condition.type=="74" && jju.inArray(this.condition.val1,ju_setuphoverintent)==-1){
              ju_setuphoverintent.push(this.condition.val1);
              //is_exitintent = 1; not sure we want to preload for this condition
            }
  					if (!history.state){
  						assign_history_value = true;
  					} else if (typeof history.state.page === "undefined"){
  						assign_history_value = true;
  					};
            //console.log(ju_exitback,this.condition.type,juDs.pagecount,history.state,assign_history_value,typeof(history.replaceState))
  					if (!ju_exitback && this.condition.type=="60" && juDs.pagecount==1 && assign_history_value  &&  typeof(history.replaceState) == "function"){
  							ju_exitback = true;
  							juDs.exitback = history.length-1;
  							write_data_cookies(false,300,false);
  							history.replaceState({ page: history.length-1, href: fetchWindowHref() }, "foo");
  			        history.pushState({ page: history.length, href: fetchWindowHref() }, "foo");
  					};
  				});
  			});
      }

  		for (var i_t = 0; i_t < 1+is_exitintent; i_t++) {

  			jju.each(this.rule.data.rule.triggers["condition-group"].conditions, function(entryIndex, entry) {

  				var tg_sub_con = this["condition-group"].logic_type; // 1 = any, 2 = all

  				if (this["condition-group"].conditions.length==0){
  					sTrig = (tg_sub_con=="1") ? true : (entryIndex==0) ? true : sTrig;
  				}

  				jju.each(this["condition-group"].conditions, function(entryIndex, entry) {

  					var thisevaltype = this.condition.evaltype;
  					var thisval1 = this.condition.val1;
  					var thisval2 = this.condition.val2;
  					var thisval3 = this.condition.val3;

  					if (typeof thisval1 == 'string' || thisval1 instanceof String){
  						thisval1 = (thisval1.substring(thisval1.length-1) == "/") ? thisval1.substring(0, thisval1.length-1) : thisval1;
  						thisval1 = thisval1.replace('https://','');
  						thisval1 = thisval1.replace('http://','');
  					}

            var tTrig = function(thetest){
              if (thetest){
                return (tg_sub_con=="1") ? true : (entryIndex==0) ? true : sTrig;
              } else {
                return (tg_sub_con!="1") ? false : (entryIndex==0) ? false : sTrig;
              }
            }

  					switch (this.condition.type){
  						case "1":
                sTrig = tTrig(evaltype(ju_referrer_url,thisval1,thisevaltype) && thisval1!='');
  							break;
  						case "2":
                sTrig = tTrig(evaltype(juDa.camefrom,thisval1,thisevaltype) && thisval1!='');
  							break;
  						case "3":
                sTrig = tTrig(evaltype(ju_current_url,thisval1,thisevaltype) && thisval1!='');
  							break;
  						case "47":
                sTrig = tTrig(evaltype(juDs.firsturl,thisval1,thisevaltype) && thisval1!='');
  							break;
  						case "48":
                sTrig = tTrig(evaltype(juDa.firsturl,thisval1,thisevaltype) && thisval1!='');
  							break;
  						case "11":
                sTrig = tTrig(evaltype(juDa.visits,thisval1,thisevaltype));
  							break;
  						case "12":
                sTrig = tTrig(evaltype(juDs.pagecount,thisval1,thisevaltype));
  							break;
  						case "13":
                sTrig = tTrig(evaltype(juDa.pagecount,thisval1,thisevaltype));
  							break;
  						case "14":
  							sTrig = is_exitintent==0 ? tTrig(evaltype(juDp.spentsite,thisval1,thisevaltype)) : tTrig(true);
  							break;
  						case "15":
                sTrig = is_exitintent==0 ? tTrig(evaltype(parseFloat(juDs.spentsite),parseFloat(thisval1)*60,thisevaltype)) : tTrig(true);
  							break;
  						case "16":
                sTrig = is_exitintent==0 ? tTrig(evaltype(parseFloat(juDa.spentsite),parseFloat(thisval1)*60,thisevaltype)) : tTrig(true);
  							break;
  						case "21":
                sTrig = is_exitintent==0 ? tTrig(evaltype(juDs.seen,1,thisevaltype)) : tTrig(true);
  							break;
  						case "22":
                sTrig = is_exitintent==0 ? tTrig(evaltype(juDa.seen,1,thisevaltype)) : tTrig(true);
  							break;
              case "23":
                sTrig = is_exitintent==0 ? tTrig((thisval1 && thisval1!='' && thisval1!='engaged' ? evaltype(existArrayObj(juDs.offers_engaged,'ty',thisval1),true,thisevaltype) : evaltype(juDs.engaged,1,thisevaltype))) : tTrig(true);
  							break;
              case "24":
                sTrig = is_exitintent==0 ? tTrig((thisval1 && thisval1!='' && thisval1!='engaged' ? evaltype(existArrayObj(juDa.offers_engaged,'ty',thisval1),true,thisevaltype) : evaltype(juDa.engaged,1,thisevaltype))) : tTrig(true);
                break;
  						case "25":
                sTrig = is_exitintent==0 ? tTrig(evaltype(this_seen_this_visit,1,thisevaltype)) : tTrig(true);
  							break;
  						case "26":
                sTrig = is_exitintent==0 ? tTrig(evaltype(this_ever_seen,1,thisevaltype)) : tTrig(true);
  							break;
              case "27":
                sTrig = is_exitintent==0 ? tTrig((thisval1 && thisval1!='' && thisval1!='engaged' ? evaltype(jju.inArray(thisval1, this_engaged_types) > -1,true,thisevaltype) : evaltype(this_engaged_this_visit,1,thisevaltype))) : tTrig(true);
  							break;
              case "28":
                sTrig = is_exitintent==0 ? tTrig((thisval1 && thisval1!='' && thisval1!='engaged' ? evaltype(jju.inArray(thisval1,this_engaged_types_ever) > -1,true,thisevaltype) : evaltype(this_ever_engaged,1,thisevaltype))) : tTrig(true);
                break;
  						case "29":
                sTrig = is_exitintent==0 ? tTrig(evaltype(this_ever_closed,1,thisevaltype)) : tTrig(true);
  							break;
  						case "30":
                sTrig = is_exitintent==0 ? tTrig(evaltype(this_closed_this_visit,1,thisevaltype)) : tTrig(true);
  							break;
              case "31":
  							if (is_exitintent==0){
                  if (evaltype(ju_il_activated_exit,true,thisevaltype)){
                    var allVisiblePositions = jju('.ju_Con:visible').map(function(){
                      return jju(this).data('position');
                    }).get();
                    if (jju.inArray(4,allVisiblePositions)==-1){
                      sTrig = tTrig(true);
                      ju_il_activated_temp = true;
                      jju("#ju_Con_"+cm_ID).css({'z-index':99999999});
                    } else {
                      sTrig = tTrig(false);
                    }
  								} else {
  									sTrig = tTrig(false);
  								}
  							} else {
  								sTrig = tTrig(true);
  							}
  							break;
  						case "32":
                sTrig = tTrig(evaltype(ju_custom1,thisval1,thisevaltype));
  							break;
  						case "33":
                sTrig = tTrig(evaltype(ju_custom2,thisval1,thisevaltype));
  							break;
  						case "34":
                sTrig = tTrig(evaltype(ju_custom3,thisval1,thisevaltype));
  							break;
  						case "35":
  							if (ju_options.hasOwnProperty("targeting")) {
  								if (ju_options.targeting.hasOwnProperty(thisval2)) {
  									if (evaltype(ju_options.targeting[thisval2],thisval1,thisevaltype)){
  										sTrig = tTrig(true);
  									} else {
  										sTrig = tTrig(false);
  									}
  								} else {
  									sTrig = tTrig(false);
  								}
  							} else {
  								sTrig = tTrig(false);
  							}
  							break;
  						case "36":
  							var ju_localdatetime = new Date();
  							var ju_localdate = (ju_localdatetime.getMonth()+1) + '/' + (ju_localdatetime.getDate()) + '/' + ju_localdatetime.getFullYear();
  							sTrig = tTrig(evaltype(Date.parse(ju_localdate),Date.parse(thisval1),thisevaltype));
  							break;
  						case "37":
  							var ju_localdatetime = new Date();
  							var ju_localdate = (ju_localdatetime.getMonth()+1) + '/' + (ju_localdatetime.getDate()) + '/' + ju_localdatetime.getFullYear();
                sTrig = tTrig(evaltype(ju_localdatetime,Date.parse(ju_localdate+' '+thisval1),thisevaltype));
  							break;
							case "38":
								if (thisval1=='EU'){
									sTrig = tTrig(evaltype(ju_config.ju_EU, true, thisevaltype));
								} else {
									sTrig = tTrig(evaltype(ju_config.ju_country, thisval1, thisevaltype));
								}
  							break;
  						case "45":
                sTrig = tTrig(evaltype(ju_config.ju_region,thisval1,thisevaltype));
  							break;
  						case "39":
                sTrig = tTrig(evaltype(ju_config.ju_zip,thisval1,thisevaltype));
  							break;
  						case "40":
                sTrig = tTrig(evaltype(ju_config.ju_ip,thisval1,thisevaltype));
  							break;
							case "41":
								try {
									sTrig = tTrig(evaltype(jju(thisval1).length,true,thisevaltype));
								} catch(er){
									sTrig = tTrig(false);
								}
  							break;
  						case "42":
                sTrig = tTrig(evaltype(seen_this_days,parseFloat(thisval1),thisevaltype) || seen_this_days==-1);
  							break;
  						case "43":
                sTrig = tTrig(evaltype(matched_this_rule_days,parseFloat(thisval1),thisevaltype) || matched_this_rule_days==-1);
  							break;
  						case "44":
                sTrig = tTrig(evaltype(engaged_this_days,parseFloat(thisval1),thisevaltype) || engaged_this_days==-1);
  							break;
  						case "46":
                sTrig = tTrig(evaltype(jju(window).scrollTop(),parseFloat(thisval1),thisevaltype));
  							break;
  						case "49":
                if (ju_options.hasOwnProperty("targeting") && ju_options.targeting.hasOwnProperty("optimizelyid")) {
									sTrig = tTrig(evaltype(ju_options.targeting.optimizelyid,cm_ID,thisevaltype));
								} else {
									sTrig = tTrig(false);
								}
  							break;
  						case "50":
                sTrig = is_exitintent==0 ? tTrig(evaltype(existArrayObj(juDa.offers_seen,'ID',thisval1),true,thisevaltype)) : tTrig(true);
  							break;
  						case "51":
                sTrig = is_exitintent==0 ? tTrig(evaltype(existArrayObj(juDs.offers_seen,'ID',thisval1),true,thisevaltype)) : tTrig(true);
                break;
  						case "52":
                var testresult = false;
                for (var i = 0, len = juDa.offers_engaged.length; i < len; i++) {
                  if (juDa.offers_engaged[i]['ID'] == thisval1) {
                    if ((!thisval3 || thisval3=='' || thisval3=='engaged') || (Array.isArray(juDa.offers_engaged[i]['ty']) && jju.inArray(thisval3, juDa.offers_engaged[i]['ty']) > -1)) {
                      testresult = true;
                      break;
                    }
                  }
                }
                sTrig = tTrig(evaltype(testresult,true,thisevaltype));
  							break;
  						case "53":
                var testresult = false;
                for (var i = 0, len = juDs.offers_engaged.length; i < len; i++) {
                  if (juDs.offers_engaged[i]['ID'] == thisval1) {
                    if ((!thisval3 || thisval3=='' || thisval3=='engaged') || (Array.isArray(juDs.offers_engaged[i]['ty']) && jju.inArray(thisval3, juDs.offers_engaged[i]['ty']) > -1)) {
                      testresult = true;
                      break;
                    }
                  }
                }
                sTrig = tTrig(evaltype(testresult,true,thisevaltype));
                break;
  						case "54":
  							var ju_localdatetime = new Date();
                sTrig = tTrig(evaltype(ju_localdatetime.getDay(),thisval1,thisevaltype));
  							break;
  						case "55":
                sTrig = is_exitintent==0 ? tTrig(evaltype(ju_idleStateTime,thisval1,thisevaltype)) : tTrig(true);
  							break;
  						case "56":
                sTrig = tTrig(evaltype(seen_any_days,parseFloat(thisval1),thisevaltype) || seen_any_days==-1);
  							break;
  						case "57":
                sTrig = tTrig(evaltype(engaged_any_days,parseFloat(thisval1),thisevaltype) || engaged_any_days==-1);
  							break;
  						case "58":
                sTrig = tTrig(evaltype(this_seen_x_times,parseFloat(thisval1),thisevaltype));
  							break;
  						case "59":
                sTrig = tTrig(evaltype(this_engaged_x_times,parseFloat(thisval1),thisevaltype));
  							break;
  						case "60":
                // mobile exit back
  							if (is_exitintent==0){
  								if (evaltype(ju_il_activated_back,true,thisevaltype)){
  									sTrig = tTrig(true);
  									ju_il_activated_temp = true;
  									jju("#ju_Con_"+cm_ID).css({'z-index':99999999});
  								} else {
  									sTrig = tTrig(false);
  								}
  							} else {
  								sTrig = tTrig(true);
  							}
  							break;
  						case "61":
  							// days since last seen specific offer - ever
  							var seen_a_offer_days = -1;
  							jju.each(juDa.offers_seen, function(entryIndex, entry) {
  								if (this.ID==thisval1){
  									seen_a_offer_days = ju_todayDate()-parseInt(this.dt);
  									return false;
  								}
  							})
                sTrig = tTrig(evaltype(seen_a_offer_days,parseFloat(thisval3),thisevaltype) || seen_a_offer_days==-1);
  							break;
  						case "62":
  							// days since last egaged specific offer - ever
  							var engaged_a_offer_days = -1;
  							jju.each(juDa.offers_engaged, function(entryIndex, entry) {
  								if (this.ID==thisval1){
  									engaged_a_offer_days = ju_todayDate()-parseInt(this.dt);
  									return false;
  								}
  							})
                sTrig = tTrig(evaltype(engaged_a_offer_days,parseFloat(thisval3),thisevaltype) || engaged_a_offer_days==-1);
  							break;
  						case "63":
  							// sessions since last saw any
                sTrig = tTrig(evaltype(seen_any_sessions,parseFloat(thisval1),thisevaltype) || seen_any_sessions==-1);
  							break;
  						case "64":
  							// session since last engaged any
                sTrig = tTrig(evaltype(engaged_any_sessions,parseFloat(thisval1),thisevaltype) || engaged_any_sessions==-1);
  							break;
  						case "65":
  							// sessions since last saw this
                sTrig = tTrig(evaltype(seen_this_sessions,parseFloat(thisval1),thisevaltype) || seen_this_sessions==-1);
  							break;
  						case "66":
  							// session since last engaged this
                sTrig = tTrig(evaltype(engaged_this_sessions,parseFloat(thisval1),thisevaltype) || engaged_this_sessions==-1);
  							break;
  						case "67":
  							// session since last seen specific offer - ever
  							var seen_a_offer_sessions = -1;
  							jju.each(juDa.offers_seen, function(entryIndex, entry) {
  								if (this.ID==thisval1){
  									seen_a_offer_sessions = juDa.visits - parseInt(this.se);
  									return false;
  								}
  							})
                sTrig = tTrig(evaltype(seen_a_offer_sessions,parseFloat(thisval3),thisevaltype) || seen_a_offer_sessions==-1);
  							break;
  						case "68":
  							// session since last egaged specific offer - ever
  							var engaged_a_offer_sessions = -1;
  							jju.each(juDa.offers_engaged, function(entryIndex, entry) {
  								if (this.ID==thisval1){
  									engaged_a_offer_sessions = juDa.visits - parseInt(this.se);
  									return false;
  								}
  							})
                sTrig = tTrig(evaltype(engaged_a_offer_sessions,parseFloat(thisval3),thisevaltype) || engaged_a_offer_sessions==-1);
  							break;
  						case "69":
                sTrig = tTrig(evaltype(matched_this_rule_sessions,parseFloat(thisval1),thisevaltype) || matched_this_rule_sessions==-1);
  							break;
  						case "70":
                sTrig = tTrig(evaltype(ju_language,thisval1,thisevaltype));
  							break;
  						case "71":
                sTrig = is_exitintent==0 ? tTrig(evaltype(jju(window).scrollTop(),(jju(document).height()-jju(window).height())*(parseFloat(thisval1)/100),thisevaltype)) : tTrig(true);
  							break;
              case "73":
                if (is_exitintent==0){
                  if (evaltype(jju.trim(ju_setupclickintent_el),thisval1,thisevaltype)){
                    //ju_setupclickintent_el = '';
                    splice_rules_matched(tg_frequency,cm_ID,tg_ID);
                    sTrig = tTrig(true);
                    ju_il_activated_temp = true;
                    ju_allow_again = true;
                    jju("#ju_Con_"+cm_ID).css({'z-index':99999999});
                  } else {
                    sTrig = tTrig(false);

                    //is_exitintent = 1;
                  }
                } else {
                  sTrig = tTrig(true);
                }
                break;
              case "74":
                if (is_exitintent==0){
                  if (evaltype(jju.trim(ju_setuphoverintent_el),thisval1,thisevaltype)){
                    //ju_setuphoverintent_el = '';
                    splice_rules_matched(tg_frequency,cm_ID,tg_ID);
                    sTrig = tTrig(true);
                    ju_il_activated_temp = true;
                    ju_allow_again = true;
                    jju("#ju_Con_"+cm_ID).css({'z-index':99999999});
                  } else {
                    sTrig = tTrig(false);

                    //is_exitintent = 1;
                  }
                } else {
                  sTrig = tTrig(true);
                }
                break;
              case "75":
                if (juDs.hasOwnProperty("arb") && juDs.arb.hasOwnProperty(thisval2) && evaltype(juDs.arb[thisval2].v,thisval1,thisevaltype)){
									sTrig = tTrig(true);
								} else {
									if (jju.inArray(thisevaltype, ['13', '17', '25']) > -1 && (!juDs.hasOwnProperty("arb") || !juDs.arb.hasOwnProperty(thisval2))){
										sTrig = tTrig(true);
									} else {
										sTrig = is_exitintent == 0 ? tTrig(false) : tTrig(true);
									}
                }
                break;
              case "76":
								if (juDa.hasOwnProperty("arb") && juDa.arb.hasOwnProperty(thisval2) && evaltype(juDa.arb[thisval2].v, thisval1, thisevaltype)) {
									sTrig = tTrig(true);
								} else {
									if (jju.inArray(thisevaltype, ['13', '17', '25']) > -1 && (!juDa.hasOwnProperty("arb") || !juDa.arb.hasOwnProperty(thisval2))) {
										sTrig = tTrig(true);
									} else {
										sTrig = is_exitintent == 0 ? tTrig(false) : tTrig(true);
									}
								}
								break;
              case "77":  // cart attributes
                var testresult=null;
                if (juDs.hasOwnProperty("cartItem")) {
                  var key_array = thisval2.split('|');
                  var val_array = thisval1.split('|');
                  var eval_array = thisevaltype.split('|');
                  for (var key in juDs.cartItem) {
                    // skip loop if the property is from prototype
                    if (!juDs.cartItem.hasOwnProperty(key)) continue;
                    for (var i = 0; i < key_array.length; i++) {
                      if ((i==0 || testresult) && evaltype((key_array[i]=='key' ? key : juDs.cartItem[key].v[key_array[i]]),val_array[i],eval_array[i])){
                        testresult = (jju.inArray(eval_array[i],['13','17'])>-1 ? (testresult==null?true:testresult) : true);
                      } else {
                        testresult = (jju.inArray(eval_array[i],['13','17'])>-1 ? false : (testresult==null?false:testresult));
                      }
                    }
                    //if (testresult) break;
                  }
                }
                sTrig = is_exitintent==0 ? tTrig((testresult==null?false:testresult)) : tTrig(true);
                break;
              case "78":  // cart attributes in past
                var testresult=null;
                if (juDa.hasOwnProperty("cartItem")) {
                  var key_array = thisval2.split('|');
                  var val_array = thisval1.split('|');
                  var eval_array = thisevaltype.split('|');
                  for (var key in juDa.cartItem) {
                    // skip loop if the property is from prototype
                    if (!juDa.cartItem.hasOwnProperty(key) || ((new Date()) - (new Date(juDa.cartItem[key].d))) < 1800000) continue;
                    for (var i = 0; i < key_array.length; i++) {
                      if ((i==0 || testresult) && evaltype((key_array[i]=='key' ? key : juDa.cartItem[key].v[key_array[i]]),val_array[i],eval_array[i])){
                        testresult = (jju.inArray(eval_array[i],['13','17'])>-1 ? (testresult==null?true:testresult) : true);
                      } else {
                        testresult = (jju.inArray(eval_array[i],['13','17'])>-1 ? false : (testresult==null?false:testresult));
                      }
                    }
                    //if (testresult) break;
                  }
                }
                sTrig = is_exitintent==0 ? tTrig((testresult==null?false:testresult)) : tTrig(true);
                break;
              case "79":  // cart totals
                var testresult = false;
                if (juDs.cartTotals) {
                  if (thisval2=='tq'){
                    if (evaltype(juDs.cartTotals.tq,thisval1,thisevaltype)){
                      testresult = true;
                    }
                  }
                  if (thisval2=='tp'){
                    if (evaltype(juDs.cartTotals.tp,thisval1,thisevaltype)){
                      testresult = true;
                    }
                  }
                }
                sTrig = is_exitintent==0 ? tTrig(testresult) : tTrig(true);
                break;
              case "80":  // cart totals in past
                var testresult = false;
                if (juDa.cartTotals) {
                  try{
                    if (juDa.cartTotals[juDa.cartTotals.length-1].hasOwnProperty(ju_config.ju_sessionkey)){
                      var propertyMinus = 2;
                    } else {
                      var propertyMinus = 1;
                    }
                    var cartobj = juDa.cartTotals[juDa.cartTotals.length-propertyMinus][Object.keys(juDa.cartTotals[juDa.cartTotals.length-propertyMinus])[0]];
										//console.log(cartobj)
                    var cartTp = cartobj.tp;
                    var cartTq = cartobj.tq;
                  }
                  catch(er){
										//console.log(er)
                    var cartTp = 0;
                    var cartTq = 0;
                  }

                  if (thisval2=='tq'){
                    if (evaltype(cartTq,thisval1,thisevaltype)){
                      testresult = true;
                    }
                  }
                  if (thisval2=='tp'){
                    if (evaltype(cartTp,thisval1,thisevaltype)){
                      testresult = true;
                    }
                  }
                }

                sTrig = is_exitintent==0 ? tTrig(testresult) : tTrig(true);
                break;
              case "81":  // has ordered before
                var objlength = 0;
                for (var key in juDa.order) {
                  if (juDa.order.hasOwnProperty(key)) objlength++;
                }
                sTrig = is_exitintent==0 ? tTrig(evaltype(objlength>0,true,thisevaltype)) : tTrig(true);
                break;
              case "82":  // order item attributes
                var testresult = false;
                if (juDa.hasOwnProperty("order")) {
                  var key_array = thisval2.split('|');
                  var val_array = thisval1.split('|');
                  var eval_array = thisevaltype.split('|');
                  for (var key in juDa.order) {
                    // skip loop if the property is from prototype
                    if (!juDa.order.hasOwnProperty(key)) continue;
                    for (var oi in juDa.order[key].i) {
                      // skip loop if the property is from prototype
                      if (!juDa.order[key].i.hasOwnProperty(oi)) continue;
                      for (var k = 0; k < key_array.length; k++) {
                        if ((k==0 || testresult) && evaltype((key_array[k]=='key' ? k : juDa.order[key].i[oi][key_array[k]]),val_array[k],eval_array[k])){
                          testresult = true;
                        } else {
                          testresult = false;
                        }
                        if (testresult) break;
                      }
                      if (testresult) break;
                    }
                    if (testresult) break;
                  }
                }
                sTrig = is_exitintent==0 ? tTrig(testresult) : tTrig(true);
                break;
              case "83":  // order totals
                var testresult = false;
                var totalorders = 0;
                var totalprice = 0;
                var lastorderday = 9999;
                if (juDa.hasOwnProperty("order")) {
                  for (var key in juDa.order) {
                    // skip loop if the property is from prototype
                    if (!juDa.order.hasOwnProperty(key)) continue;
                    totalorders++;
                    totalprice += juDa.order[key].v.t;
                    var thisdate = ju_todayDate()-parseInt(juDa.order[key].d/8.64e7);
                    lastorderday = (thisdate<lastorderday ? thisdate : lastorderday);
                  }
                }
                if (thisval2=='tq'){
                  if (evaltype(totalorders,thisval1,thisevaltype)){
                    testresult = true;
                  }
                }
                if (thisval2=='tp'){
                  if (evaltype(totalprice,thisval1,thisevaltype)){
                    testresult = true;
                  }
                }
                if (thisval2=='ld'){
                  if (evaltype(lastorderday,thisval1,thisevaltype)){
                    testresult = true;
                  }
                }
                sTrig = is_exitintent==0 ? tTrig(testresult) : tTrig(true);
                break;
              case "84":
                sTrig = is_exitintent==0 ? tTrig(evaltype(jju_getCookie(thisval2),thisval1,thisevaltype)) : tTrig(true);
                break;
              case "85":
                sTrig = is_exitintent==0 ? tTrig(evaltype(juDs.closed.length>0,true,thisevaltype)) : tTrig(true);
                break;
              case "86":
                sTrig = is_exitintent==0 ? tTrig(evaltype(juDa.closed.length>0,true,thisevaltype)) : tTrig(true);
                break;
              case "87":
                sTrig = tTrig(evaltype(this_seen_x_times_ever,parseFloat(thisval1),thisevaltype));
                break;
              case "88":
                sTrig = tTrig(evaltype(this_engaged_x_times_ever,parseFloat(thisval1),thisevaltype));
                break;
              case "89":
				if (thisval1=='Safari') thisval1 = '^(?=.*Safari)(?!.*Chrome).*';
				if (ju_mobile){
                  sTrig = tTrig(evaltype((new RegExp(thisval1, "i")).test(navigator.userAgent),true,thisevaltype));
                } else if (thisval1.indexOf('iPad')!=-1 || thisval1.indexOf('Android')!=-1) {
                  sTrig = tTrig(evaltype((new RegExp(thisval1, "i")).test(navigator.userAgent) && ((typeof(window.orientation)!=='undefined' && ju_windowWidth<=1024) || (typeof(window.orientation)!=='undefined' && ju_windowWidth<=1366 && window.orientation>0)),true,thisevaltype));
                } else {
                  sTrig = tTrig(evaltype((new RegExp(thisval1, "i")).test(navigator.userAgent),true,thisevaltype));
                }
                break;
              case "90":
                try{
                  sTrig = tTrig(evaltype(eval(thisval2),thisval1,thisevaltype));
                } catch(er){
                  sTrig = tTrig(false);
                }
                break;
  					};

  				});

  				if (sTrig){
  					ju_triggerred = (tg_main_con=="1") ? true : (entryIndex==0) ? true : ju_triggerred;
  				} else {
  					ju_triggerred = (tg_main_con!="1") ? false : (entryIndex==0) ? false : ju_triggerred;
  				}

  			});


  		}

  		if (i_t==0 && ju_triggerred){
  			//console.log('triggered')
  			is_exitintent = 0;
  		}

      if (ju_triggerred) {
        urlvalidmatch["0"] = ju_current_url;
        urlvalidmatch[cm_ID.toString()] = ju_current_url;
      }

      // check to see if it's visible and close it if the url check failed (this is used for ajax navigation where a promo is already shown and then they navigate to a page where it shouldn't be shown)
      if (!ju_triggerred && urlvalidmatch[cm_ID.toString()]!=ju_current_url){
        var inpage_parent = jju('#ju_iframe_'+cm_ID+'.ju_inpage:visible').closest('.ju_inpage_con');
        splice_rules_matched(tg_frequency,cm_ID,tg_ID);
        if (tg_action==2){
          if (jju('#ju_bbox[data-promoid="' + cm_ID + '"]').is(':visible')){
            jju('#ju_bbox').remove();
          }
        } else {
          if (inpage_parent.length){
            inpage_parent.slideUp('fast',function(){
              inpage_parent.remove();
              jju('.ju_CSSJS_' + cm_ID).remove();
            });
          } else if (jju('#ju_Con_'+cm_ID+':visible').length){
            ju_fadeout(cm_ID);
            ju_fadeoutoverlay(cm_ID);
          } else {
            jju('.ju_CSSJS_' + cm_ID).remove();
          }
        }
      }

      // lets skip this rule if the promo is already being shown or tab
      if (jju.inArray(tg_action,[1,3,4])>-1 && (jju('#ju_iframe_'+cm_ID).is(":visible") || jju('#ju_Con_'+cm_ID).is(":visible"))) return true;
      if (jju.inArray(tg_action,[2])>-1 && jju('#ju_bbox').is(':visible')) return true;

  		//ju_haveseen
  		if (ju_triggerred) {

  			//ju_il_activated = false;

  			var allow_combine = (ju_haveseen ? false : true);

  			var dont_allow = false;

  			if (ju_il_activated_temp || allow_combine){ //if ((ju_il_activated_temp && !jju('.ju_Con[data-position="4"]:visible').length) || allow_combine){
  				allow_combine = true;
  			} else {
  				jju.each(ju_config.ju_campaigns,function(ci, citem) {
  				    if (cm_ID==ju_config.ju_campaigns[ci].cmid){
  				    	if (ju_config.ju_campaigns[ci].tab.design.overlay.hasOwnProperty("combine")){
  				    		allow_combine = (ju_config.ju_campaigns[ci].tab.design.overlay.combine=='1' ? true : false);
  				    		//console.log(ju_config.ju_campaigns[ci].tab.design.overlay.combine)
  				    	} else {
  				    		allow_combine = false;
  						};
  						return false;
  				    };
  				});
  			}

  			ju_il_activated_temp = false;

  			//if (allow_combine){console.log(cm_ID + ' allow combine')}

  			if (!allow_combine){

  				jju('.ju_Con').each(function(entryIndex, entry) {
  					//console.log('test id = '+this.ID+' = '+jju('#ju_Con_'+this.ID).data('ju_combine'))
  					if ((jju(this).data('ju_combine')!='1' || jju(this).data('ju_exit')=='1') && jju(this).is(":visible")) {
  								dont_allow = true;
  					}
  				})
  			}

  			//if (dont_allow){console.log(cm_ID + ' dont allow')}

        // 2 is a tab, 4 is a inpage promo, 5 is tag

        // need to allow inpage promos to show again in same page if something deleted the dom element and the user never closed it.
				if (tg_action==4 && this_closed_this_visit==0 && (!jju("#ju_iframe_"+cm_ID).length && (!jju(".ju_iframe.ju_inpage[data-ex=\""+ex_ID+"\"]").length || ex_ID==0))) window.ju_allow_again = true;

  			if (!dont_allow || tg_action==2 || tg_action==4){

					update_rules_matched(juDp,"3",tg_ID,cm_ID,ex_ID,ex_cm_IDs,zindex,tg_element,tg_location,ju_allow_again,is_exitintent,tg_frequency,tg_action);
					update_rules_matched(juDs,"2",tg_ID,cm_ID,ex_ID,ex_cm_IDs,zindex,tg_element,tg_location,ju_allow_again,is_exitintent,tg_frequency,tg_action);
					update_rules_matched(juDa,"1",tg_ID,cm_ID,ex_ID,ex_cm_IDs,zindex,tg_element,tg_location,ju_allow_again,is_exitintent,tg_frequency,tg_action);
  			}

			}

      urlvalidmatch["0"] = ju_current_url;
      urlvalidmatch[cm_ID.toString()] = ju_current_url;

      ju_allow_again = false;

  	});

    ju_setupclickintent_el = '';
    ju_setuphoverintent_el = '';

  	ju_il_activated_back = false;
    ju_il_activated_exit = false;

  }

  function splice_rules_matched(tg_frequency,cm_ID,tg_ID){
    if (tg_frequency=="3" && (jju('#ju_iframe_'+cm_ID).is(":visible") || jju('#ju_Con_'+cm_ID).is(":visible"))){
      for( i=juDp.rules_matched.length-1; i>=0; i--) {
        if( juDp.rules_matched[i].ID == tg_ID) juDp.rules_matched.splice(i,1);
        break;
      }
    }
  }

	function update_rules_matched(obj,freq,tg_ID,cm_ID,ex_ID,ex_cm_IDs,zindex,tg_element,tg_location,ju_allow_again,is_exitintent,tg_frequency,tg_action){
		var tg_ID_exists = false;
		jju.each(obj.rules_matched, function(entryIndex, entry) {
			if (this.ID==tg_ID) {
				tg_ID_exists = true;
				this.dt = ju_todayDate();
				this.ct = (this.hasOwnProperty("ct")) ? this.ct + (tg_frequency==freq ? 1 : 0) : 1;
				this.se = obj.visits;
			}
		})

		if ((!tg_ID_exists || ju_allow_again) && is_exitintent==0) {
			if (!tg_ID_exists){
				obj.rules_matched[obj.rules_matched.length] = {
					"ID": tg_ID,
					"dt": ju_todayDate(),
					"ct": 1,
					"se": obj.visits
				};
			}
			if (tg_frequency==freq){
        //console.log(cm_ID + 'run target')
        run_target_action(tg_action,tg_ID,cm_ID,ex_ID,ex_cm_IDs,zindex,tg_element,tg_location,{ruleId:tg_ID,exit:is_exitintent});
			}
		} else if (!tg_ID_exists && tg_frequency==freq){ // this is for preloading offer
			if (!jju("#ju_Con_"+cm_ID).length){
				run_target_action(0,tg_ID,cm_ID,ex_ID,ex_cm_IDs,zindex,tg_element,tg_location,{ruleId:tg_ID,exit:is_exitintent});
			}
		}
	}

  function run_target_action(action,tg_ID,cm_ID,ex_ID,ex_cm_IDs,zindex,tg_element,tg_location,options){

  	// check if user hasn't already been assigned a cmID for this exID then add it to the cookie if not

  	var new_visit = 1;

  	if (ju_loadcm>0 && ju_show_campaign_id>0){
  		return false;
  	}

  	if (ju_loadcm>0){

  		new_visit = 0;
  		ju_show_campaign_id = cm_ID;
  		ju_matched_cm = ju_show_campaign_id;

  	} else if (ex_ID==0) {
  		if (action==0 || action==1 || action==3 || action==4){
  			ju_show_campaign_id = cm_ID;
  		}
  		ju_matched_cm = cm_ID;

  	} else {

  		jju.each(juDs.extocm, function(entryIndex, entry) {
  			if (typeof this.ex !== 'undefined') {
  				if (this.ex==ex_ID) {
  					new_visit = 0;
  					if (action==0 || action==1 || action==3 || action==4){
  						ju_show_campaign_id = this.cm;
  					}
  					ju_matched_cm = this.cm;
  				}
  				//console.log("this.ex = " + this.ex);
  				//console.log("ex_ID = " + ex_ID);
  			}
  		})
  		if (new_visit == 1) {


        // Lets blow up this array to 100 length based on allocation % for each variation
		//console.log(ex_cm_IDs)
        var ex_cm_IDs_expanded = ex_cm_IDs.reduce(function(memo, thecmid) {
					var splitarray = []
					for (var i = 0; i < thecmid.we; i++) {
						splitarray.push({"cmid":thecmid.cmid});
					}
					return memo.concat(splitarray);
				}, [])
				//console.log(ex_cm_IDs_expanded)		
        // now we can just randomly pick a variation from that array
				var ju_random_ex_cm_ID = ex_cm_IDs_expanded[Math.floor(Math.random()*ex_cm_IDs_expanded.length)].cmid;

  			//console.log("random ex_cm_ID = " + ju_random_ex_cm_ID);
  			if (action==0 || action==1 || action==3 || action==4){
  				ju_show_campaign_id = ju_random_ex_cm_ID;
  			}
  			ju_matched_cm = ju_random_ex_cm_ID;
			
  			juDs.extocm[juDs.extocm.length] = {
  				"ex": ex_ID,
  				"cm": ju_random_ex_cm_ID
  			};

				//console.log("ju_matched_cm = " + ju_matched_cm);
  		}

  	}

  	//if (ju_matched_cm!=0 || 1==1){

	if (action==2 || action==3){
		ju_show_button = true;

		if (!ju_initialized_button){
			if (ju_matched_cm!=0){
				//console.log(ju_matched_cm,ju_show_campaign_id)
				jju.each(ju_config.ju_campaigns,function(ci, citem) {
					if (ju_matched_cm==ju_config.ju_campaigns[ci].cmid){
						if (ju_config.ju_campaigns[ci].tab.design.overlay.hasOwnProperty("tab")){
							show_preview_tab = (ju_config.ju_campaigns[ci].tab.design.overlay.tab!='no' ? 'yes' : 'no');
						}
						if (show_preview_tab=='no' && ju_loadcm>0){
							ju_show_button = false;
						}
						// check targeting rules to see if tab is set to be hidden
						ju_config.ju_location= "ju-tab-location-"+ju_config.ju_campaigns[ci].tab.design.tab.location;
						ju_config.ju_alignment= "ju-tab-alignment-"+ju_config.ju_campaigns[ci].tab.design.tab.alignment;
						ju_config.ju_offset= ju_config.ju_campaigns[ci].tab.design.tab.offset;
						ju_config.ju_tab_url= ju_config.ju_campaigns[ci].tab.design.tab.hasOwnProperty("url") ? ju_config.ju_campaigns[ci].tab.design.tab.url : '';
						ju_config.ju_tab_window= ju_config.ju_campaigns[ci].tab.design.tab.hasOwnProperty("window") ? ju_config.ju_campaigns[ci].tab.design.tab.window : '';
						ju_config.ju_button_text= ju_config.ju_campaigns[ci].tab.design.tab.html;
						ju_config.ju_size= ju_config.ju_campaigns[ci].tab.design.tab.padding;
						ju_config.ju_corners= ju_config.ju_campaigns[ci].tab.design.tab["border-radius"];
						ju_config.ju_shadow= ju_config.ju_campaigns[ci].tab.design.tab["box-shadow"];
						ju_config.ju_bordersize= ju_config.ju_campaigns[ci].tab.design.tab["border-width"];
						ju_config.ju_bordercolor= ju_config.ju_campaigns[ci].tab.design.tab["border-color"];
						ju_config.ju_borderstyle= ju_config.ju_campaigns[ci].tab.design.tab["border-style"];
						ju_config.ju_color= ju_config.ju_campaigns[ci].tab.design.tab["background-color"];
						ju_config.ju_close_color= ju_config.ju_campaigns[ci].tab.design.tab.hasOwnProperty("close-color") ? ju_config.ju_campaigns[ci].tab.design.tab["close-color"] : '#ffffff';
						ju_config.ju_gradientcolor= ju_config.ju_campaigns[ci].tab.design.tab["gradient-color"];
						ju_config.ju_custombutton= parseImageFromTab(ju_config.ju_button_text);
						ju_config.ju_overlay_color= ju_config.ju_campaigns[ci].tab.design.overlay["background-color"];
						ju_config.ju_overlay_image= ju_config.ju_campaigns[ci].tab.design.overlay["background-image"];
						ju_config.ju_cmid= ju_config.ju_campaigns[ci].cmid;
						ju_config.ju_cmid_version= ju_config.ju_campaigns[ci].tab.design.version;
						if (typeof(ju_config.ju_campaigns[ci].tab.design.fonts) === 'object'){
							ju_config.ju_fonts = ju_config.ju_campaigns[ci].tab.design.fonts;
						}
						if (action==3){
							ju_promo_title = ju_config.ju_campaigns[ci].title;
							ju_promo_options = ju_config.ju_campaigns[ci].options;
						}
						//console.log("cm set to "+ju_config.ju_cmid)
						ju_show_tab_campaign_id = ju_config.ju_cmid;

						if (!jju(".ju_CSSJS_" + ju_config.ju_campaigns[ci].cmid).length) {
							ju_add_js(ju_config.ju_campaigns[ci].tjs, ju_config.ju_campaigns[ci].cmid);
							ju_add_css(ju_config.ju_campaigns[ci].tcss, ju_config.ju_campaigns[ci].cmid);
						}

						return false;
					};
				});
			}
			//console.log('test ini')
			if (ju_matched_cm!=0) ju_initialize(true);
			//logtarget(tg_ID,-1,ju_show_tab_campaign_id,ex_ID,new_visit);
		}
	} else if (ju_matched_cm!=0){
		jju.each(ju_config.ju_campaigns,function(ci, citem) {
			if (ju_matched_cm==ju_config.ju_campaigns[ci].cmid){
				ju_promo_title = ju_config.ju_campaigns[ci].title;
				ju_promo_options = ju_config.ju_campaigns[ci].options;
				if (!jju(".ju_CSSJS_" + ju_config.ju_campaigns[ci].cmid).length) {
					ju_add_js(ju_config.ju_campaigns[ci].tjs, ju_config.ju_campaigns[ci].cmid);
					ju_add_css(ju_config.ju_campaigns[ci].tcss, ju_config.ju_campaigns[ci].cmid);
				}
				return false;
			};
		});
    }
    if (tg_element!='' && tg_location!='' && !jju(tg_element).length && action!=2) {
		return false;
	}
		if (action==1 || action==2 || action==3 || action==4){
			if (action!=2) ju_show_coupon = true;
			//setTimeout(function(){
				if (ju_matched_cm!=0){
					for (var attr in options) { ju_promo_options[attr] = options[attr]; }
					ju_record_event('', 'Targeted Overlay', ju_promo_title + (ex_ID>0 ? ' - ab:'+ex_ID : ''), ju_show_campaign_id, {"promo_options":ju_promo_options},1,[]);
				} else {
					ju_record_event('', 'Control Variation', 'Control - ab:'+ex_ID, 0, {"promo_options":{ruleId:tg_ID,exit:options.is_exitintent}},1,[]);
					if (action==2){
						ju_logimpression(0,ex_ID);
					}
				}
			//}, 100);

			// log target run only if the target rule shows the popup
			//logtarget(tg_ID,-1,ju_show_campaign_id,ex_ID,new_visit);
		};

		if (action==0){
			ju_loadiframe({'zindex':zindex,'preload':true,'exid':ex_ID});
		};

  	//};

  	if (action!=0){
  		//console.log('initial impression')
  		write_data_cookies(false,600,false);
  	}

  	if ((ju_show_coupon || ju_il_activated_back || ju_il_activated_exit) && action!=0) {
  		ju_show_coupon = false;
  		if (action==4){
  			ju_loadiframe({'campaign_id':ju_show_campaign_id,'loadwindow':tg_element,'windowLocation':tg_location,'exid':ex_ID});
  		} else {
  			ju_loadiframe({'zindex':zindex,'exid':ex_ID});
  		}
  	}

	}

	function ju_logimpression(promoid,exid){
		if (ju_loadcm>0) return false;
		exid = exid || 0;
		var postvar = {
			accid: ju_active_ju_num,
			promoId: promoid,
			sessionKey: ju_config.ju_sessionkey,
			pageId: ju_pageid,
			abTestId: exid
		}
		ju_beaconsend('https://'+ju_profileUrl+'/api/analytics/impression', postvar);

		//need to change promoid to a string now because control ids are zero and are prepended with test id underscore like 123_123

		promoid = promoid.toString();
		if (promoid=='0') promoid = exid+'_'+promoid

		update_offers_seen(juDs,promoid);
    	update_offers_seen(juDa,promoid);

		write_data_cookies(false, 100, false);
  }

  function update_prods_seen(obj,prodid){
    if (prodid=='') return;
    var ju_prods_seen = false;
    prodid = forceString(prodid, 250)
		jju.each(obj.prods_seen, function (entryIndex, entry) {
			if (typeof this.ID !== 'undefined') {
				if (this.ID == prodid) {
					ju_prods_seen = true;
					this.dt = ju_todayDate();
					this.ct = this.ct + 1 || 1;
          this.se = obj.visits;
          obj.prods_seen = obj.prods_seen.concat(obj.prods_seen.splice(entryIndex, 1));
				}
			}
		})
		if (!ju_prods_seen) {
			obj.prods_seen[obj.prods_seen.length] = {
				"ID": prodid,
				"dt": ju_todayDate(),
				"ct": 1,
				"se": obj.visits
			};
		}
	}

  function update_offers_seen(obj,promoid){
		var ju_offer_seen = false;
		jju.each(obj.offers_seen, function (entryIndex, entry) {
			if (typeof this.ID !== 'undefined') {
				if (this.ID == promoid) {
					ju_offer_seen = true;
					this.dt = ju_todayDate();
					this.tm = (new Date()).getTime();
					this.ps = jju('#ju_Con_' + promoid).data('position');
					this.ct = this.ct + 1 || 1;
					this.se = obj.visits;
				}
			}
		})
		if (!ju_offer_seen) {
			obj.offers_seen[obj.offers_seen.length] = {
				"ID": promoid,
				"dt": ju_todayDate(),
				"tm": (new Date()).getTime(),
				"ps": jju('#ju_Con_' + promoid).data('position'),
				"ct": 1,
				"se": obj.visits
			};
		}
  }

  function addJuIcon(){
    if ((ju_config.ju_acow || ju_current_url.indexOf('juProfile')!=-1 || window.location.hash=='#juProfile') && !window.ju_isPreview && !jju('.ju_controls_btn').length){
		var wf = document.createElement('script');
		wf.src = window.asset_host+'owner-controls.js';
		wf.type = 'text/javascript';
		wf.async = 'true';
	  	if (document.querySelector('script[nonce]') && document.querySelector('script[nonce]')?.nonce!="null" && document.querySelector('script[nonce]')?.nonce!="") wf.nonce = document.querySelector('script[nonce]')?.nonce;
		var s = document.getElementsByTagName('script')[0];
		s.parentNode.insertBefore(wf, s);
    }
  }

  function testju_mobile(){
  	ju_mobile = ju_config.ju_mobile=="2" ? true : false;
  	ju_mobile_scale = (ju_mobile) ? (ju_windowWidth < 450 || ju_windowHeight < 450) : false ;

  	//console.log('is mobile = '+ju_mobile)
  	//console.log('mobile scale = '+ju_mobile_scale)
  }

  function ju_logpagestats(){
    try {
      if (ju_loadcm>0) return false;
      var mouseActivityPct = parseFloat((1-(ju_config.totalIdleTime/juDp.spentsite)).toFixed(2));
      var postvar = {
        accid: ju_active_ju_num,
        scrollPct:parseFloat(ju_config.totalPctScrolled.toFixed(2)),
        mouseActivityPct:(isNaN(mouseActivityPct) || mouseActivityPct<0 || mouseActivityPct===null ? .5 : mouseActivityPct),
        mouseClicks:ju_config.totalClicked,
        productID:ju_config.prodId.toString(),
        pageType:ju_config.pageType.toString(),
        customerID:ju_config.custId.toString(),
        sessionKey: ju_config.ju_sessionkey,
        pageId: ju_pageid
      }
      ju_beaconsend('https://'+ju_profileUrl+'/api/analytics/pagestats', postvar, true);
    } catch(e){
      ju_logerr('pagestats',e);
    }
	}

	function ju_renderStore(obj){
		var i = document.createElement('iframe');
		i.id = 'juStore';
    i.style.display = 'none';
    obj.sha1 = obj.sha1 || '';
    obj.sha256 = obj.sha256 || '';
    obj.md5 = obj.md5 || '';
    i.src = window.asset_host+'store_' + ju_v + '.html?v=' + ju_vr + '#'+ju_active_ju_num+'|'+obj.id+'|'+obj.sha1+'|'+obj.sha256+'|'+obj.md5;
		document.body.appendChild(i);
	}

  function ju_getconfig(){

		if (_ju_dn != '-1' || ju_loadcm>0) {
			ju_Cookie.restoreCookies('_ju_dc', 365, '/', '.' + ju_config.root)
				.then(function (data) {
					//end = new Date().getTime();

					var resultcookie = (typeof (data) === 'object' ? data.value : '');
					resultcookie = (resultcookie === null ? '' : resultcookie);
					resultcookie = (resultcookie === undefined ? '' : resultcookie);
					resultcookie = (resultcookie.indexOf('-') == -1 ? '' : resultcookie);

          _ju_dt = resultcookie.replace(/\\"/g,'').replace(/"/g,'');
          if (_ju_dt.indexOf('-')!=-1){
            ju_renderStore({id:_ju_dt});
          } else {
            ju_renderStore({id:''});
          }
					setTimeout(ju_readyfetch,1000);

				})["catch"](function (er) {
					_ju_dt = '';
					ju_renderStore({id:_ju_dt});
					setTimeout(ju_readyfetch,1000);
				});
		}

  }

  function ju_readyfetch(){
		ju_fetchconfig(false);
  }

  function ju_fetchconfig(reset){
  	//console.log("about to get config file");
		//start = new Date().getTime();

		ju_config.ju_mobile = (ju_MobileEsp.DetectTierIphone() ? "2" : "0");
		testju_mobile();

		if (ju_fetchconfig_once) return false;

		ju_plastsaved = new Date().getTime();

		ju_fetchconfig_once = true;
		ju_targetruncount=0;
    ju_idleStateTime=0;

		ju_pst.m = ju_config.ju_mobile;
		ju_pst.id = ju_active_ju_num;
		ju_pst.p = (ju_loadcm > 0 ? 1 : 0);
		ju_pst.cm = ju_cm;
		ju_pst.pl = juDetectPlatform();

		var _ju_ui = jju_getCookie("_ju_ui");

		if (ju_options.hasOwnProperty("userid") && ju_options.userid!='' && ju_options.userid!='[unique-userid]') _ju_ui = ju_sha256(ju_options.userid);
    var p1 = ju_jsonp_p(ju_domain+'/ajax/account_config_'+ju_widget_v+'.html',ju_pst,'jsonCallback')["catch"](function (err){
      return ju_jsonp_p(ju_domain+'/ajax/account_config_'+ju_widget_v+'.html',ju_pst,'jsonCallback');
    });

		//var p1 = ju_safepost_p(ju_domain+'/ajax/account_config_'+ju_widget_v+'.html', 'POST', 'application/x-www-form-urlencoded', ju_pst, true);

		ju_camefrom_url = ju_camefrom_url.replace('?&','?');
    ju_current_url = ju_current_url.replace('?&','?');

		var ju_fsd = {
			"accid":ju_active_ju_num,
			"genhash":'',
			"device_static_hash":'',
			"userid_hash":(_ju_ui && _ju_ui!='undefined' ? _ju_ui : ''),
			"pageId":ju_pageid,
			"guid":_ju_dt,
			"time":0,
			"segment":parseInt(ju_config.ju_mobile),
			"language":ju_language,
			"camefrom":(ju_camefrom_url!='' ? ju_camefrom_url_protocol + ju_camefrom_url : '').replace(/\\"/g,'').replace(/"/g,'').replace(/\\%22/g,'').replace(/%22/g,''),
			"thisurl":(ju_current_url!='' ? ju_current_url_protocol + ju_current_url : '').replace(/\\"/g,'').replace(/"/g,'').replace(/\\%22/g,'').replace(/%22/g,''),
      "agent":navigator.userAgent,
      "sw":isNaN(window.screen.width) ? 0 : window.screen.width,
      "sh":isNaN(window.screen.height) ? 0 : window.screen.height
    }

    var ju_fsd = Object.keys(ju_fsd).map(function(key) {
        return key + '=' + encodeURIComponent(ju_fsd[key])
    }).join('&');

    var p2 = ju_jsonp_p('https://'+ju_profileUrl+'/api/session/'+(reset?'reset':'findp'),ju_fsd,'jsonFindCallback')["catch"](function (err){
      return ju_jsonp_p('https://'+ju_profileUrl+'/api/session/'+(reset?'reset':'findp'),ju_fsd,'jsonFindCallback');
    });

		Promise.all([p1,p2]).then(function(data){


			//console.log("first",data[0],data[1])
			ju_plastsaved = (new Date()).getTime();
			//data[0] = JSON.parse(data[0]);

      try {
        data[1] = JSON.parse(data[1]);
      } catch(er){
        data[1] = data[1];
      }

			if (data[1].sessionKey && data[1].sessionKey!=''){

				_ju_dt = data[1].id;
				if (_ju_dt!==undefined && _ju_dt!='undefined'){
          ju_renderStore({id:_ju_dt});
					ju_Cookie.setCookies("_ju_dc", _ju_dt,365, '/', '.'+ju_config.root);
				} else {
					_ju_dt = '';
				}
				juDs = ju_data_session = JSON.parse(data[1].current);
        juDa = ju_data_all = JSON.parse(data[1].allTime);
        // fix for profile merging summing up .engaged key
        juDs.engaged = (juDs.engaged>=1 ? 1 : 0);
        juDa.engaged = (juDa.engaged>=1 ? 1 : 0);
        // done with fix
        ju_config.profileExists = true;
        //ju_showcoupon = data[0].res;
        ju_config.ju_status= data[0].res;
        ju_config.alertMsg = data[0].alertMsg;
        ju_config.ju_a = data[0].arbor;
        ju_config.ju_targeting = data[0].tar;
        ju_config.ju_campaigns = data[0].campaigns;
				ju_config.ju_lastupdated = data[1].lastUpdated;
				ju_config.ju_newuser = data[1].newUser;
				ju_config.ju_sessionkey = data[1].sessionKey;
        ju_config.ju_ip = data[1].ip;
        ju_config.ju_plan = data[0].pl;
        ju_config.ju_country= juDs.cnt;
        ju_config.ju_region= juDs.reg;
        ju_config.ju_city= juDs.cty;
        ju_config.ju_zip= juDs.zip;
        ju_config.ju_vid = data[0].vid;
        ju_config.customCSS = data[0].customCSS;
        ju_config.customJS = data[0].customJS;
        ju_config.ju_EU = jju.inArray(ju_config.ju_country, ju_eu_countries) >= 0;
        ju_config.ju_acow = data[0].acow;
        ju_config.domain = data[0].domain;

        window.ju_tmpCartObj[ju_config.ju_sessionkey] = { "d": new Date().getTime(),"tp":0,"tq":0};

        juDs.config = juDs.config || {};
        juDs.arb = juDs.arb || {};
        juDa.arb = juDa.arb || {};
        juDs.cartItem = juDs.cartItem || {};
        juDa.cartItem = juDa.cartItem || {};
        juDs.cartTotals = juDs.cartTotals || {"tp":0,"tq":0};
        juDa.cartTotals = juDa.cartTotals || [jju.extend(true, {}, ju_tmpCartObj)];
        juDs.notif = juDs.notif || {};
        juDa.notif = juDa.notif || {};
        juDs.prods_seen = juDs.prods_seen || [];
        juDa.prods_seen = juDa.prods_seen || [];
        if (ju_current_url_protocol=="https://" && window.Notification) {
          juDs.notif.perm==window.Notification.permission;
          juDa.notif.perm==window.Notification.permission;
        }

        // this is a fix for people who haven't yet updated their shopify app
        if (!Array.isArray(juDa.cartTotals)){
          juDa.cartTotals = [jju.extend(true, {}, ju_tmpCartObj)];
        } else {
          // remove all but the most recent two array cart totals
          juDa.cartTotals.splice(0, juDa.cartTotals.length - 2);

          // check to see if there are totals in the alltime older then 1 week
          for (var k in juDa.cartTotals) {
            if (!juDa.cartTotals.hasOwnProperty(k)) continue;
            var sessionCart = juDa.cartTotals[k][Object.keys(juDa.cartTotals[k])[0]]
            if (isNaN(sessionCart.d) || ju_todayDate() - ((new Date(sessionCart.d)) / 8.64e7) > 6) {
              juDa.cartTotals.splice(k, 1);
              break;
            }
          }
        }

        // the above may truncate the carttotals array, so check if so and add back this session's
        if (juDa.cartTotals.length==0) {
          juDa.cartTotals = [jju.extend(true, {}, ju_tmpCartObj)];
        }

        juDs.order = juDs.order || {};
        juDa.order = juDa.order || {};

        if (typeof(juapp)==='function'){
          window.juappTempArray = juapp.q;
        } else {
          window.juappTempArray = '';
        }

        window.addEventListener("hashchange", addJuIcon, false);

        window.juapp = function(){
          try{
            var suppkey = ''; // this is for backwards compatability with older tracking code
            var key = '';
            var event = arguments[0];
            var newvalue = '';
            var skipaddkey = false;
            if (arguments.length>2){
              suppkey = forceString(arguments[1], 250);
              key = suppkey;
              var value = arguments[2];
            } else {
              var value = arguments[1];
            }

            function getKey(i,v,u){
              // i = productId, v = variantId, u = sku
              i = forceString(i,100)
              v = forceString(v,100)
              u = forceString(u,100)
              if (suppkey==''){
                if (i!='' && v!=''){
                  return i+'.'+v;
                } else if (u!=''){
                  return u;
                } else {
                  return i;
                }
              } else {
                return suppkey;
              }
            }

            if (!Array.isArray(juDa.cartTotals)){
              juDa.cartTotals = [jju.extend(true, {}, ju_tmpCartObj)];
            }

            var curCart = jju.extend(true, {}, juDs.cartItem)

            // juapp('config','[key]','[value]');
            // juapp('arb','[key]','[value]');
            // juapp('cartItemAdd',{productid:'xyz',variationid:'123123',sku:'xyz',quantity:1,price:10,name:'mens tshirt',color:'red',size:'xl'});
            // juapp('cartItemRemove',{productid:'xyz',variationid:'123123',sku:'xyz'});
            // juapp('cartItems',[{ productid: 'xyz', variationid: '123123',sku:'xyz', quantity: 1, price: 10, name: 'mens tshirt', color: 'red', size: 'xl' }]);
            // juapp('cart',{total:10,subtotal:9,tax:1,shipping:2,currency:'USD'});
            // juapp('order',{orderid:'xyz',total:10,subtotal:9,tax:1,shipping:2,currency:'USD'});
            // juapp('orderItem',{productid:'xyz',variationid:'123123',sku:'xyz',quantity:1,price:10,name:'mens tshirt',color:'red',size:'xl'});

            //juapp('config','email_sel','input[name*="email"]');
            //juapp('config','coupon_sel','input[name*="[reduction_code]"]');
            //juapp('config','coupon_btn_sel','.order-summary__section button[type="submit"]');

            //juapp('local','pageType',ShopifyAnalytics.meta.page.pageType);
            //juapp('local','prodId',ShopifyAnalytics.meta.product.id);
            //juapp('local','custId',ShopifyAnalytics.meta.page.customerId);

            //juapp('identify','name@domain.com');

            //juapp('trackFunc','[impression|engagement|conversion]',function(email, eventname, promotitle, cmid, options, form){console.log('custom function')});
            //juapp('initFunc',function(){console.log('custom function')});

            if (jju.inArray(event, ['initFunc', 'trackFunc', 'local', 'identify', 'config', 'arb', 'cartItemAdd', 'cartItemRemove', 'orderItem', 'order', 'cartItems', 'cart']) == -1) return 'event type not allowed';

            if (event=='trackFunc'){
              if (typeof(value)==='function'){
                var funcObj = {};
                funcObj[key] = value;
                ju_config[event].push(funcObj);
              }
              return;
            }

            if (event=='initFunc'){
              if (typeof(value)==='function'){
                ju_config[event].push(value);
                if (ju_initialized) {
                  value();
                };
              }
              return;
            }

            if (jju.inArray(event, ['local', 'config', 'arb', 'identify']) != -1){
              var newvalue = (typeof value==="number" || typeof value==="boolean" ? value : forceString(value,500));
              if (event!='local' && event!='identify'){
                juDs[event] = juDs[event] || {};
                juDa[event] = juDa[event] || {};
                juDs[event] = ju_limitobjectlength(juDs[event],20);
                juDa[event] = ju_limitobjectlength(juDa[event],20);
              } else if (event=='local') {
                ju_config[key] = newvalue;
                if (key=='prodId'){
                  update_prods_seen(juDs,newvalue);
                  update_prods_seen(juDa,newvalue);
                  juDs.prods_seen = juDs.prods_seen.splice((juDs.prods_seen.length-20), 1000)
                  juDa.prods_seen = juDa.prods_seen.splice((juDa.prods_seen.length-20), 1000)
                }
                if (key=='custId'){
                  if (!ju_options.userid || ju_options.userid==''){
                    // disabled this because It's causing a lot of merges, pretty sure it's because of websites (possibly bigcommerce or others) that pass "guest" or equivilent for non logged in users.
                    //ju_Cookie.setCookies("_ju_ui", ju_sha256(newvalue), .0208, '/', '.' + ju_config.root);
                  }
                }
                return;
              } else if (event=='identify') {
                ju_Cookie.setCookies("_ju_ui", ju_sha256(newvalue), .0208, '/', '.' + ju_config.root);
                return;
              }
            }

            if (event=='cartItemAdd'){
              //event = 'cartItem';
              juDs.cartItem = juDs.cartItem || {};
              juDa.cartItem = juDa.cartItem || {};
              juDs.cartItem = ju_limitobjectlength(juDs.cartItem,100);
              juDa.cartItem = ju_limitobjectlength(juDa.cartItem,100);

              // check to see if there are items in the alltime older then 1 week
              for (var k in juDa.cartItem) {
                if (ju_todayDate() - ((new Date(juDa.cartItem[k].d))/8.64e7) > 6){
                  delete juDa.cartItem[k];
                  break;
                }
              }
              key = getKey(forceString(value.productid,100),forceString(value.variationid,100),forceString(value.sku,100));
              if (!value.productid) value.productid = key; // this is for backwards compatability with older tracking code
              var newvalue = {i:forceString(value.productid,100),v:forceString(value.variationid,100),u:forceString(value.sku,100),q:forceNumber(value.quantity,1),p:forceNumber(value.price,0),n:forceString(value.name,100),c:forceString(value.color,25),s:forceString(value.size,25)};
              key = getKey(newvalue.i,newvalue.v,newvalue.u);
            }

            if (event=='cartItemRemove'){
              //event = 'cartItem';
              key = getKey(forceString(value.productid,100),forceString(value.variationid,100),forceString(value.sku,100));
              juDs.cartItem = juDs.cartItem || {};
              juDa.cartItem = juDa.cartItem || {};
              delete juDs.cartItem[key];
              delete juDa.cartItem[key];
              skipaddkey = true;
            }

            if (event == 'cartItems') {
              juDs.cartItem = {};
              juDs.cartTotals = { "tq": 0, "tp": 0 };
              if (value && value.length>=0){
                value.forEach(function (item) {
                  if (item.itemid) item.productid = item.itemid; // this is for backwards compatability with older tracking code
                  key = getKey(item.productid,item.variationid,item.sku);
                  delete juDa.cartItem[key];
                  juapp('cartItemAdd',{ productid: item.productid, variationid: item.variationid, sku: item.sku, quantity: item.quantity, price: item.price, name: item.name, color: item.color, size: item.size });
                });
              } else {
                juDs.cartItem={};
                juDa.cartItem={};
                juDs.cartTotals={"tp":0,"tq":0};
                juDa.cartTotals[juDa.cartTotals.length - 1] = jju.extend(true, {}, ju_tmpCartObj);
              }
              ju_push_pers(0);
              return false;
            }

            if (event=='order'){
              juDs[event] = juDs[event] || {};
              juDa[event] = juDa[event] || {};
              key = getKey('','',value.orderid);
              ju_orderid = key;
              juDs[event] = ju_limitobjectlength(juDs[event],19);
              juDa[event] = ju_limitobjectlength(juDa[event],19);
              var newvalue = { t: forceNumber(value.total,0), s: forceNumber(value.subtotal,0), v: forceNumber(value.tax,0), p: forceNumber(value.shipping,0), c: forceString(value.currency, 3)};
              ju_log_conversion();
            }

            if (event=='orderItem'){
              if (ju_orderid != ''){
                var newvalue = { i: forceString(value.productid, 100), v: forceString(value.variationid, 100), u: forceString(value.sku, 100), q: forceNumber(value.quantity,1), p: forceNumber(value.price,0), n: forceString(value.name, 100), c: forceString(value.color, 25), s: forceString(value.size, 25) };
                var key = getKey(newvalue.i,newvalue.v,newvalue.u);
                if (!juDs.order[ju_orderid].hasOwnProperty("i")) juDs.order[ju_orderid].i = {};
                if (!juDa.order[ju_orderid].hasOwnProperty("i")) juDa.order[ju_orderid].i = {};
                juDs.order[ju_orderid].i[key] = newvalue;
                juDa.order[ju_orderid].i[key] = newvalue;
                ju_log_conversion();
              }
            } else {
              if (event=='cartItemAdd' || event=='cartItemRemove') event = 'cartItem';
              if (!skipaddkey){
                var tempobj = {};
                tempobj[key] = {};
                tempobj[key].v = newvalue;
                tempobj[key].d = new Date().getTime();

                if (event=='cartItem' && juDs.cartItem[key]){
                  juDs[event][key].v.q += tempobj[key].v.q;
                  juDs[event][key].d = new Date().getTime();
                } else if (event!='cart') {
                  juDs[event][key] = jju.extend(true, {}, tempobj[key]);
                }

                if (!juDa.cartTotals[juDa.cartTotals.length-1].hasOwnProperty(ju_config.ju_sessionkey)){
                  juDa.cartItem={};
                }
                if (event=='cartItem' && juDa.cartItem[key]){
                  juDa[event][key].v.q += tempobj[key].v.q;
                  juDa[event][key].d = new Date().getTime();
                } else if (event!='cart' && event!='config'){
                  juDa[event][key] = jju.extend(true, {}, tempobj[key]);
                }
              }

              if (event=='cartItem' || event=='cart'){
                var totaldate = new Date().getTime();
                var totalqty = 0;
                var totalprice = 0;
                var totalsub = 0;
                var totaltax = 0;
                var totalshipping = 0;
                var currency = 'USD';
                if (juDs.hasOwnProperty("cartItem")) {
                  for (var key in juDs.cartItem) {
                    // skip loop if the property is from prototype
                    if (!juDs.cartItem.hasOwnProperty(key)) continue;
                    totalqty += juDs.cartItem[key].v.q;
                    totalprice += juDs.cartItem[key].v.p*juDs.cartItem[key].v.q;
                  }
                }
                totalsub = totalprice;
                if (event=='cart'){
                  totalprice = (value.total ? forceNumber(value.total,0) : totalprice);
                  totalsub = (value.subtotal ? forceNumber(value.subtotal,0) : totalsub);
                  totaltax = (value.tax ? forceNumber(value.tax) : totaltax,0);
                  totalshipping = (value.shipping ? forceNumber(value.shipping,0) : totalshipping);
                  currency = forceString(value.currency, 3);
                }

                juDs.cartTotals = {tp:totalprice,ts:totalsub,tq:totalqty,t:totaltax,s:totalshipping,c:currency};

                if (juDa.cartTotals[juDa.cartTotals.length-1].hasOwnProperty(ju_config.ju_sessionkey)){
                  juDa.cartTotals[juDa.cartTotals.length - 1][ju_config.ju_sessionkey] = { d:totaldate,tp:totalprice,ts:totalsub,tq:totalqty,t:totaltax,s:totalshipping,c:currency};
                } else {
                  juDa.cartTotals.push(jju.extend(true, {}, ju_tmpCartObj));
                  juDa.cartTotals[juDa.cartTotals.length - 1][ju_config.ju_sessionkey] = { d:totaldate,tp:totalprice,ts:totalsub,tq:totalqty,t:totaltax,s:totalshipping,c:currency};
                }
              }
            }
            if (jju.inArray(event, ['initFunc', 'trackFunc', 'local', 'config', 'identify']) == -1) {
              var newCart = jju.extend(true, {}, juDs.cartItem);
              ju_removeProp(curCart,"d");
              ju_removeProp(newCart,"d");
              if (safeToJSON(curCart)!=safeToJSON(newCart)){
								ju_cartDirty = true;
								juApplyCouponDebounced();
              }
              ju_push_pers(0);
              write_data_cookies(false, 30, false);
            }
          } catch (e) {
            e.juDa = juDa;
            ju_logerr('juapp',e);
          }
        }

        if (jju.isArray(juappTempArray)){
          jju.each(juappTempArray,function(i,v){
            if (v.length>2) {
              juapp(v[0],v[1],v[2]);
            } else {
              juapp(v[0],v[1]);
            }
          });
          juappTempArray = ''
        };

        if (ju_qstr && ju_qstr.ju_source=='push-click'){
          ju_beaconsend('https://'+ju_profileUrl+'/api/analytics/pushclickback', {accid:_ju_dt,sessionKey:ju_config.ju_sessionkey,pageId:ju_pageid,subscriberId:ju_qstr.subscriber_id,notificationId:ju_qstr.notification_id,transactionId:ju_qstr.transaction_id,jobId:ju_qstr.job_id});
        }

        for (var k in data[0].cfoptions) {
          switch (k) {
            case "autoemail":
              if (data[0].cfoptions[k].app_on=="1") juapp('config','email_sel',data[0].cfoptions[k].email_sel);
              break;
            case "autocoupon":
              if (data[0].cfoptions[k].app_on=="1") juapp('config','coupon_sel',data[0].cfoptions[k].coupon_sel);
              if (data[0].cfoptions[k].app_on=="1") juapp('config','coupon_btn_sel',data[0].cfoptions[k].coupon_btn_sel);
              break
          }
        }

        // reset some things if they are off
        if (juDa.spentsite<0 || juDp.spentsite<0){
          juDa.spentsite=0;
          juDp.spentsite=0;
        }

        addDefaultCSS();

        if (typeof(ju_init) === 'function' && !ju_initialized) {
          ju_init();
        };

        if (ju_config.initFunc.length>0 && !ju_initialized) {
          jju.each(ju_config.initFunc,function(i,v){
            v();
          });
        };

        // try to auto set email
        if (juDs.config.email_sel) ju_autosetemail();

        // try to auto apply coupon
        ju_autoapplycoupon();

        //console.log("setting session data from server")
        jju_setCookie("_ju_pn", juDs.pagecount,.0208, '/', '.'+ju_config.root, '');

        ju_setup_cookie_data(false);

        if (ju_useBeacon && !ju_initialized){
          window.addEventListener('beforeunload', function(){
            ju_logpagestats();
            write_data_cookies(false,0,true);
          }, false);
        }

        if(data[0].res=="1"){

          test_targets();

          if(!ju_initialized) {
            ju_initialize(false);
          } else {
            // at least check to see if we need to readd default CSS
            addDefaultCSS();
          }
        } else {
          // account is in active or no live promotions
          ju_initialized = true;
          clearInterval(ju_target_interval)
          ju_target_interval = setInterval ( ju_targeting_data, 1000 );
          ju_targeting_data();
        }

        jju(document).on('mousemove.juEv keydown.juEv scroll.juEv touchmove.juEv', function () {
          ju_activityAdjust();
        });

        document.addEventListener('click', function (event) {
          ju_config.totalClicked += 1;
        }, false);

        jju('input,select,textarea').on('keydown.juEv', function () {
          ju_lastKeyDown = Math.round((new Date()).getTime() / 1000);
        });

			}

			addJuIcon();

			/*
			if (ju_config.ju_acow && !jju('.ju_element_controls_btn').length){
				jju.ajax({
					type: "GET",
					url: ju_domain+'/ajax/element-controls.js',
					dataType: "script",
					cache: true
				});
			}
			*/
		})["catch"](function (err) {
      //console.error('Justuno Problem Loading:', err);
      ju_logerr('loading error',err);
      //ju_config.ju_a=true;
      //ju_config.ju_country= 'US';
      //ju_setup_cookie_data(true);
      //clearInterval(ju_target_interval)
      //ju_a();
    });
  }

  function ju_replaceErrors(key, value) {
    if (value instanceof Error) {
      var error = {};

      Object.getOwnPropertyNames(value).forEach(function(propertyName) {
        error[propertyName] = value[propertyName];
      });

      return error;
    }
    return value;
  }

  function ju_logerr(note,err){
    var ignoreArr = ['whoop','always'];
    var ignoreFound = false;
    try{
      var juerr = JSON.stringify({source:note,error:err}, ju_replaceErrors)
      ignoreArr.forEach(function(ign){
        if (juerr.indexOf(ign)!=-1) ignoreFound = true;
      })
      if (juerr.length<30 ||("ActiveXObject" in window) || err.status==404 || err.status==200 || ignoreFound) return false;
      ju_safepost_p('https://'+ju_profileUrl+'/api/error','POST','text/plain',juerr,false)
      ["catch"](function (err) {
        console.log('trouble logging error',juerr)
      });
    } catch(er){
      ju_safepost_p('https://'+ju_profileUrl+'/api/error','POST','text/plain',"error serializing : "+note,false)
      ["catch"](function (err) {
        console.log('trouble logging error',juerr)
      });
    }
  }

  function forceNumber(v,forceNum){
	var fNum = forceNum || 0;
	var a = (!v || isNaN(v) ? 0 : parseFloat(v));
	return (forceNum != null && a<fNum ? fNum : a);
  }

  function forceString(v,l){
    return (typeof(v)!=="string" && typeof(v)!=="number" ? '' : String(v).substring(0,l));
  }

  function parseImageFromTab(v){
  	if (v.indexOf('src=')>=0){
  		var t = jju(v).attr('src');
  	}
  	if (t!='' && t!=undefined){
  		var t_array = t.split('/');
  		t = t_array[t_array.length-1];
  	} else {
  		t = '';
  	}
  	return t
	}

	function ju_removeProp(obj, propToDelete) {
		for (var property in obj) {
			if (obj.hasOwnProperty(property)) {
				if (typeof obj[property] == "object") {
					ju_removeProp(obj[property],propToDelete);
				} else {
					if(property === propToDelete){
						delete obj[property];
					}
				}
			}
		}
	}

  function ju_setup_cookie_data(reset){
    // set new cookie data incase we need it
    ju_config.totalIdleTime = 0;
    ju_config.totalPctScrolled = 0;
    ju_config.totalClicked = 0;

  	var newcookiedata_page = {"visits":1, "userhide":0, "pagecount":1, "spentsite":0, "seen":0, "engaged":0, "cartItem":{}, "cartTotals":{"tp":0,"tq":0}, "arb":{}, "config":{}, "order":{}, "offers_seen":[], "offers_engaged":[], "prods_seen":[], "camefrom":ju_camefrom_url, "firsturl":ju_current_url, "thisurl":ju_current_url, "rules_matched":[], "extocm":[], "closed":[], "hashes":{"m":"","s1":"","s256":"","pc":0}, "exitback":0, "notif":{}};

		var utm_coupon = jju_getParameterByName('utm_coupon');
		if (utm_coupon != '') juapp('arb', 'utm_coupon', utm_coupon);

  	if (juDs.pagecount==1){
  		ju_new_visit = 1;

      var utm_source = jju_getParameterByName('utm_source');
      var utm_medium = jju_getParameterByName('utm_medium');
      var utm_campaign = jju_getParameterByName('utm_campaign');
      var utm_term = jju_getParameterByName('utm_term');
      var utm_content = jju_getParameterByName('utm_content');

      if (utm_source!='') juapp('arb','utm_source',utm_source);
      if (utm_medium!='') juapp('arb','utm_medium',utm_medium);
      if (utm_campaign!='') juapp('arb','utm_campaign',utm_campaign);
      if (utm_term!='') juapp('arb','utm_term',utm_term);
      if (utm_content!='') juapp('arb','utm_content',utm_content);
  		//console.log("new visit")
  	}

    if (juDa.pagecount==1 && ju_config.ju_newuser){
      ju_new_user_ever = 1;
      if (ju_config.ju_newuser){
        // this is reset on the 1st of each month
        ju_new_user = 1;
      }
    }

  	if (!juDa.camefrom) juDa.camefrom = '';
  	juDa.camefrom = ((juDa.camefrom.substring(juDa.camefrom.length-1) == "/") ? juDa.camefrom.substring(0, juDa.camefrom.length-1) : juDa.camefrom).replace('https://','').replace('http://','');

  	if (!juDa.firsturl) juDa.firsturl = '';
  	juDa.firsturl = ((juDa.firsturl.substring(juDa.firsturl.length-1) == "/") ? juDa.firsturl.substring(0, juDa.firsturl.length-1) : juDa.firsturl).replace('https://','').replace('http://','');

  	if (!juDs.firsturl) juDs.firsturl = '';
  	juDs.firsturl = ((juDs.firsturl.substring(juDs.firsturl.length-1) == "/") ? juDs.firsturl.substring(0, juDs.firsturl.length-1) : juDs.firsturl).replace('https://','').replace('http://','');

  	// setup any page data

  	juDp = ju_data_page = newcookiedata_page;

  	// now add some data back

  	juDa.cnt = juDs.cnt = ju_config.ju_country;
  	juDa.reg = juDs.reg = ju_config.ju_region;
  	juDa.cty = juDs.cty = ju_config.ju_city;
  	juDa.zip = juDs.zip = ju_config.ju_zip;

  	if (!reset){
  		ju_a();
  	} else {
			ju_pageChange(true);
      // delete all current promos from the dom
      jju('.ju_Con,#ju_bbox,#ju_custom_open_btn,#ju_overlay,[class^="ju_CSSJS_"]').remove();
      ju_initialized_button = false;
      addDefaultCSS();
			newcookiedata_page.cnt = juDa.cnt;
			newcookiedata_page.reg = juDa.reg;
			newcookiedata_page.cty = juDa.cty;
			newcookiedata_page.zip = juDa.zip;
  		//console.log('cookie setup')
      juDp = ju_data_page = jju.extend(true, {}, newcookiedata_page);
  		juDs = ju_data_session = jju.extend(true, {}, newcookiedata_page);
      newcookiedata_page.cartTotals = [jju.extend(true, {}, ju_tmpCartObj)];
      juDa = ju_data_all = jju.extend(true, {}, newcookiedata_page);

      if (ju_current_url_protocol=="https://" && window.Notification) {
        juDs.notif.perm==window.Notification.permission;
        juDa.notif.perm==window.Notification.permission;
      }

      var utm_source = jju_getParameterByName('utm_source')
      var utm_medium = jju_getParameterByName('utm_medium')
      var utm_campaign = jju_getParameterByName('utm_campaign')
      var utm_term = jju_getParameterByName('utm_term')
      var utm_content = jju_getParameterByName('utm_content')

      if (utm_source!='') juapp('arb','utm_source',utm_source);
      if (utm_medium!='') juapp('arb','utm_medium',utm_medium);
      if (utm_campaign!='') juapp('arb','utm_campaign',utm_campaign);
      if (utm_term!='') juapp('arb','utm_term',utm_term);
      if (utm_content!='') juapp('arb','utm_content',utm_content);

  		ju_new_visit = 1;
      ju_new_user = 1;
      ju_new_user_ever = 1;
      ju_il_activated_exit = false;
      ju_il_activated_back = false;
      ju_targetruncount = 0;
      if (history.state){
        history.state.page = undefined;
      };
      ju_exitback = false;
  		write_data_cookies(true,600,false);
  	}

		if (juDs.pagecount == 5 && ju_config.ju_plan >= 200 && ju_config.ju_plan <= 299 && !ju_initialized && ju_config.ju_vid && ju_config.ju_vid!=''){

      setTimeout(function(){
        jju.ajax({
          type: 'GET',
          contentType: false,
          url: 'https://tools.justuno.com/comp/detectedScripts/'+ju_active_ju_num,
          jsonpCallback: 'jsonComp',
          global: false,
          cache: true,
          contentType: "application/json",
          dataType: 'jsonp',
          success: function(data) {
            // console.log('results:', results);
            var detected = ju_detectCompetitors();
            // console.log('detected:', detected);

            var changes = ju_compareDetected(detected.competitors, data.competitors);
            // console.log('changes:', changes);

            if(changes){
              var update = safeToJSON({
                accid: ju_active_ju_num,
                vid: ju_config.ju_vid,
                competitors: changes
              });

              ju_safepost_p('https://tools.justuno.com/comp/updateDetectedScripts','POST','application/json',update,false)
              ["catch"](function (err) {
                console.log('trouble logging error',juerr)
              });
            }
          }
        });
      },10000)

    }
  }

  function ju_conv_cart(){
    if (juDa.order[ju_orderid] && !juDa.order[ju_orderid].hasOwnProperty("i")) {
      for (var k in juDs.cartItem) {
        var ki = juDs.cartItem[k].v;
        juapp('orderItem',{productid:ki.i,variationid:ki.v,sku:ki.u,quantity:ki.q,price:ki.p,name:ki.n,color:ki.c,size:ki.s});
      }
    }
    // remove all items from cart
    juDs.cartItem={};
    juDa.cartItem={};
    juDs.cartTotals={"tp":0,"tq":0};
    juDa.cartTotals[juDa.cartTotals.length - 1] = jju.extend(true, {}, ju_tmpCartObj);
  }

	function ju_log_conversion(){
		clearTimeout(ju_cv_timer_check);
		ju_cv_timer_check = setTimeout(function () {
			if (typeof (ju_cvs_recorded) != 'boolean') {
        window.ju_cvs_recorded = true;
        try {
          ju_conv_cart();
          ju_submit_conv();
        } catch (e) {
          ju_logerr('conversion tracking error',e);
        }
			}
		}, 50);
	}

	function ju_submit_conv() {

		var juConvArr = [];

		// add any same session engagements to the array
		jju.each(juDs.offers_engaged, function() {
			var id = this.ID;
			var ex = juDs.extocm.filter(function(v) {
				return v.cm == id;
			});
			var testId = 0;
			if (ex && ex[0] && ex.length>0 && ex[0].ex) testId = ex[0].ex;
			juConvArr.push({promoId:id,abTestId:testId,sEng:true,aEng:true});
		})

		// add any past engagements to the array
		jju.each(juDa.offers_engaged, function() {
			var id = this.ID;
			var dt = this.dt;

			if (dt && !existArrayObj(juConvArr,'promoId',id)){
				if (juConvArr.length > 0){
					if (ju_todayDate()-dt <= 7){
						juConvArr.push({promoId:id,abTestId:0,sEng:false,aEng:true});
					}
				} else {
					if (ju_todayDate()-dt <= 14){
						juConvArr.push({promoId:id,abTestId:0,sEng:false,aEng:true});
					}
				}
			}
		})

		// there are no engaged promos to add conversions for
		if (juConvArr.length == 0) juConvArr.push({promoId:0,abTestId:0,sEng:false,aEng:false});

		// loop through array and start posting engagements
		jju.each(juConvArr, function() {
			try{
				var ju_conv_post = {
					accid:ju_active_ju_num,
					promoId:parseInt(this.promoId),
					abTestId:parseInt(this.abTestId),
					orderId:ju_orderid,
					revenue:juDs.order[ju_orderid].v.t,
					sameSessEng:this.sEng,
					anySessEng:this.aEng,
					sessionKey:ju_config.ju_sessionkey,
					pageId:ju_pageid,
					currency:juDs.order[ju_orderid].v.c
				}

        ju_beaconsend('https://'+ju_profileUrl+'/api/analytics/conversion',ju_conv_post);
        try{
          jju.each(ju_config.trackFunc,function(i,v){
            v.conversion();
          });
        } catch(e){

        }
			} catch(e){
        ju_logerr('conversion',e);
			}
		});

	}

  function ju_beaconsend(url,formdata,usebeacon){

  	try {
  		if (_ju_dt.length>0){
  			if (ju_useBeacon && usebeacon){
  				navigator.sendBeacon(url, safeToJSON(formdata));
          ju_plastsaved = (new Date()).getTime();
  			} else {
          ju_safepost_p(url,'POST','text/plain',safeToJSON(formdata),false)
  			}
  		}
  	} catch(e){
      // do something
      try {
        ju_safepost_p(url,'POST','text/plain',safeToJSON(formdata),false)
      } catch(err){
        ju_logerr(url,err);
      }
  	};
	}

	function ju_regtest_array(arr,v){
		var tmp = false;
		jju.each(arr,function(){
			if (this.test(v)){
				tmp = true;
				return;
			}
		})
		return tmp;
	}

	function ju_beaconsend_gzip(url,formdata,usebeacon){
  	try {
      if (usebeacon) url = url+'-beacon';

  		if (_ju_dt.length>0){
				var notCompat = navigator.userAgent.match(/(?!.*Chrome).(iPad|iPhone|iphone|iPod|Android).*?(OS |os |OS\_|Version\/)(\d+((_|\.)\d)?((_|\.)\d)?)/i);
				var notCompatArr = [
					/.*Windows NT 6\.1.*\Chrome\/58\.0\.3029\.110.*/i,
					/.*Epiphany.*/i,
					/.*NintendoBrowser.*/i,
          /.*rv:11*/i,
          /.*MSIE 7.0*/i
        ];
        if (ju_regtest_array(notCompatArr,navigator.userAgent) || ju_config.ju_acow || (navigator.userAgent.indexOf('Trident/7.0')==-1 && notCompat && notCompat[3] && parseInt(notCompat[3].split('_')[0])<=8)) {
					var gzip = safeToJSON(formdata);
				} else {
					var gzip = pako.gzip(safeToJSON(formdata),{ level: 9});
        }
  			if (ju_useBeacon && usebeacon){
  				navigator.sendBeacon(url, gzip);
  			} else {
					ju_safepost_p(url,'POST','text/plain',gzip,false)
				}
				ju_plastsaved = (new Date()).getTime();
  		}
  	} catch(e){
      try{
        ju_safepost_p(url,'POST','text/plain',safeToJSON(formdata),false)
      } catch(err){
        ju_logerr('gzip: '+url,err);
      }
  	};
	}


  function ju_visibility_change() {
    if (document.hidden) {
      ju_visible = false;
    } else  {
      ju_visible = true;
    }
  }

  try{
  	document.addEventListener("visibilitychange", ju_visibility_change, false);
  } catch(err){}

  function ju_savetodb(usebeacon){
  	//return false;
  	//console.log('beacon send')

  	// jju_setCookie("juDs", "",-1, '/', '.'+ju_config.root, '');
  	// jju_setCookie("juDa", "",-1, '/', '.'+ju_config.root, '');
		//ju_beaconsend(ju_domain+'/ajax/save_cookie_to_db.html',{id: ju_active_ju_num, guid: _ju_dt, session: safeToJSON(juDs), all: safeToJSON(juDa)})

  	if (!ju_stopupdating) ju_beaconsend_gzip('https://'+ju_profileUrl+'/api/session/update',{"guid":_ju_dt,"accid":ju_active_ju_num,"session":{"current": juDs, "allTime": juDa, "sessionKey": ju_config.ju_sessionkey, "cartUpdate": ju_cartDirty}},usebeacon);
		ju_cartDirty = false;
	}

  function safeToJSON(value){
      if (typeof value === 'object' && typeof Object.toJSON === 'function') {
				return Object.toJSON(value);
			} else if (typeof value === 'object' && typeof Array.toJSON === 'function') {
				return Array.toJSON(value);
      } else if (typeof value === 'object') {
      	return JSON.stringify(value);
			}
  }

  function ju_limitobjectlength(obj,allowed){
    var objlen = ju_objectlength(obj);

    if (objlen<=allowed) return obj;

    var tempArray = [];
    var k;
    for(var k in obj) {
      var tempk = {};
      tempk[k] = obj[k];
      tempArray.push(tempk);
    }

    tempArray = tempArray
      .sort(function(a, b) {
        return a.d < b.d
      })
      .slice(tempArray.length-allowed, tempArray.length);

    var newObj = {};
    tempArray.forEach(function(val) {
      var k = Object.keys(val)[0];
      newObj[k] = val[k];
    })
    return newObj;
  }

  function ju_objectlength(obj) {
      var size = 0, key;
      for (key in obj) {
          if (obj.hasOwnProperty(key)) size++;
      }
      return size;
  };

	function ju_safepost_p(url,method,type,data,cred,headers) {
		return new Promise(function(resolve, reject) {
      method = method.toLowerCase();
      jju.ajax({
        timeout: 5000,
        type: method,
        data: data,
        url: url,
        dataType:'',
        processData: (type.indexOf('urlencoded')!=-1 ? true : false),
        global: false,
				contentType: type,
				headers: headers,
        xhrFields: {
          withCredentials: cred
        },
        beforeSend: function(jqXHR, settings) {
          jqXHR.url = settings.url;
        },
        success: function(data) {
          resolve(data);
        },
        error: function(res){
          if (headers){
            var fHeaders = headers;
          } else {
            var fHeaders = {};
          }
          fHeaders["Content-Type"] = type;
          if (method=='post'){
            fBody = data;
          } else {
            fBody = null;
            url = url+'?'+jju.param(data);
          };
          fetch(
            url,
            {
              method: method,
              cache: 'no-cache',
              credentials: (cred ? 'include' : 'omit'),
              headers: fHeaders,
              body: fBody
            }
          )
          .then( function(data){
            resolve(data.text())
          })
          .catch( function(data){
            reject(data)
          });
        }
      })

		});
  }

  function ju_jsonp_p(url,data,callback) {
		return new Promise(function(resolve, reject) {
      jju.ajax({
        type: 'GET',
        cache:true,
        data: data,
        url: url,
        jsonpCallback: callback,
        global: false,
        contentType: "application/json",
        dataType: 'jsonp',
        //timeout : 10000, // this doesn't play nice with some libraries, but is required to catch timeout errors
        beforeSend: function(jqXHR, settings) {
          jqXHR.url = settings.url;
        },
        success: function(data) {
          resolve(data);
        },
        error: function(data){
          reject(data);
        }
      })
    });
  }

  function addDefaultCSS(){
    var raw_css = '';
    var cssExists = jju('style.ju_CSSJS_default').length;

    if (ju_show_button && (!cssExists || !ju_initialized_button)){

      if (ju_config.ju_custombutton==""){

        raw_css += ".ju_preview_3 {white-space: nowrap;font-family: \"Helvetica Neue\", Helvetica, Arial, sans-serif; font-weight:500; line-height: 1.428571429; background-color: #fff;text-rendering: optimizeLegibility !important;-webkit-font-smoothing: antialiased !important;display:none; z-index:999996; position: absolute; position: fixed;  color: white; text-align: center;  cursor: pointer;  }  .ju_preview_3.ju-tab-on-off-1 {    display: block; }  .ju_preview_3.ju-tab-size-0 {    padding: 10px; }  .ju_preview_3.ju-tab-size-1 {    padding: 20px; }  .ju_preview_3.ju-tab-size-2 {    padding: 30px; }  .ju_preview_3.ju-tab-size-3 {    padding: 10px 0; }  .ju_preview_3.ju-tab-corners-0.ju-tab-location-0 {    -webkit-border-radius: 5px 5px 0px 0px;    border-radius: 5px 5px 0px 0px; }  .ju_preview_3.ju-tab-corners-0.ju-tab-location-1 {    -webkit-border-radius: 0px 0px 5px 5px;    border-radius: 0px 0px 5px 5px; }  .ju_preview_3.ju-tab-corners-0.ju-tab-location-2 {    -webkit-border-radius: 0px 0px 5px 5px;    border-radius: 0px 0px 5px 5px; }  .ju_preview_3.ju-tab-corners-0.ju-tab-location-3 {    -webkit-border-radius: 5px 5px 0px 0px;    border-radius: 5px 5px 0px 0px; }  .ju_preview_3.ju-tab-shadow-1.ju-tab-location-0, .ju_preview_3.ju-tab-shadow-1.ju-tab-location-3 {    -webkit-box-shadow: 0px -1px 5px 1px rgba(0, 0, 0, 0.5);    box-shadow: 0px -1px 5px 1px rgba(0, 0, 0, 0.5); }  .ju_preview_3.ju-tab-shadow-2.ju-tab-location-0, .ju_preview_3.ju-tab-shadow-2.ju-tab-location-3 {    -webkit-box-shadow: -2px -1px 5px 1px rgba(0, 0, 0, 0.5);    box-shadow: -2px -1px 5px 1px rgba(0, 0, 0, 0.5); }  .ju_preview_3.ju-tab-shadow-1.ju-tab-location-1, .ju_preview_3.ju-tab-shadow-1.ju-tab-location-2 {    -webkit-box-shadow: 0px 1px 5px 1px rgba(0, 0, 0, 0.5);    box-shadow: 0px 1px 5px 1px rgba(0, 0, 0, 0.5); }  .ju_preview_3.ju-tab-shadow-2.ju-tab-location-1, .ju_preview_3.ju-tab-shadow-2.ju-tab-location-2 {    -webkit-box-shadow: -2px 1px 5px 1px rgba(0, 0, 0, 0.5);    box-shadow: -2px 1px 5px 1px rgba(0, 0, 0, 0.5); }" +
          ".ju_preview_3:hover {filter: brightness(1.1); -webkit-filter: brightness(1.1); -moz-filter: brightness(1.1); -o-filter: brightness(1.1);}"

      } else {
        // just need to position the initial custom button out of site so we can get the dimensions and then properly place it
        raw_css += "#ju_bbox {display:none; z-index:999996;overflow:visible !important;position: fixed;  }" +
          "#ju_bbox img {border:none !important; max-width:500px !important;} "

      }

      raw_css += "#ju_custom_close_btn {color:#fff;line-height: 24px !important; z-index:99999997; position: absolute !important; font-size: 14px !important; text-decoration: none !important; font-family:Arial !important;height:24px !important;width:24px !important;text-align: center !important;font-weight: 500 !important;}" +
        "#ju_custom_open_btn {color:#fff;display:none; z-index:99999997; position: fixed; padding: 5px;font-size: 11px; font-weight: bold; color: #fff; text-decoration: none; font-family:Arial !important;}" +
        "#ju_bbox * {-webkit-box-sizing: initial !important;-moz-box-sizing: initial !important;box-sizing: initial !important;margin:0px !important;padding:0px !important;} "

      if(cssExists) ju_add_css(raw_css, 'default');

    }

    if (!cssExists){
    //if (!skipstart){

      raw_css += ".ju_Con{text-align:left;z-index:99999998;top:0px;left:0px;display:none;font-family:Arial, Helvetica, sans-serif;width:100%;position:absolute;position:fixed; box-sizing:content-box;line-height: normal;-moz-transition: none;-webkit-transition: none;-o-transition: color 0 ease-in;transition: none;} " +
        ".ju_overlay {text-align: center; display: none; -webkit-transform: translateZ(0); position: fixed; left: 0%; top: 0%; width: 100%; height: 100%; z-index: 999998; background-position: center center; background-repeat: no-repeat; background-size: cover;}" +
        ".ju_overlay:before {content: '';height: 100%;display: inline-block;vertical-align: middle;} " +
        ".ju_iframe{border:none !important;width:100%;height:100% !important;display:block !important;opacity:0;max-width:none !important;} " +
        ".ju_inpage_con {padding:0 !important;} " +
        ".ju_inpage_back {background-position: center center; background-repeat: no-repeat; background-size: cover;} " +
        ".ju_hideall {display:none !important;} "

      if (ju_config.ju_button_css!=undefined){
        raw_css = raw_css + ju_config.ju_button_css;
      }

      raw_css = ju_config.customCSS + '\n' + raw_css;

      ju_add_css(raw_css, 'default');

      // add any custom js

      ju_add_js(ju_config.customJS, 'default')

    }
  }

  function ju_initialize(skipstart){
  	if (!skipstart){
  		ju_target_interval = setInterval ( ju_targeting_data, 1000 );
      ju_targeting_data();
  	}

  	// done getting config
  	if (ju_config.ju_status=="1"){

  		addDefaultCSS();

  		if (ju_show_button && !ju_initialized_button){

        // log the tab impression
        if (ju_loadcm==0) {
          var exIDresult = juDs.extocm.filter(function(v) {
            return v.cm == ju_show_tab_campaign_id;
          });
		
          var exID = (exIDresult.length===0 ? 0 : exIDresult[0].ex);
          ju_beaconsend('https://'+ju_profileUrl+'/api/analytics/tabimpression',{"accid":ju_active_ju_num,"promoId":parseInt(ju_show_tab_campaign_id),"abTestId":exID,"sessionKey":ju_config.ju_sessionkey,"pageId":ju_pageid});
        }
        // done logging tab impression

  			ju_initialized_button = true;
//console.log('ju_show_campaign_id',ju_show_campaign_id,ju_show_button)
			if (ju_show_button && ju_show_tab_campaign_id>0){
  			if (ju_config.ju_custombutton==""){


  				// lets show justuno button

  				// lets attempt to delay this for a half second to help account for browsers still tweaking size of dom
  				setTimeout(function(){

  					var waitforgooglefont = false;
  					//console.log(ju_config.ju_button_text)

  					if (typeof(ju_config.ju_fonts) === 'object'){

  						if (!jju.isEmptyObject(ju_config.ju_fonts)) {

  							var ju_google_fonts = [];
  							var ju_obj_serialized = ju_config.ju_button_text; //safeToJSON(ju_config.ju_button_text);

                //console.log(ju_obj_serialized)

  							jju.each(ju_config.ju_fonts,function(key, data){
                  //console.log(ju_obj_serialized.indexOf(key))
  								if (ju_obj_serialized.indexOf(key.toLowerCase())!=-1){
  									ju_google_fonts.push(key+":400,700");
                    ju_google_fonts.push(key+":400i,700i");
  									//console.log('tab found font being used - '+key)
  								} else {
  									//console.log('tab couldn\'t find font being used - '+key)
  								}
  							});

  							//console.log(ju_google_fonts)

  							if (ju_google_fonts.length && ju_config.loadGoogleFonts) {

                  ju_google_fonts[ju_google_fonts.length-1] = ju_google_fonts[ju_google_fonts.length-1]+'&display=swap';

  								waitforgooglefont = true;

  								// incase google font is already loaded on site
  								ju_googlefonttimer = setTimeout(function(){
  					    			tabOptions();
  						    		tabPosition();
  									ju_animate_button();
  					    		}, 2000);

  								WebFontConfig = {
  							    	google: { families: ju_google_fonts },
  							    	active: function() {
  							    		clearTimeout(ju_googlefonttimer);
  						    			tabOptions();
  							    		tabPosition();
  										ju_animate_button();
  							    	}
  								};

  								(function() {
  									var wf = document.createElement('script');
  									wf.src = window.asset_host+'webfont.js';
  									wf.type = 'text/javascript';
  									wf.async = 'true';
									if (document.querySelector('script[nonce]') && document.querySelector('script[nonce]')?.nonce!="null" && document.querySelector('script[nonce]')?.nonce!="") wf.nonce = document.querySelector('script[nonce]')?.nonce;
  									var s = document.getElementsByTagName('script')[0];
  									s.parentNode.insertBefore(wf, s);
  								})();
  							}
  						};
  					};

  					var ju_button_html = '<div id="ju_tab_text" class="ju_tab_text">' + ju_config.ju_button_text + '</div>';

  					var ju_myLink = document.createElement('div');

  					ju_myLink.setAttribute('id','ju_bbox');

  					ju_myLink.innerHTML = ju_button_html;

  					var bodybottom = document.getElementsByTagName('body')[0];
  					bodybottom.appendChild(ju_myLink);

  					jju('#ju_bbox').addClass("ju_preview_3").attr("data-promoid",ju_show_tab_campaign_id).data("promoid",ju_show_tab_campaign_id);

  					//console.log("inserting ju_preview_3 into dom")

						if (!waitforgooglefont){
							tabOptions();
              tabPosition();
              ju_animate_button();
						};

  					jju('#ju_bbox').click(function(event){
              event.preventDefault();
              event.stopPropagation();
  						ju_tabClick();
            });

  				},1000)

  			} else {


  				// lets show custom button

  				ju_svgmode = true // we don't want to rotate anything

  				var ju_myLink = document.createElement('div');
  				var ju_myImg = jju("<img>");

  				ju_myLink.setAttribute('id','ju_bbox');
  				var ju_button_stuff = '<a href="Javascript:void(0);" id="ju_custom_close_btn">X</a><a class="ju_custom_button"></a>';
  				ju_myLink.innerHTML = ju_button_stuff;

  				var bodybottom = document.getElementsByTagName('body')[0];
  				bodybottom.appendChild(ju_myLink);

  				jju('#ju_bbox').addClass("ju_preview_3").attr("data-promoid",ju_show_tab_campaign_id).data("promoid",ju_show_tab_campaign_id);


  				jju('a.ju_custom_button').attr('href','Javascript:void(0)').append(ju_myImg);

  				tabOptions();

  				// create load event for custom button
  				ju_myImg.on("load.juEv",function(){
  					// get width and height and place it correctly by writing the css
  					tabPosition();

  					if (juDs.userhide==0){
  						ju_animate_button();
  					}else{
  						ju_animate_show_open()
  					}

  				});

  				ju_myImg.attr('src',"//tabs.justuno.com/"+ju_config.ju_custombutton);

  				jju("#ju_custom_close_btn").on((touchPresent?'touchstart':'click'), function (event) {
            event.preventDefault(); event.stopPropagation();
  					ju_animate_hide_button();
  					juDs.userhide=1;
  					write_data_cookies(false,100,false);
  				});

  				jju("#ju_custom_open_btn").on((touchPresent?'touchstart':'click'), function (event) {
            event.preventDefault(); event.stopPropagation();
  					ju_reshow_button();
  					juDs.userhide=0;
  					write_data_cookies(false,100,false);
  				});

  				jju('#ju_bbox a.ju_custom_button').on((touchPresent?'touchstart':'click'), function (event) {
            event.preventDefault(); event.stopPropagation();
  					ju_tabClick();
          });

          jju('#ju_bbox img').click(function(event){
            event.preventDefault();
          });

  			}
		}



  		}

  		if (!skipstart){

  			//ju_createiframe(promo_count_id);

  			// new intent to leave

  			setTimeout(function(){

  				if (ju_setupexitintent){
  					var _ouibounce = ouibounce(false, {
  						sensitivity: 5,
  						aggressive: true,
  					  callback: function() {
  					  	if ( ju_loadcm>0 ) return;
  					  	if (!ju_il_activated_exit){
                  ju_il_activated_exit = true;
                  ju_targeting_data();
                }
  					  }
  					});
  				}

  				if (ju_setupbackintent){
  					window.addEventListener('popstate', function(event) {
    					//console.log('popstate fired!');

    					if (history.state  &&  history.state.page == juDs.exitback) {
  					    // It appears that we are positioned at the first history item for this site
  					    if ( ju_loadcm>0 ) return;
  					  	if (!ju_il_activated_back){
    					  		//console.log("back")
    							ju_il_activated_back = true;
    							ju_targeting_data();
  							}
  						}
  					});
  				}

					if (ju_setupclickintent.length>0){
						jju.each(ju_setupclickintent,function(i,v){
							try {
								jju(document).on('click.ju_widget',v,function(e){
									if (jju(this).attr('href')=='#') e.preventDefault();
									if ( ju_loadcm>0 ) return;
									ju_setupclickintent_el = v;
									ju_targeting_data();
								})
							} catch (er) {
								console.log('Justuno | Invalid selector used in targeted click condition : ' + v)
							}
						})
					}

					if (ju_setuphoverintent.length>0){
						jju.each(ju_setuphoverintent,function(i,v){
							try {
								jju(document).on('mouseenter.ju_widget',v,function(e){
									if ( ju_loadcm>0 ) return;
									ju_setuphoverintent_el = v;
									ju_targeting_data();
								})
							} catch (er) {
								console.log('Justuno | Invalid selector used in targeted hover condition : ' + v)
							}
						})
					}


  			},100)

  			// end intent to leave
  		};

  	};

		if (!skipstart) {
  		ju_initialized = true;
		}
  }

  function ju_tabClick(){
		var exIDresult = juDs.extocm.filter(function(v) {
			return v.cm == ju_show_tab_campaign_id;
		});

    var exID = (exIDresult.length===0 ? 0 : exIDresult[0].ex);

    if (ju_loadcm==0) {
			ju_beaconsend('https://'+ju_profileUrl+'/api/analytics/tabclick',{"accid":ju_active_ju_num,"promoId":parseInt(ju_show_tab_campaign_id),"abTestId":exID,"sessionKey":ju_config.ju_sessionkey,"pageId":ju_pageid});
		}

		if (ju_config.ju_tab_url!=''){
  		if (ju_config.ju_tab_window=='_blank'){
  			window.open(ju_config.ju_tab_url,'_blank');
  		} else {
  			document.location = ju_config.ju_tab_url;
  		}
  	} else {
      ju_show_campaign_id = ju_show_tab_campaign_id;
  	  jju("#ju_Con_"+ju_show_campaign_id+" .ju_iframe").css({'opacity':0});
  		jju("#ju_Con_"+ju_show_campaign_id).css({'left':'0px','top':'0px','height':'100%','width':'100%'});
  		//resizejucon(0,true,false);
      ju_loadiframe({'focus':true,'exid':exID});
  		ju_promo_title = decodeURI(jju("#ju_Con_"+ju_show_campaign_id).data('title'));
  		ju_promo_options = jju("#ju_Con_"+ju_show_campaign_id).data('promo_options');
			ju_record_event('', 'Tab Click', ju_promo_title, ju_show_campaign_id, { "promo_options": ju_promo_options }, 1, []);
  	}
  }


  function ju_reshow_button(){

  	switch(ju_config.ju_location)
  	{
  	case "ju-tab-location-0":
  		jju('#ju_custom_open_btn').animate({
  		right: -25
  		}, 300, function(){
  			ju_animate_button()
  		});
  	  break;
  	case "ju-tab-location-1":
  		jju('#ju_custom_open_btn').animate({
  		left: -25
  		}, 300, function(){
  			ju_animate_button()
  		});
  	  break;
  	case "ju-tab-location-2":
  		jju('#ju_custom_open_btn').animate({
  		top: -25
  		}, 300, function(){
  			ju_animate_button()
  		});
  	  break;
  	case "ju-tab-location-3":
  		jju('#ju_custom_open_btn').animate({
  		bottom: -25
  		}, 300, function(){
  			ju_animate_button()
  		});
  	  break;
  	}


  }

  function ju_animate_show_open(){

  	jju('#ju_custom_open_btn').css('display','block')

  	switch(ju_config.ju_location)
  	{
  	case "ju-tab-location-0":
  		jju('#ju_custom_open_btn').animate({
  		right: 0
  		}, 300);
  	  break;
  	case "ju-tab-location-1":
  		jju('#ju_custom_open_btn').animate({
  		left: 0
  		}, 300);
  	  break;
  	case "ju-tab-location-2":
  		jju('#ju_custom_open_btn').animate({
  		top: 0
  		}, 300);
  	  break;
  	case "ju-tab-location-3":
  		jju('#ju_custom_open_btn').animate({
  		bottom: 0
  		}, 300);
  	  break;
  	}

  }

  function ju_animate_hide_button(){



  	switch(ju_config.ju_location)
  	{
  	case "ju-tab-location-0":
  		jju('#ju_bbox').animate({
  		right: juStartingPosition
  		}, 300, function(){
  			jju('#ju_bbox').hide();
  			ju_animate_show_open()
  		});
  	  break;
  	case "ju-tab-location-1":
  		jju('#ju_bbox').animate({
  		left: juStartingPosition
  		}, 300, function(){
  			jju('#ju_bbox').hide();
  			ju_animate_show_open()
  		});
  	  break;
  	case "ju-tab-location-2":
  		jju('#ju_bbox').animate({
  		top: juStartingPosition
  		}, 300, function(){
  			jju('#ju_bbox').hide();
  			ju_animate_show_open()
  		});
  	  break;
  	case "ju-tab-location-3":
  		jju('#ju_bbox').animate({
  		bottom: juStartingPosition
  		}, 300, function(){
  			jju('#ju_bbox').hide();
  			ju_animate_show_open()
  		});
  	  break;
  	}

  }

  function ju_animate_button(){
  	switch(ju_config.ju_location)
  	{
  	case "ju-tab-location-0":
  		jju('#ju_bbox').show();
  		jju('#ju_bbox').animate({
  		right: juFinalPosition
  		}, 500);
  		jju('#ju_bbox').css('display','block');
  	  break;
  	case "ju-tab-location-1":
  		jju('#ju_bbox').show();
  		jju('#ju_bbox').animate({
  		left: juFinalPosition
  		}, 500);
  		jju('#ju_bbox').css('display','block');
  	  break;
  	case "ju-tab-location-2":
  		jju('#ju_bbox').show();
  		jju('#ju_bbox').animate({
  		top: juFinalPosition
  		}, 500);
  		jju('#ju_bbox').css('display','block');
  	  break;
  	case "ju-tab-location-3":
  		jju('#ju_bbox').show();
  		jju('#ju_bbox').animate({
  		bottom: juFinalPosition
  		}, 500);
  		jju('#ju_bbox').css('display','block');
  	  break;
  	}

  }

  function ju_activityAdjust(){
    var curScrolled = (jju(window).scrollTop()+jju(window).height())/(jju(document).height());
    curScrolled = curScrolled>1 ? 1 : curScrolled;
    ju_config.totalPctScrolled = curScrolled>ju_config.totalPctScrolled ? curScrolled : ju_config.totalPctScrolled;
    ju_idleStateTime = 0;
  }


  function ju_createiframe(cmid,zindex,title,options){

  	jju('<div class="ju_Con" id="ju_Con_'+cmid+'" data-position="" data-zindex="'+zindex+'" style="z-index:'+zindex+';position:'+(fixed_supported ? 'fixed' : 'absolute')+'" data-title="'+encodeURI(title)+'"><div class="ju_wrapper" style="width: 100%; height: 100%; overflow: auto; -webkit-overflow-scrolling: touch;overflow-x: hidden;"></div></div>').appendTo( "body" );
  	jju('#ju_Con_'+cmid).data('promo_options',options);
	}

	var pstmsgresize = ju_debounce(function (id,resize,orientation) {
		setwidthheight();
		if (ju_mobile && !fixed_supported) {
			alert_iframe_of_scroll();
		}
		//console.log('ju_stoptop_resize',ju_stoptop)
		resizejucon(id, resize, orientation);
	}, 20, 'End');

	// var pstmsgscroll = ju_debounce(function () {
	// 	if (ju_mobile && !fixed_supported) {
	// 		alert_iframe_of_scroll();
	// 	}
	// 	//console.log('ju_stoptop_resize',ju_stoptop)
	// 	resizejucon(0, true, false);
	// 	console.log('scroll')
	// }, 300, 'End');

  function ju_setup_interval_stuff(){

  	jju(window).on('resize',function(){
			//console.log('resize')
  		if (!ju_stoptop){
  			pstmsgresize(0,true,false);
  		}
  	});

  	// if (ju_mobile && !fixed_supported){
  	// 	jju(window).on('scroll.juEv',function(){
  	// 		if (!ju_stoptop){
  	// 			//clearTimeout(ju_scroll_check)
  	// 			//ju_scroll_check = setTimeout(function(){
  	// 				//alert_iframe_of_scroll();
    //         //console.log('ju_stoptop_notfixed',ju_stoptop)
		// 				pstmsgresize(0, true, false);
  	// 			//},20)
  	// 		}
  	// 	});
  	// }

    if (touchPresent) {
      jju(window).on('scroll.juEv', function(){
        if (!ju_stoptop){
					window.ju_lastwindowheight = ju_windowHeight;
					setwidthheight();
					//console.log(ju_lastwindowheight,ju_windowHeight,document.documentElement.clientHeight,window.innerHeight,jju(window).height())
          if (ju_windowHeight != ju_lastwindowheight) {
            pstmsgresize(0, true, false);
					}

          if (ju_ratio>1.3){
            jju('.ju_overlay').addClass('ju_hideall');
            jju('.ju_Con').filter(function() {
              return (jju(this).css("position") === 'fixed' && jju(this).data('position') != 9);
            }).addClass('ju_hideall');
          } else if (jju('.ju_Con.ju_hideall').length) {
            jju('.ju_Con, .ju_overlay').removeClass('ju_hideall');
            //console.log('ju_stoptop_scroll_ratio',ju_stoptop)
            pstmsgresize(0, true, false);
          }
        }
      })
    }

    // if (!ju_stoptop){
		// 	//console.log('test screen size')
    //   window.ju_lastwindowheight = ju_windowHeight;
    //   setwidthheight();
    //   if (ju_windowHeight != ju_lastwindowheight) {
    //     pstmsgresize(0, true, false);
    //   }
    // }

  	jju(window).on( 'orientationchange.juEv', function(e){
  		clearTimeout(ju_scroll_check)
  		ju_scroll_check = setTimeout(function(){
  			//alert_iframe_of_scroll();
				//resizejucon(0,true,true);
				pstmsgresize(0, true, true);
  		},500)
  	});
  }

  function alert_iframe_of_scroll(){

  	//jju('.ju_Con').css({'top':jju(window).scrollTop()});

  	jju('.ju_iframe').each(function(){
  		var pass_data = {
  		'scroll_top':jju(window).scrollTop()
  		};

  		// ju_postMessage(
  		//   safeToJSON(pass_data),
  		//   jju(this).attr('src'),
  		//   document.getElementById(jju(this).attr('id')).contentWindow
      // );
      var thisConWin = document.getElementById(jju(this).attr('id')).contentWindow;
      if (typeof(thisConWin.jju_receiveMessage)==='function'){
        tryCatch(thisConWin.jju_receiveMessage(pass_data));
      }
  	})
  }

  function ju_inPageVisCheck(){
    //console.log('testing for viewable inpage promos');
    jju('.ju_inpage_con:not(.ju_seen)').each(function(){
      //console.log(jju(this).attr('id')+' check if viewable',ju_isInViewport(jju(this)));
      if (ju_isInViewport(jju(this))){
        jju(this).addClass('ju_seen');
        var thiscmid = jju(this).data('inpageId');
        var thisex = jju(this).data('ex');
        juDs.seen = 1;
        juDa.seen = 1;
        juDp.seen = 1;
              //console.log('iframe load')
        ju_logimpression(thiscmid,thisex);
      }
    })
  }

  function ju_loadiframe(new_options){
	//if (ju_show_campaign_id==-1) return;
  	var options = {'campaign_id':'','desktop_promotion_id':'','mobile_promotion_id':'','zindex':99999998,'preload':false,'loadwindow':'','windowLocation':5,'exid':'','focus':false};
  	if (ju_loadiframe.arguments.length == 0) var new_options = {};

  	for (var attrname in new_options) { options[attrname] = new_options[attrname]; }

	//console.log(ju_show_campaign_id)

  	if (options.desktop_promotion_id!='' && !ju_mobile) {
  		ju_show_campaign_id = options.desktop_promotion_id
  	} else if (options.mobile_promotion_id!='' && ju_mobile) {
  		ju_show_campaign_id = options.mobile_promotion_id
  	} else if (options.campaign_id!='') {
  		ju_show_campaign_id = options.campaign_id
    }

    if (options.loadwindow!='' && (options.campaign_id!='' || options.campaign_id==0)){
      if (!jju(options.loadwindow).length) return false;
      options.windowLocation = (options.windowLocation && options.windowLocation!='' ? options.windowLocation : 5);
      switch(options.windowLocation) {
        case 1:
          jju('<div id="ju_inpage_'+options.campaign_id+'"><\/div>').insertBefore(options.loadwindow);
          break;
        case 2:
          jju('<div id="ju_inpage_'+options.campaign_id+'"><\/div>').insertAfter(options.loadwindow);
          break;
        case 3:
          jju(options.loadwindow).prepend('<div id="ju_inpage_'+options.campaign_id+'"><\/div>');
          break;
        case 4:
          jju(options.loadwindow).append('<div id="ju_inpage_'+options.campaign_id+'"><\/div>');
          break;
      }

      if (options.windowLocation!=5) options.loadwindow = '#ju_inpage_'+options.campaign_id;

      jju(options.loadwindow).addClass('ju_inpage_con').data({'inpageId':ju_show_campaign_id,'ex':options.exid});

      if (ju_show_campaign_id==0) return false;
    } else if (ju_show_campaign_id==0){
      // this means we are comparing them to no promotion and they have been selected to show no promotion
      if (!options.preload) ju_logimpression(ju_show_campaign_id,options.exid);
			return false;
    }

    if (new_options && new_options.campaign_id==0) return false;

		var tabjson_match = existArrayObj(ju_config.ju_campaigns,'cmid',ju_show_campaign_id);

  	if (!tabjson_match && ju_show_campaign_id>0){
  		// we need to fetch the tab json since this is being loaded without it via javascript
  		ju_config_timeout = setTimeout( function(){
  			ju_loadiframe_con(options)
  		}, 2000 );
  		jju.ajax({
  			url: ju_domain+"/ajax/get_tab_json.html?id="+ju_active_ju_num+"&cm="+ju_show_campaign_id+'&pageid='+ju_pageid+"&callback=?",
  		    dataType: 'jsonp',
  		    jsonpCallback: 'ju_tab_config',
          cache: true,
  		    success: function(data) {
		        clearTimeout(ju_config_timeout);
		        ju_config.ju_campaigns.push(data);
  				  ju_loadiframe_con(options);
  		    }
  		});
  	} else {
  		ju_loadiframe_con(options);
  	}
  }

  function ju_loadiframe_con(options){
  	// get overlay settings

  	var allow_combine = false;
  	var show_dim = 'no';
  	var ju_title = '';
		var ju_options = {};
		var cmID = ju_show_campaign_id;

  	setwidthheight();

  	jju.each(ju_config.ju_campaigns,function(ci, citem) {
  		//console.log(cmID+' = '+ju_config.ju_campaigns[ci].cmid)
  	    if (cmID==ju_config.ju_campaigns[ci].cmid){
  	    	ju_title = ju_config.ju_campaigns[ci].title;
  	    	ju_options = ju_config.ju_campaigns[ci].options;
  	    	ju_config.ju_overlay_color= ju_config.ju_campaigns[ci].tab.design.overlay["background-color"];
  	    	ju_config.ju_overlay_image= ju_config.ju_campaigns[ci].tab.design.overlay["background-image"];
  	    	//console.log(ju_config.ju_overlay_color)
  	    	show_dim = ju_config.ju_campaigns[ci].tab.design.overlay.dim;
  	    	if (ju_config.ju_campaigns[ci].tab.design.overlay.hasOwnProperty("combine")){
  	    		allow_combine = (ju_config.ju_campaigns[ci].tab.design.overlay.combine!='1' ? '0' : '1');
  	    	}
					if (!jju(".ju_CSSJS_" + ju_config.ju_campaigns[ci].cmid).length){
						ju_add_js(ju_config.ju_campaigns[ci].tjs, ju_config.ju_campaigns[ci].cmid);
						ju_add_css(ju_config.ju_campaigns[ci].tcss, ju_config.ju_campaigns[ci].cmid);
  		    }
  			//jju('#ju_overlay').css('background-color',ju_config.ju_overlay_color);
  			return false;
  	    };
  	});

  	if (!jju("#ju_overlay").length){
  		jju('<div id="ju_overlay" class="ju_overlay" style="position:fixed;"></div>').appendTo( "body" );
			fixed_supported = jju( '#ju_overlay' ).css( 'position' ) === 'fixed';
  		//console.log(fixed_supported)
  		ju_setup_interval_stuff();
  	}

  	// create only if not created before
  	if (!jju("#ju_Con_"+cmID+".ju_Con").length){
      //console.log(options)
  		ju_createiframe(cmID,options.zindex,ju_title,ju_options);
  	}

  	if (options.loadwindow=='' && !options.preload){
  		ju_haveseen = true;
  	}

  	if (options.loadwindow=='' && show_dim != 'no'){
  		jju('#ju_overlay')
  			.off('click')
  			.data('cmid',cmID)
  			.css({'background-color':ju_config.ju_overlay_color,'background-image':(ju_config.ju_overlay_image!='' && ju_config.ju_overlay_image!==undefined ? 'url('+replaceJustuno(ju_config.ju_overlay_image)+')' : 'none'),'z-index':jju('#ju_Con_'+cmID).data('zindex')});
  	}

  	if (options.loadwindow=='' && options.campaign_id!='' && show_dim != 'no'){
  		ju_fadeinoverlay(cmID);
  	}

  	//var stringcouponids;
  	ju_show_coupon = false;

  	var ju_show_ex_id = 0

  	jju.each(juDs.extocm, function(entryIndex, entry) {
  		if (typeof this.cm !== 'undefined') {
  			if (this.cm==cmID) {
  				ju_show_ex_id = this.ex;
  			}
  		}
  	})

	  ju_iframe_url = ju_domain + "/ifm_" + ju_widget_v + ".html";

		var ju_ifm = {
			"ju_num":ju_active_ju_num,
			"p":(ju_loadcm > 0 ? 1 : 0),
			"d":fetchWindowHref().match(/:\/\/(.[^/]+)/)[1],
			"iframe":(options.campaign_id != '' && options.loadwindow != '' ? true : false),
			"preload":options.preload,
			"mobile":ju_mobile,
			"cmid":cmID,
			"eng":existArrayObj(juDs.offers_engaged,'ID',cmID),
      "ex":ju_show_ex_id,
      "host":window.ju_host,
      "cdn":window.asset_host,
			"customvar":ju_customvar
		}

    if (options.loadwindow!='' && options.campaign_id!=''){
  		if (!jju("#ju_iframe_"+cmID).length){
  			if (jju(options.loadwindow).length){
          jju(options.loadwindow).css('height',jju(options.loadwindow).height());
          jju(options.loadwindow).html('<iframe name="ju_iframe_'+cmID+'" data-ex="'+options.exid+'" title="'+encodeURI(ju_title)+'" class="ju_iframe ju_inpage" id="ju_iframe_'+cmID+'" tabindex="0" allowTransparency="true" scrolling="auto" frameborder="0" src="about:blank" data-hj-allow-iframe=""></iframe>');
    			jju("#ju_Con_"+cmID).data('ju_combine',allow_combine);
    			if (show_dim != 'no'){
            var thisBgCss = {'background-color':ju_config.ju_overlay_color,'background-image':(ju_config.ju_overlay_image!='' && ju_config.ju_overlay_image!==undefined ? 'url('+replaceJustuno(ju_config.ju_overlay_image)+')' : 'none')};
            if (ju_onboarding_display==0){
              var thisBgCss = {'background-color':'#fff'};
            }
    				jju(options.loadwindow)
    				.addClass('ju_inpage_back')
    				.data('cmid',cmID)
    				.css(thisBgCss);
    			}
					//document.getElementById("ju_iframe_"+cmID).src = ju_iframe_url;
					ju_safepost_p(ju_iframe_url, 'GET', 'application/x-www-form-urlencoded', ju_ifm, false).then(function(data){
						ju_writeIframe('#ju_iframe_'+cmID,data)
					});
        }
  		} else if (!jju(options.loadwindow).is(':visible')){
        // we need to show it again
        jju(options.loadwindow).slideDown('fast');
      }
  	} else {

			var need_to_fire_animation = true

  		if (!jju("#ju_iframe_"+cmID).length){
  			jju("#ju_Con_"+cmID+".ju_Con .ju_wrapper").html('<iframe name="ju_iframe_'+cmID+'" data-ex="'+options.exid+'" title="'+encodeURI(ju_title)+'" class="ju_iframe" id="ju_iframe_'+cmID+'" tabindex="0" allowTransparency="true" scrolling="no" frameborder="0" src="about:blank" style="width:'+ju_windowWidth+'px;" data-hj-allow-iframe=""></iframe>');
				jju("#ju_Con_"+cmID).data('ju_combine',allow_combine);

				ju_safepost_p(ju_iframe_url, 'GET', 'application/x-www-form-urlencoded', ju_ifm, false).then(function(data){
					ju_writeIframe('#ju_iframe_'+cmID,data)
				});
  			//document.getElementById("ju_iframe_"+cmID).src = ju_iframe_url;
  			need_to_fire_animation = false
      }

      if (options.focus) jju("#ju_Con_"+cmID).attr('data-focus','true');

  		if (!options.preload) {
				// //jju('#ju_Con_'+cmID).css({'left':'0px','top':'0px','height':'100%','width':'100%'});
						if (need_to_fire_animation) {
							// need to put a delay on this since the iframe is currently loading
							fire_animation(cmID);
						} else {
							// need to reproduce
							ju_fadein(cmID, false);
						}
  		}
    }

    // add dialog role to outer outer container
    jju("#ju_iframe_"+cmID).parent().attr('role','dialog');

  	if (!options.preload && (!jju('#ju_iframe_' + cmID).hasClass('ju_inpage') || ju_isInViewport(jju('#ju_iframe_' + cmID)))){
  		juDs.seen = 1;
  		juDa.seen = 1;
  		juDp.seen = 1;
            //console.log('iframe load')
			ju_logimpression(cmID,options.exid);
  		//write_data_cookies(false,300,false);
  	} else {
  		jju('#ju_Con_'+cmID).data('ju_combine','1');
  		jju('#ju_Con_'+cmID).data('ju_exit','1');
  	}
  }

  function ju_isInViewport(elem) {
    var $win = jju(window)
    var viewport_top = $win.scrollTop()
    var viewport_height = $win.height()
    var viewport_bottom = viewport_top + viewport_height
    var $elem = jju(elem)
    var top = $elem.offset().top
    var height = $elem.height()
    var bottom = top + height

    return $elem.is(':visible') && ((top >= viewport_top && top < viewport_bottom) ||
    (bottom > viewport_top && bottom <= viewport_bottom) ||
    (height > viewport_height && top <= viewport_top && bottom >= viewport_bottom));
  }

	function ju_writeIframe(el,data){
    var newdata = replaceJustuno(data);
		var x = jju(el)[0].contentWindow.document;
		x.open();
		x.write(newdata);
		x.close();
	}

  function fire_animation(cmid){
  	ju_fadein(cmid,false);

  	// ju_postMessage(
  	//   safeToJSON({'animate':true}),
  	//   ju_iframe_url,
  	//   document.getElementById("ju_iframe_"+cmid).contentWindow
    // );
    var thisConWin = document.getElementById("ju_iframe_"+cmid).contentWindow;
    if (typeof(thisConWin.jju_receiveMessage)==='function'){
      tryCatch(thisConWin.jju_receiveMessage({'animate':true}));
    }
  }

  function ju_add_css(css_content,cmid) {
		var head = document.getElementsByTagName('head')[0];
		var style = document.createElement('style');
		style.type = 'text/css';
		if (document.querySelector('script[nonce]') && document.querySelector('script[nonce]')?.nonce!="null" && document.querySelector('script[nonce]')?.nonce!="") style.nonce = document.querySelector('script[nonce]')?.nonce;
		style.className = "ju_CSSJS_" + cmid;

		if(style.styleSheet) {
			style.styleSheet.cssText = css_content;
		} else {
			style.appendChild(document.createTextNode(css_content));
		}
		head.appendChild(style);
  };

	var ju_push_pers = ju_debounce(function (cmid) {
		ju_options.arb = juDs.arb;
		if (!ju_options.hasOwnProperty("personalized")) {
			ju_options.personalized = {};
		}
		ju_options.personalized.session = jju.parseJSON(safeToJSON(juDs));
		ju_options.personalized.all = jju.parseJSON(safeToJSON(juDa));
		ju_options.personalized.session.cartquantity = juDs.cartTotals.tq;
		ju_options.personalized.session.carttotal = juDs.cartTotals.tp;
		ju_options.personalized.cartquantity = ju_options.personalized.session.cartquantity; // keep this for compatibility customers
		ju_options.personalized.carttotal = ju_options.personalized.session.carttotal; // keep this for compatibility customers
		try {
			if (juDa.cartTotals[juDa.cartTotals.length - 1].hasOwnProperty(ju_config.ju_sessionkey)) {
				var propertyMinus = 2;
			} else {
				var propertyMinus = 1;
			}
			var cartobj = juDa.cartTotals[juDa.cartTotals.length - propertyMinus][Object.keys(juDa.cartTotals[juDa.cartTotals.length - propertyMinus])[0]];
			var cartTp = cartobj.tp;
			var cartTq = cartobj.tq;
		} catch (er) {
			var cartTp = 0;
			var cartTq = 0;
		}
		ju_options.personalized.all.cartquantity = cartTq;
		ju_options.personalized.all.carttotal = cartTp;

		jju((cmid > 0 ? '#ju_iframe_' + cmid : '') + '.ju_iframe').each(function () {
			// ju_postMessage(
			// 	safeToJSON(ju_options),
			// 	jju(this).attr('src'),
			// 	document.getElementById(jju(this).attr('id')).contentWindow
      // );
      var thisConWin = document.getElementById(jju(this).attr('id')).contentWindow;
      if (typeof(thisConWin.jju_receiveMessage)==='function'){
        tryCatch(thisConWin.jju_receiveMessage(ju_options));
      }
		})
	}, 200, 'Both');

  function ju_add_js(functionBody,cmid) {
  	if (functionBody!==undefined && functionBody!=''){
  		var script = document.createElement("script");
			script.text = functionBody;
			script.className = "ju_CSSJS_" + cmid;
  		document.getElementsByTagName("body")[0].appendChild(script);
  	}
  }

	function existArrayObj(arr,key,comp){
		for (var i = 0, len = arr.length; i < len; i++) {
			if (Array.isArray(arr[i][key])) {
						if (jju.inArray(comp, arr[i][key]) > -1) return true; // Return as soon as the object is found
			} else {
				if (arr[i][key] == comp) return true; // Return as soon as the object is found
			}
				}
				return false
		}

	function tryCatch(t,c){
		try{
			t
		} catch(er){
			if (c){
				c
			}
		}
	}

  // check to make sure jquery isn't already loaded and load it if not

  function ju_jqLoaded() {

    if (ju_jqLoaded_once) return false;

    // we check for an error since some libraries mess with the default jquery twean that will cause an error.
    // jju.fn.fadeOut = function(duration,complete) {
    //   try{ jju(this).fadeOut(duration, complete); } catch(er){jju(this).hide();};
    //   return jju(this);
    // }

    jju.ajaxPrefilter(function(options, originalOptions){
      //console.log(options,originalOptions,options.data!=originalOptions.data)
      if ((options.url.indexOf('analytics.'+window.ju_host)!=-1 || options.url.indexOf('aly.'+window.ju_host)!=-1 || options.url.indexOf('account_config_')!=-1 || options.url.indexOf('ifm_')!=-1) && options.type.toLowerCase() =='post' ) {
        options.data = (originalOptions.processData ? jju.param(originalOptions.data) : originalOptions.data);
      }
    });

    ju_jqLoaded_once = true;
    jju.migrateMute = true;

		setwidthheight();

		// add some new expressions

		jju.extend(jju.expr[':'], {
			sMore: function(e, i, m) {
				var param = m[3];
				var elval = jju(e).text();
				if (elval==''){
					elval = jju(e).val();
				}
				if (isNaN(param)) {
					return elval.toLowerCase() >  param.toLowerCase();
				} else {
					return parseFloat(elval.replace(/[^\d.-]/g, '')) > parseFloat(m[3]);
				}
			},
			sLess: function(e, i, m) {
				var param = m[3];
				var elval = jju(e).text();
				if (elval==''){
					elval = jju(e).val();
				}
				if (isNaN(param)) {
					return elval.toLowerCase() <  param.toLowerCase();
				} else {
					return parseFloat(elval.replace(/[^\d.-]/g, '')) < parseFloat(m[3]);
				}
			},
			sContains: function(e, i, m) {
				var param = m[3];
				var elval = jju(e).text();
				if (elval==''){
					elval = jju(e).val();
				}
				return elval.toString().toLowerCase().indexOf(param.toString().toLowerCase()) >= 0;
			}
		});

		jju.fn.sendkeys = function (x){
			x = x.replace(/([^{])\n/g, '$1{enter}'); // turn line feeds into explicit break insertions, but not if escaped
			return this.each( function(){
				bililiteRange(this).bounds('selection').sendkeys(x).select();
				this.focus();
			});
		}; // sendkeys

		// add a default handler for keydowns so that we can send keystrokes, even though code-generated events
		// are untrusted (http://www.w3.org/TR/DOM-Level-3-Events/#trusted-events)
		// documentation of special event handlers is at http://learn.jquery.com/events/event-extensions/
		jju.event.special.keydown = jju.event.special.keydown || {};
		jju.event.special.keydown._default = function (evt){
			if (evt.isTrusted) return false;
			if (evt.ctrlKey || evt.altKey || evt.metaKey) return false; // only deal with printable characters. This may be a false assumption
			if (evt.key == null) return false; // nothing to print. Use the keymap plugin to set this
			var target = evt.target;
			if (target.isContentEditable || target.nodeName == 'INPUT' || target.nodeName == 'TEXTAREA') {
				// only insert into editable elements
				var key = evt.key;
				if (key.length > 1 && key.charAt(0) != '{') key = '{'+key+'}'; // sendkeys notation
				jju(target).sendkeys(key);
				return true;
			}
			return false;
		}

  	ju_getconfig();
	}

	window.jju_receivePostMessage = function(e){
		if (e.origin.indexOf(window.asset_host.slice(0, -1))!=-1){
      //console.log('e.data',e.data)
			if (e.data!='' && (e.data._ju_dt || e.data.userInfo || e.data.acow)) {
        var dat = e.data;
        if (dat._ju_dt && dat._ju_dt!='' && dat._ju_dt.indexOf('-')!=-1) _ju_dt = dat._ju_dt;
        if (dat.acow) ju_config.ju_acow = true;
        addJuIcon();
        if (dat.userInfo && dat.userInfo!='') {
          var uInfoArr = dat.userInfo.split('|');
          ju_config.s1 = uInfoArr[0];
          ju_config.s256 = uInfoArr[1];
          ju_config.m = uInfoArr[2];
        }
      }
			jju('#juStore').remove();
			ju_readyfetch();
			return;
		}
    if (e.origin.replace(ju_current_url_protocol,'') !== ju_current_domain && e.origin.indexOf('.p.'+window.ju_host)==-1) return;
		try {
			jju_receiveMessage(jju.parseJSON(e.data));
		} catch (e) {

		}
	}


  window.jju_receiveMessage = function(e) {

		//console.log(e)
    var dat = e;

    if (dat.push_window=='ready'){
      sendPushBody();
    }

    if (typeof (dat.push_accepted) === 'boolean'){
      console.log(dat)

      if (!dat.push_accepted){
        // they denied it
        jju_receiveMessage({
          'close':true,
          'promoid':ju_pushBody.promoId
        });
        juDs.notif.perm = 'denied';
        juDa.notif.perm = 'denied';
        write_data_cookies(false,100,false);
        return;
      }

      if (dat.rsw){ // chrome accepted
        ju_sendSubscriptionToBackEnd(dat.rsw);
      }
      if (dat.ssw){ // safari accepted

      }


      jju('#ju_iframe_'+ju_pushBody.promoId)[0].contentWindow.getpromocode('19','',ju_pushBody.cpID,1,1);
      juPushWindow.close();
      juDs.notif.perm = 'granted';
      juDa.notif.perm = 'granted';
      write_data_cookies(false,100,false);
    }

    if (dat.promoid){
      var inpage_parent = jju('#ju_iframe_' + dat.promoid + '.ju_inpage').closest('.ju_inpage_con');
    }

    if (jju("#ju_iframe_" + dat.offer_engaged).is(':visible') || jju("#ju_Con_" + dat.offer_engaged).is(':visible')) {
      if (dat.offer_engaged && dat.shared != 0 && dat.shared != 15 && dat.shared != 1000) {

        update_offers_engaged(juDs,dat.offer_engaged,dat.shared);
        update_offers_engaged(juDa,dat.offer_engaged,dat.shared);


        write_data_cookies(false, 10, false);
      }
      if (dat.couponcode) {
        window.lastCoupon = dat.couponcode;
        juapp('arb', 'code', dat.couponcode);
				juapp('arb', 'code_' + dat.offer_engaged, dat.couponcode);
				if (juDs.config.coupon_sel && (!window.Shopify || location.pathname.indexOf("/checkouts/") == -1)) quickapplycoupon(dat.couponcode);
				write_data_cookies(false, 100, false);
      }
      if (dat.shared && dat.shared != 15 && dat.shared != 0) {
        juDs.engaged = 1;
				juDa.engaged = 1;
				juDp.engaged = 1;

				var ju_engagetype = return_engagment_type(dat.shared);

				if (ju_config.ju_status == "1" && ju_show_button && ju_config.ju_custombutton != "" && dat.shared != 17 && dat.shared != 1000) {
          if (!jju('#ju_iframe_'+dat.offer_engaged)[0].contentWindow.$( "script:contains(recommend."+window.ju_host+")" ).length) jju("#ju_custom_close_btn").click();
				}

				if (dat.email && dat.email != '') {
					ju_save_hash(dat.email);
					juapp('arb', 'email', dat.email);
					// try to auto set email
					if (juDs.config.email_sel) ju_autosetemail();
				}

				if (dat.shared != 1000) {
					//console.log('engagement')
					write_data_cookies(false, 100, false);
        }

        // check if there is no impression and log some details if not.
        var offerSeen = false;
        jju.each(juDs.offers_seen, function(entryIndex, entry) {
          if (dat.offer_engaged.toString() == this.ID){
            offerSeen = true;
          }
        })
        if (!offerSeen && !window.ju_isPreview) {
          var pIDs = jju('.ju_iframe').map(function() { return this.id; }).get();
          var offerErr = {
            "cmid":dat.offer_engaged,
            "t":dat.shared,
            "inview":pIDs,
            "profile":juDs
          }
          ju_logerr('no impression',offerErr);
        }

				if (typeof (ju_callback) === 'function') {
					var sT_Shared = dat.shared;
					var sT_email = dat.email;
					var sT_couponcode = dat.couponcode || window.lastCoupon;
					var sT_couponexpire = dat.couponexpire;
					setTimeout(function () {
						ju_callback(sT_Shared, sT_email, sT_couponcode, sT_couponexpire);
					}, 1000);
				};

				if (ju_engagetype != '') {

					// get promo title
					ju_promo_title = decodeURI(jju("#ju_Con_" + dat.offer_engaged).data('title'));
					ju_promo_options = jju("#ju_Con_" + dat.offer_engaged).data('promo_options');
					if (dat.fromcookie.toString() != '1' && ju_engagetype != '') {
						ju_record_event(dat.email, 'Engagement - ' + ju_engagetype, ju_promo_title, dat.offer_engaged, {
							"promo_options": ju_promo_options,
							"promo_coupon": dat.couponcode || window.lastCoupon,
							"promo_expire": dat.couponexpire
						}, 2, dat.form);
					};
        }
      }
    }

	if (dat.showiframe) {
      var datpromo = dat.promoid;
      var juIfm = jju('#ju_iframe_' + datpromo);
      ju_push_pers(datpromo);
      var pushFocus = false;
      if (juIfm.css('opacity')==0) pushFocus = true;
	  if (jju('[id^=_jst-iframe]').length) pushFocus = false;
      setTimeout(function(){
				juIfm.css({'opacity':1,'display':'block'});
				if (!juIfm.hasClass('ju_inpage')){
					juIfm.closest('.ju_Con').css({'overflow':'auto'});
					juIfm.closest('.ju_wrapper').css({'min-height':juIfm[0].contentWindow.jju('.design-layer[data-layertype="frame"]').height()+10});
				}
				if (pushFocus && !juIfm.hasClass('ju_inpage') && (jju('#ju_Con_' + datpromo).data('position')==4 || jju('#ju_Con_' + datpromo).is('[data-focus]'))) {
					var juFocusIfm = juIfm[0];
					juFocusIfm.contentWindow.focus();
					function juKeyboardHandler(e) {
						if (e.keyCode === 9) {
						if (parent.document.activeElement !== juFocusIfm && jju(juFocusIfm).is(":visible")) {
							e.preventDefault();
							juFocusIfm.focus();
							juFocusIfm.contentWindow.setLowestFocusableItem();
							juFocusIfm.contentWindow.$('[tabindex="'+juFocusIfm.contentWindow.lowestIndex+'"]:visible:first').focus();
						}
						}
					};
					document.addEventListener('keydown', juKeyboardHandler);
					}
				},100)
		}

		if (dat.optout) {
			ju_removeProfile();
		}

		if (dat.changecon) {
			if (inpage_parent.length) {

				if (!window["inPageResize"+dat.promoid]){
					window["inPageResize"+dat.promoid] = ju_debounce(function (inpage_parent,c_h,promoid) {
						inpage_parent.animate({
							'height': c_h + 'px'
						}, 'fast', function () {
							fire_animation(promoid);
							//ju_fadein(dat.promoid,true)
						});
					}, 200, 'Start');
				}

				// this portion might loop if we are not carful about it
				if (dat.c_h - inpage_parent.height() > 2) {
					window["inPageResize"+dat.promoid](inpage_parent,dat.c_h,dat.promoid)
				}
			}

			//if (!touchPresent || !ju_stoptop) {
				jju('#ju_Con_' + dat.promoid).attr('data-position', dat.overlayposition).data('position', dat.overlayposition);
				jju('#ju_Con_' + dat.promoid).css({
					'left': (dat.overlayposition == 4 ? 0 : dat.c_x),
					'top': (dat.overlayposition == 4 ? 0 : dat.c_y),
					'height': (dat.overlayposition == 4 ? '100%' : dat.c_h),
					'width': (dat.overlayposition == 9 || dat.overlayposition == 10 || dat.overlayposition == 4 ? '100%' : dat.c_w)
				});
			//}
			jju('#ju_Con_' + dat.promoid + ' #ju_iframe_' + dat.promoid).css({
				'width': jju('#ju_Con_' + dat.promoid).width()
			});
		}

		if (dat.pushdown) {

			pushdown_distance = dat.distance;
			fixed_push_type = dat.pushdown;

			jju('body').data('ju_pushcmid', dat.promoid);

			pushdown_stuff();
			clearInterval(fixed_push_interval);
			fixed_push_interval = setInterval(function () {
				pushdown_stuff();
			}, 1000);

		}

		if (dat.fadeinoverlay) {
			ju_fadeinoverlay(dat.promoid);
		}

		if (dat.close) {
			//ju_loadiframe();
			if (inpage_parent.length) {
				inpage_parent.slideUp('fast');
			}
			ju_fadeout(dat.promoid);
			ju_fadeoutoverlay(dat.promoid);
			var promoid = dat.promoid;

			update_offers_closed(juDa,promoid);
			update_offers_closed(juDs,promoid);

			//console.log('close')
			// try to auto apply coupon
			ju_autoapplycoupon();

			write_data_cookies(false, 10, false);

		}

		if (dat.openpromo) {
			//ju_loadiframe();
			if (!dat.keepopen) {
				ju_fadeout(dat.promoid);
				ju_fadeoutoverlay(dat.promoid);
			}
			ju_loadiframe({
				'campaign_id': dat.openpromo
			});
		}
		if (typeof(dat.stoptop)!=='undefined' && ju_stoptop != dat.stoptop) {
      ju_stoptop = dat.stoptop;
      if (ju_stoptop) {
        ju_config.scrollTopCheck = jju(window).scrollTop();
      }
			setTimeout(ju_switchfixedabsolute,1000);
		}

		if (dat.resize) {
			jju('.ju_Con').css('min-height', (dat.resize).toString() + 'px');
		}

		if (dat.juCustom) {
			if (typeof (juIframeCatch) !== 'undefined' && typeof (juIframeCatch) === 'function') {
				juIframeCatch(dat);
			};
		}

	};

	function update_offers_closed(obj,promoid){
		var promoid_exists = false;
		jju.each(obj.closed, function (entryIndex, entry) {
			if (this.ID == promoid) {
				promoid_exists = true;
				this.dt = ju_todayDate();
			}
		})
		if (!promoid_exists) {
			obj.closed[obj.closed.length] = {
				"ID": promoid,
				"dt": ju_todayDate()
			};
		}
	}

	function update_offers_seen(obj,promoid){
		var ju_offer_seen = false;
		jju.each(obj.offers_seen, function (entryIndex, entry) {
			if (typeof this.ID !== 'undefined') {
				if (this.ID == promoid) {
					ju_offer_seen = true;
					this.dt = ju_todayDate();
					this.tm = (new Date()).getTime();
					this.ps = jju('#ju_Con_' + promoid).data('position');
					this.ct = this.ct + 1 || 1;
					this.se = obj.visits;
				}
			}
		})
		if (!ju_offer_seen) {
			obj.offers_seen[obj.offers_seen.length] = {
				"ID": promoid,
				"dt": ju_todayDate(),
				"tm": (new Date()).getTime(),
				"ps": jju('#ju_Con_' + promoid).data('position'),
				"ct": 1,
				"se": obj.visits
			};
		}
  }

	function update_offers_engaged(obj,promoid,sharetype){
		var ju_offer_engaged = false;
		jju.each(obj.offers_engaged, function (entryIndex, entry) {
			if (typeof this.ID !== 'undefined') {
				if (this.ID == promoid) {
					ju_offer_engaged = true;
					this.dt = ju_todayDate();
					this.tm = (new Date()).getTime();
					this.ps = jju('#ju_Con_' + promoid).data('position');
					this.ct = this.ct + 1 || 1;
					this.se = obj.visits;
					this.ty = ju_arr_upsert(this.ty, sharetype);
				}
			}
		})
		if (!ju_offer_engaged) {
			obj.offers_engaged[obj.offers_engaged.length] = {
				"ID": promoid,
				"dt": ju_todayDate(),
				"tm": (new Date()).getTime(),
				"ps": jju('#ju_Con_' + promoid).data('position'),
				"ct": 1,
				"se": obj.visits,
				"ty": [sharetype]
			};
		}
	}

	window.addEventListener("message", jju_receivePostMessage, false);


  function ju_switchfixedabsolute(){
    if (touchPresent && ju_windowWidth<800){
      //console.log(ju_stoptop)
      if (ju_stoptop){
        //if (ju_config.scrollTopCheck==jju(window).scrollTop()){
          //jju(document.activeElement).closest('.ju_Con').each(function(){
            //try{
              var thiscon = jju(document.activeElement).closest('.ju_Con');
              var focusedDivTop = thiscon.offset().top - jju(window).scrollTop();
						//	console.log(focusedDivTop)
              var iframeContent = document.getElementById(thiscon.find('.ju_iframe').attr('id')).contentWindow;
              var focusedInputTop = iframeContent.jju(':focus').offset().top;
							console.log(focusedInputTop)
              //if (jju(thiscon).data("position")=="10"){
              //  jju(thiscon).css({'top':'auto','bottom':'0px','height':iframeContent.jju('.design-layer[data-layertype="frame"]').height()});
              //} else {
                //var offset = focusedInputTop+90;
                thiscon.hide();
								if (thiscon.data("position")=="4" || thiscon.data("position")=="6" || thiscon.data("position")=="7" || thiscon.data("position")=="8" || thiscon.data("position")=="10"){
									thiscon.css({'overflow':'auto','top':'auto','bottom':'0px'});
									thiscon.find('.ju_wrapper').css({'min-height':iframeContent.jju('.design-layer[data-layertype="frame"]').height()+(thiscon.data("position")=="10" ? 10 : 200)});
								}
								//jju(thiscon).css({'position':'absolute','height':(jju(thiscon).data("position")=="4" ? ju_windowHeight : iframeContent.jju('.design-layer[data-layertype="frame"]').height()+50)});
                thiscon.show();
								//thiscon.scrollTop(function() { console.log(this.clientHeight);return (this.scrollHeight-this.clientHeight)/2; });
								console.log(offset,focusedDivTop)
                jju(thiscon).stop().animate({'top':-focusedDivTop-focusedInputTop+20}, 200)
              //}
            //} catch (er){}
          //});
        //}
      } else {
        jju('.ju_Con').stop().css({'position':'fixed'});
				//jju('.ju_Con .ju_wrapper').css({'height':'100%'});
				pstmsgresize(0, true, false);
      }
    }
	}

	function quickapplycoupon(couponCode){
    try {
      if (couponCode && window.BCData) {
        ju_safepost_p('/remote/v1/apply-code','POST','application/x-www-form-urlencoded',{code:couponCode},false,{ 'x-xsrf-token': window.BCData&&window.BCData.csrf_token?window.BCData.csrf_token:"" }).then(
          function(resp){
            if (resp && resp.data && resp.data.status === "success") {
              juapp('arb','lastappliedcode',couponCode);
              console.log('coupon applied')
            } else if (resp && resp.data && resp.data.status === "failed") {
              console.log(resp.data.errors[0])
            }
          }
				)
				["catch"](function (err) {
					//console.error('Error Happened:', err)
				});
      }
      if (couponCode && window.Shopify) {
        jju.get('/discount/' + couponCode + '?redirect=/');
				juapp('arb','lastappliedcode',couponCode);
      }
    } catch (ex) {}
  }

  function replaceJustuno(data){
    var newdata = data;
    newdata = newdata.replace(/https:\/\/cdn\.justuno\.com\//g, window.asset_host);
    newdata = newdata.replace(/https:\/\/graphics\.justuno\.com/g, 'https://graphics.'+window.ju_host);
    newdata = newdata.replace(/https:\/\/assets\.justuno\.com/g, 'https://assets.'+window.ju_host);
    newdata = newdata.replace(/https:\/\/client\.justuno\.com/g, 'https://client.'+window.ju_host);
	if (document.querySelector('script[nonce]') && document.querySelector('script[nonce]')?.nonce!="null" && document.querySelector('script[nonce]')?.nonce!=""){
		newdata = newdata.replace(/<script/gi, "<script nonce='"+document.querySelector('script[nonce]')?.nonce+"'");
		newdata = newdata.replace(/<style/gi, "<style nonce='"+document.querySelector('script[nonce]')?.nonce+"'");
	}
    return newdata;
  }

	function juDebug(){
		if (ju_current_url.indexOf('#debug')!=-1){
			console.log(arguments);
		}
	}

  function pushdown_stuff(){
    if (!jju('.ju_Con:visible').length) return false;
    if( !jju('body').is("[ju_orig_marg]") || parseFloat(jju('body').css('margin-top').replace('px',''))<pushdown_distance ){
			var origtopmargin = jju('body').css('margin-top').replace('px','');
			jju('body').css({'-webkit-overflow-scrolling':'initial'});
      jju('body').attr('ju_orig_marg',origtopmargin);
      jju('body').animate({
        marginTop: parseInt(origtopmargin)+pushdown_distance
      },{duration:(fixed_push_type=='slide' ? 500 : 100),queue:false});
    }

  	jju('.ju_forcepush, body > *:not(.ju_Con):not(#ju_bbox):not(.ju_stoppush):not([class*="bx-"]), body > * > *:not(.ju_Con):not(#ju_bbox):not(.ju_stoppush):not([class*="bx-"]), body > * > * > *:not(.ju_Con):not(#ju_bbox):not(.ju_stoppush):not([class*="bx-"]), body > * > * > * > *:not(.ju_Con):not(#ju_bbox):not(.ju_stoppush):not([class*="bx-"]), body > * > * > * > * > *:not(.ju_Con):not(#ju_bbox):not(.ju_stoppush):not([class*="bx-"]), body > * > * > * > * > * > *:not(.ju_Con):not(#ju_bbox):not(.ju_stoppush):not([class*="bx-"]), body > * > * > * > * > * > * > *:not(.ju_Con):not(#ju_bbox):not(.ju_stoppush):not([class*="bx-"]), body > * > * > * > * > * > * > * > *:not(.ju_Con):not(#ju_bbox):not(.ju_stoppush):not([class*="bx-"])').filter(function() {
  				    return (jju(this).css("position") === 'fixed' || jju(this).css("position") === 'sticky' || jju(this).hasClass('ju_forcepush')) && !jju(this).is("[ju_orig_top]");
  					}).each(function(){
                      var blockList = [
                        "tidio"
                      ];
                      for (var i = 0, len = blockList.length; i < len; i++) {
                        if (jju(this).attr('id') && jju(this).attr('id').toLowerCase().indexOf(blockList[i]) !== -1) {
                          return;
                        }
                      }
											var orig_top = jju(this).css('top').replace('px','');
											var orig_bot = jju(this).css('bottom').replace('px','');
											if (!isNaN(orig_top) && orig_top!='' && !isNaN(orig_bot) && orig_bot!=''){
												// this is a fix for ff calculating auto into a number
												orig_bot = parseFloat(orig_bot);
												orig_top = parseFloat(orig_top);
                        //console.log(jju(this).attr('class'),orig_bot,orig_top)
												if (orig_bot>orig_top){
													orig_bot = 'auto';
												}else if ((orig_bot<100 && orig_top<100) && (orig_bot>0 || orig_top>0)){
													orig_bot = 'auto';
												}else if (orig_bot<orig_top){
													orig_top = 'auto';
												}
											}
											if ((!isNaN(orig_top) && orig_top.toString()!='' && (isNaN(orig_bot) || orig_bot.toString()=='')) || jju(this).hasClass('ju_forcepush')){
												orig_top = parseInt(orig_top);
												if ((isNaN(orig_top) && orig_top>-10) || jju(this).hasClass('ju_alternativepush')){
                          orig_top = jju(this).css('margin-top').replace('px','');
                          jju(this).animate({
                            marginTop: parseInt(orig_top)+pushdown_distance
                          },{duration:(fixed_push_type=='slide' ? 500 : 100),queue:false});
                        } else {
                          jju(this).animate({
                            top: orig_top+pushdown_distance
                          },{duration:(fixed_push_type=='slide' ? 500 : 100),queue:false});
                        }
                        jju(this).attr('ju_orig_top',orig_top);
											}
  									});
  	jju('*[ju_orig_top]:not(.ju_Con):not(#ju_bbox):not(.ju_stoppush):not([class*="bx-"])').filter(function() {
  				    return (jju(this).css("position") === 'relative' || jju(this).css("position") === 'absolute') && !jju(this).hasClass('ju_alternativepush') && !jju(this).hasClass('ju_forcepush');
  					}).each(function(){
              orig_top = jju(this).css('top').replace('px','');
              if (!isNaN(orig_top)){
                jju(this).animate({
                  top: jju(this).attr('ju_orig_top')
                },{duration:300,queue:false});
              }
							jju(this).removeAttr('ju_orig_top');
						});
	}

	function ju_arr_upsert(arr,v){
		var tempArr = [];
		if (Array.isArray(arr)) {
			tempArr = arr;
			if (jju.inArray(v, tempArr) < 0) {
				tempArr.push(v);
			}
		} else {
			tempArr.push(v);
		}
		return tempArr;
  }

  function return_engagment_type(type){
  	switch(type)
  	{
  	case "1":
  		return 'Facebook';
  	  break;
  	case "2":
  		return 'Google Plus';
  	  break;
  	case "3":
  		return 'Twitter TWeet';
  	  break;
  	case "4":
  		return 'Email Signup';
  	  break;
  	case "5":
  		return 'LinkedIn Share';
  	  break;
  	case "6":
  		return 'Twitter Follow';
  	  break;
  	case "7":
  		return 'Pinterest Follow';
  	  break;
  	case "8":
  		return 'Instagram Follow';
  	  break;
  	case "9":
  		return 'Videos Watched';
  	  break;
  	case "10":
  		return 'Incentivized Form';
  	  break;
  	case "11":
  		return 'VK Follow';
  	  break;
  	case "12":
  		return 'Reddit Subscribe';
  	  break;
  	case "13":
  		return 'Google Follow';
  	  break;
  	case "14":
  		return 'LinkedIn Follow';
  	  break;
  	case "15":
  		return 'Intro Continue Click';
  	  break;
  	case "16":
  		return 'Unlocked or CTA Click';
  	  break;
  	case "17":
  		return 'Unlocked or CTA View';
  	  break;
  	case "18":
  		return 'Plugin';
      break;
    case "19":
  		return 'Push Notification Subscribe';
      break;
    case "20":
  		return 'Facebook Messenger Opt-in';
      break;
    case "21":
  		return 'Item Added To Cart';
      break;
    case "22":
      return 'Product Click-Through';
      break;
    case "23":
      return 'SMS Text Message';
      break;
  	default:
      return '';
      break;
  	};
  }

  function ju_check() {
  	return window.jQuery && jQuery.fn && jQuery.fn.jquery.indexOf('-ajax')==-1 && /^1\.[7-9]|^1\.1[0-9]|^2\.[0-9]|^3\.[0-9]/.test(jQuery.fn.jquery);
  }

  function jju_setCookie( name, value, days, path, domain, secure ){
  	// set time, it's in milliseconds
  	var today = new Date();
  	today.setTime(today.getTime()+(days*24*60*60*1000));

  	document.cookie = name + "=" +escape( value ) +
  	";expires=" + (days==-1 ? 'Thu, 01 Jan 1970 00:00:01 GMT' : today.toGMTString()) +
  	( ( path ) ? ";path=" + path : "" ) +
  	( ( domain ) ? ";domain=" + domain : "" ) +
  	( ( secure ) ? ";secure" : "" );
  }

  function jju_getCookie(c_name){
  	var i,x,y,ARRcookies=document.cookie.split(";");
  	for (i=0;i<ARRcookies.length;i++)
  	{
  	  x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
  	  y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
  	  x=x.replace(/^\s+|\s+$/g,"");
  	  if (x==c_name) {
  		return unescape(y);
  	  }
  	}
  	return '';
  }

  function jju_getDomain() {
  	var i,h,
      weird_cookie='_ju_dm=cookie',
      hostname = document.location.hostname.split('.');
      h = hostname.slice(hostname.length-1).join('.');
    for(i=hostname.length-2; i>=0; i--) {
      h = hostname.slice(i).join('.');
      ju_Cookie.setCookies("_ju_dm", 'cookie', 1, '/', '.' + h);
      if(document.cookie.indexOf(weird_cookie)>-1){
        return h;
      }
    }
  }

  function ju_save_hash(email){
		if (email != '' && email !== undefined){
  		var hemail = email.toLowerCase().trim();
  		var hmd5 = ju_md5(hemail);
  		var hsha1 = ju_sha1(hemail);
  		var hsha256 = ju_sha256(hemail);
  		juDa.hashes={"m":hmd5,"s1":hsha1,"s256":hsha256};
      juDs.hashes={"m":hmd5,"s1":hsha1,"s256":hsha256};
      // disabling the below automatic cross device recognition based on emails
			// if (!ju_options.userid || ju_options.userid==''){
			// 	ju_Cookie.setCookies("_ju_ui", hsha256, .0208, '/', '.' + ju_config.root);
			// }
  		//console.log('save hash')
      write_data_cookies(false,50,false);
      ju_renderStore({id:_ju_dt,sha1:hsha1,sha256:hsha256,md5:hmd5});
  		setTimeout(ju_call_a, 3000);
  	};
  }

  function ju_a(){
    //console.log('ju_a')
      juDa.hashes = juDa.hashes || {m:"",s1:"",s256:"",pc:0};
      if ((juDa.hashes.m===undefined || juDa.hashes.m=='') && ju_config.m){
        juDa.hashes = {m:ju_config.m,s1:ju_config.s1,s256:ju_config.s256};
      }
    	if (juDa.hashes.m!==undefined && juDa.hashes.m!='' && juDs.hashes.pc!=-1){
				setTimeout(ju_call_a, 0);
				//console.log('ju_call_a')
    	} else if (juDa.hashes.m===undefined || juDa.hashes.m==''){
				//console.log('.on')
    		jju('input').on('change.juEv blur.juEv', function () {
					//console.log('catch blur')
    			var emailReg = /^([\w-\.\+]+@[\w-\.\+]+\.+[\w-]{2,10})?$/;
    			var emailaddressVal = jju.trim(jju(this).val());
    			if(emailaddressVal!=''){
    				if(emailReg.test(emailaddressVal)) {
    				  ju_save_hash(jju(this).val());
    				  jju('input').off( ".juEv" );
    				};
    			};
    		});
        try{
          if(typeof Shopify.checkout.email != "undefined"){
            ju_save_hash(Shopify.checkout.email);
            jju('input').off( ".juEv" );
          }
        }catch(er){}
    	};
      // if ((juDs.pagecount==1 && ju_config.ju_plan==1) || (juDs.pagecount==2 && ju_config.ju_plan>1)){
      //   setTimeout(ju_call_o, 0);
      // };
  };

  function ju_call_a(){
    if (juDa.hashes.m!==undefined && juDa.hashes.m!='' && juDs.hashes.pc!=-1){
      juDs.hashes.pc = -1;
      write_data_cookies(false,300,false);
      //var lr = 0;
			if (!ju_config.ju_acow && ju_config.ju_a && ((1==2 && ju_config.ju_country == 'US' && ju_config.ju_region != 'CA' && ju_config.ju_region != 'Unknown') || ju_config.ju_country == 'AU') && navigator.doNotTrack != 1) {
        //var lr = 1;
        //jju.getScript('https://pippio.com/api/sync?pid=1807&it=4&iv='+juDa.hashes.m+'&it=4&iv='+juDa.hashes.s1+'&it=4&iv='+juDa.hashes.s256);
      }
      // var lrobj = {
      //   ip:ju_config.ju_ip,
      //   ct:ju_config.ju_country,
      //   rg:ju_config.ju_region,
      //   zp:ju_config.ju_zip,
      //   guid:ju_active_ju_num,
      //   lr:lr
      // }
      // ju_safepost_p('https://my.justuno.com/ajax/lr.html', 'GET', 'application/x-www-form-urlencoded', lrobj, false).then(function(data){
      // });
    };
  }

  function ju_autosetemail(){
    if (!juDs.hasOwnProperty("arb")) return;
    if (!juDs.arb.hasOwnProperty("email")) return;
    var email_selector = juDs.config.email_sel.v;
    if (!jju(email_selector).length || juDs.arb.email.v=='') return;
    if (jju(email_selector).val()!='') return;
    jju(email_selector).val(juDs.arb.email.v);
    jju(email_selector).trigger("change");
  }

  function ju_autoapplycoupon(){
    if (typeof(juDs.config.coupon_sel) !== 'object' || !juDs.hasOwnProperty("arb") || !juDs.arb.hasOwnProperty("code") || juDs.arb.code.v=='') return;
    if (juDs.arb.hasOwnProperty("lastappliedcode") && juDs.arb.code.v==juDs.arb.lastappliedcode.v) {
      if (!window.Shopify) quickapplycoupon(juDs.arb.lastappliedcode.v);
      return;
    } else {
      if (!window.Shopify || location.pathname.indexOf("/checkouts/") == -1) {
        quickapplycoupon(juDs.arb.code.v);
      }
    }
    var coupon_selector = juDs.config.coupon_sel.v;
    var coupon_btn_selector = juDs.config.coupon_btn_sel.v;
    if (!jju(coupon_selector).length) return;
    jju(coupon_selector).val('');
		try{
		jju(coupon_selector).sendkeys(juDs.arb.code.v); //  we use this jquery function because some libraries don't acknowledge change,keypress,keyup,keydown...
		} catch(er){}
    jju(coupon_selector).val(juDs.arb.code.v); // we still do this incase the above fails
    jju(coupon_selector).trigger("change");
    var couponfieldtop = jju(coupon_selector).offset().top;
    window.ju_lastsaved_compare = ju_plastsaved;
    juapp('arb','lastappliedcode',juDs.arb.code.v);
    window.ju_writecheck = setInterval(function(){
      //console.log("justuno save completed",ju_plastsaved>ju_lastsaved_compare)
      if (ju_plastsaved>ju_lastsaved_compare){
        clearInterval(ju_writecheck);
        if (jju(coupon_btn_selector).length){
          jju(coupon_btn_selector).first().removeClass('btn--disabled').prop('disabled',false).trigger("click");
        } else {
          jju(coupon_selector).closest('form').find('input').filter(function() {
            var thistype = jju(this).attr('type').toLowerCase();
            return (thistype.indexOf('button') > -1 || thistype.indexOf('submit') > -1 || thistype.indexOf('image') > -1) && (Math.abs(jju(this).offset().top - couponfieldtop) < 40);
          }).removeClass('btn--disabled').prop('disabled',false).trigger("click")
        }
      }
    }, 100);
  }

  //TAB POSITIONING ============================================D
  function tabPosition(){

  	//console.log("call tabPosition");
  	var top50 = window.innerHeight || document.documentElement.clientHeight;
  	top50 = top50/2;
  	juHeight = jju('.ju_preview_3').height();
  	juWidth = jju('.ju_preview_3').width();
  	var padding = parseInt(jju('.ju_preview_3').css('padding-top'));
  	var totalpadding = parseInt(jju('.ju_preview_3').css('padding-top'))+parseInt(jju('.ju_preview_3').css('padding-bottom'));
  	juBorder = parseInt(jju('.ju_preview_3').css('borderRightWidth'));
  	if (isNaN(juBorder)) {juBorder = 0}
  	var previewTab = jju('.ju_preview_3');
  	var openbtn = jju('#ju_custom_open_btn');
  	var closebtn = jju('#ju_custom_close_btn');
  	var TabOffset = !isNaN(ju_config.ju_offset) && ju_config.ju_offset!='' ? parseInt(ju_config.ju_offset) : 0;

  //Location to Alignment
  	//right-left
  	if ((previewTab.hasClass('ju-tab-location-0') || previewTab.hasClass('ju-tab-location-1')) && !ju_svgmode) {
  		previewTab.addClass('vertical-tab');
  		//Set position Right
      previewTab.css({"transform":"rotate(270deg)"+((ju_config.ju_cmid_version<3.52 && ju_mobile_scale) ? " scale(.5, .5)" : ""),"-ms-transform":"rotate(270deg)"+((ju_config.ju_cmid_version<3.52 && ju_mobile_scale) ? " scale(.5, .5)" : ""),"-moz-transform":"rotate(270deg)"+((ju_config.ju_cmid_version<3.52 && ju_mobile_scale) ? " scale(.5, .5)" : ""),"-webkit-transform":"rotate(270deg)"+((ju_config.ju_cmid_version<3.52 && ju_mobile_scale) ? " scale(.5, .5)" : ""),"-o-transform":"rotate(270deg)"+((ju_config.ju_cmid_version<3.52 && ju_mobile_scale) ? " scale(.5, .5)" : ""),"-webkit-transform-origin":"top left","-moz-transform-origin":"top left","-o-transform-origin":"top left","-ms-transform-origin":"top left","transform-origin":"top left"});
  	}

  //Location Right
  	if( jju('.ju_preview_3.ju-tab-location-0.ju-tab-alignment-0').length && !ju_svgmode ) {
  		var positionTop = 0 + juWidth + padding*2 + juBorder*2 - ((ju_config.ju_cmid_version<3.52 && ju_mobile_scale) ? ((juWidth/2 + padding + juBorder)) : 0);
  		var positionRight = 0 - juWidth + juHeight - juBorder-((ju_config.ju_cmid_version<3.52 && ju_mobile_scale) ? ((juHeight+totalpadding+juBorder)/2)+1 : 0);
  		juStartingPosition = positionRight-juHeight-padding*2-juBorder-20
			juFinalPosition = positionRight;
  		previewTab.css({
  			'top' : positionTop+TabOffset,
  			'right' : juStartingPosition
  		});
  	}

  	if( jju('.ju_preview_3.ju-tab-location-0.ju-tab-alignment-0').length && ju_svgmode ) {
  		var positionTop = 0;
  		var positionRight = 0;
  		juStartingPosition = positionRight-juWidth-juBorder-20
  		juFinalPosition = positionRight;
  		previewTab.css({
  			'top' : positionTop+TabOffset,
  			'right' : juStartingPosition
  		});
  		closebtn.css({
  			'right' : 0,
  			'bottom' : 0 - 26
  		});
  		openbtn.css({
  			'right' : -25,
  			'top' : positionTop+TabOffset+(juWidth/2)
  		});
  	}

  	if( jju('.ju_preview_3.ju-tab-location-0.ju-tab-alignment-1').length && !ju_svgmode ) {
  		var positionTop = top50 + juWidth/2 + padding + juBorder - ((ju_config.ju_cmid_version<3.52 && ju_mobile_scale) ? ((juWidth/2 + padding + juBorder)/2) : 0);
  		var positionRight = 0 - juWidth + juHeight - juBorder-((ju_config.ju_cmid_version<3.52 && ju_mobile_scale) ? ((juHeight+totalpadding+juBorder)/2)+1 : 0);
  		juStartingPosition = positionRight-juHeight-padding*2-juBorder-20
			juFinalPosition = positionRight
  		previewTab.css({
  			'top' : positionTop+TabOffset,
  			'right' : juStartingPosition
  		});
  	}

  	if( jju('.ju_preview_3.ju-tab-location-0.ju-tab-alignment-1').length && ju_svgmode ) {
  		var positionTop = top50 - juHeight/2 + ((ju_config.ju_cmid_version<3.52 && ju_mobile_scale && ju_config.ju_custombutton!="") ? juHeight/3 : 0);
  		var positionRight = 0;
  		juStartingPosition = positionRight-juWidth-juBorder-20
  		juFinalPosition = positionRight;
  		previewTab.css({
  			'top' : positionTop+TabOffset,
  			'right' : juStartingPosition
  		});
  		closebtn.css({
  			'right' : 0,
  			'top' : 0 - 26
  		});
  		openbtn.css({
  			'right' : -25,
  			'top' : positionTop+TabOffset+(juWidth/2)
  		});
  	}

		if (jju('.ju_preview_3.ju-tab-location-0.ju-tab-alignment-2, .ju_preview_3.ju-tab-location-0.ju-tab-alignment-3').length && !ju_svgmode ) {
      previewTab.css({
      	"transform": "rotate(270deg)" + ((ju_config.ju_cmid_version < 3.52 && ju_mobile_scale) ? " scale(.5, .5)" : ""),
      	"-ms-transform": "rotate(270deg)" + ((ju_config.ju_cmid_version < 3.52 && ju_mobile_scale) ? " scale(.5, .5)" : ""),
      	"-moz-transform": "rotate(270deg)" + ((ju_config.ju_cmid_version < 3.52 && ju_mobile_scale) ? " scale(.5, .5)" : ""),
      	"-webkit-transform": "rotate(270deg)" + ((ju_config.ju_cmid_version < 3.52 && ju_mobile_scale) ? " scale(.5, .5)" : ""),
      	"-o-transform": "rotate(270deg)" + ((ju_config.ju_cmid_version < 3.52 && ju_mobile_scale) ? " scale(.5, .5)" : ""),
      	"-webkit-transform-origin": "top left",
      	"-moz-transform-origin": "top left",
      	"-o-transform-origin": "top left",
      	"-ms-transform-origin": "top left",
      	"transform-origin": "top left"
      });
    }

  	if( jju('.ju_preview_3.ju-tab-location-0.ju-tab-alignment-2').length && !ju_svgmode ) {
  		var positionTop = jju_getju_windowHeight() - 1;
  		var positionRight = 0 - juWidth + juHeight - juBorder-((ju_config.ju_cmid_version<3.52 && ju_mobile_scale) ? ((juHeight+totalpadding+juBorder)/2)+1 : 0);
  		juStartingPosition = positionRight - juHeight - padding * 2 - juBorder - 20
			juFinalPosition = positionRight;
  		previewTab.css({
  			'top' : positionTop-TabOffset,
  			'right' : juStartingPosition
  		});
    }

  	if( jju('.ju_preview_3.ju-tab-location-0.ju-tab-alignment-2').length && ju_svgmode ) {
  		var positionRight = 0;
  		juStartingPosition = positionRight-juWidth-juBorder-20
  		juFinalPosition = positionRight;
  		previewTab.css({
  			'right' : juStartingPosition,
  			'bottom' : 0+TabOffset
  		});
  		closebtn.css({
  			'right' : 0,
  			'top' : 0 - 26
  		});
  		openbtn.css({
  			'right' : -25,
  			'bottom' : 0+TabOffset+(juWidth/2)
  		});
  	}

  	if( jju('.ju_preview_3.ju-tab-location-0.ju-tab-alignment-3').length && !ju_svgmode ) {
  		var positionTop = jju_getju_windowHeight()-1;
  		var fullWidth = (jju_getju_windowHeight() - juBorder*2 - padding*2)*((ju_config.ju_cmid_version<3.52 && ju_mobile_scale) ? 2 : 1)-2;
  		var positionRight = 0 - fullWidth + juHeight - juBorder-((ju_config.ju_cmid_version<3.52 && ju_mobile_scale) ? ((juHeight+totalpadding+juBorder)/2)+1 : 0);
  		juStartingPosition = positionRight-juHeight-padding*2-juBorder-20
  		juFinalPosition = positionRight;
  		previewTab.css({
  			'top' : positionTop,
  			'right' : juStartingPosition,
  			'width': fullWidth
  		});

  	}

  	if( jju('.ju_preview_3.ju-tab-location-0.ju-tab-alignment-3').length && ju_svgmode ) {
  		var fullWidth = jju_getju_windowHeight() - juBorder*2 - padding*2;
  		var positionRight = 0;
  		juStartingPosition = positionRight-juWidth-juBorder-20
  		juFinalPosition = positionRight;
  		previewTab.css({
  			'top' : 0,
  			'right' : juStartingPosition,
  			'height': fullWidth,
  			'padding-top': (fullWidth-juHeight)/2
  		});
  	}

  //start left
  	if( jju('.ju_preview_3.ju-tab-location-1.ju-tab-alignment-0').length && !ju_svgmode ) {
  		var positionTop = 0 + juWidth + padding*2 + juBorder*2 - ((ju_config.ju_cmid_version<3.52 && ju_mobile_scale) ? ((juWidth/2 + padding + juBorder)) : 0);
  		var positionLeft = 0 - juBorder ;
  		juStartingPosition = positionLeft-juHeight-padding*2-juBorder-20
  		juFinalPosition = positionLeft;
  		previewTab.css({
  			'top' : positionTop+TabOffset,
  			'left' : juStartingPosition
  		});
  	}

  	if( jju('.ju_preview_3.ju-tab-location-1.ju-tab-alignment-0').length && ju_svgmode ) {
  		var positionTop = 0;
  		var positionLeft = 0;
  		juStartingPosition = positionLeft-juWidth-juBorder-20
  		juFinalPosition = positionLeft;
  		previewTab.css({
  			'top' : positionTop+TabOffset,
  			'left' : juStartingPosition
  		});
  		closebtn.css({
  			'left' : 0,
  			'bottom' : 0 - 26
  		});
  		openbtn.css({
  			'left' : -25,
  			'top' : positionTop+TabOffset+(juWidth/2)
  		});
  	}

  	if( jju('.ju_preview_3.ju-tab-location-1.ju-tab-alignment-1').length && !ju_svgmode ) {
  		var positionTop = top50 + juWidth/2 + padding + juBorder - ((ju_config.ju_cmid_version<3.52 && ju_mobile_scale) ? ((juWidth/2 + padding + juBorder)/2) : 0);
  		var positionLeft = 0 - juBorder;
  		juStartingPosition = positionLeft-juHeight-padding*2-juBorder-20
  		juFinalPosition = positionLeft;
  		previewTab.css({
  			'top' : positionTop+TabOffset,
  			'left' : juStartingPosition
  		});
  	}

  	if( jju('.ju_preview_3.ju-tab-location-1.ju-tab-alignment-1').length && ju_svgmode ) {
  		var positionTop = top50 - juHeight/2 + ((ju_config.ju_cmid_version<3.52 && ju_mobile_scale && ju_config.ju_custombutton!="") ? juHeight/3 : 0);
  		var positionLeft = 0;
  		juStartingPosition = positionLeft-juWidth-juBorder-20
  		juFinalPosition = positionLeft;
  		previewTab.css({
  			'top' : positionTop+TabOffset,
  			'left' : juStartingPosition
  		});
  		closebtn.css({
  			'left' : 0,
  			'top' : 0 - 26
  		});
  		openbtn.css({
  			'left' : -25,
  			'top' : positionTop+TabOffset+(juWidth/2)
  		});
  	}

  	if( jju('.ju_preview_3.ju-tab-location-1.ju-tab-alignment-2').length && !ju_svgmode ) {
  		var positionTop = jju_getju_windowHeight() - 1;
  		var positionLeft = 0 - juBorder;
  		juStartingPosition = positionLeft-juHeight-padding*2-juBorder-20
  		juFinalPosition = positionLeft;
  		previewTab.css({
  			'top' : positionTop-TabOffset,
  			'left' : juStartingPosition
  		});
  	}

  	if( jju('.ju_preview_3.ju-tab-location-1.ju-tab-alignment-2').length && ju_svgmode ) {
  		var positionLeft = 0;
  		juStartingPosition = positionLeft-juWidth-juBorder-20
  		juFinalPosition = positionLeft;
  		previewTab.css({
  			'left' : juStartingPosition,
  			'bottom' : 0+TabOffset
  		});
  		closebtn.css({
  			'left' : 0,
  			'top' : 0 - 26
  		});
  		openbtn.css({
  			'left' : -25,
  			'bottom' : 0+TabOffset+(juWidth/2)
  		});
  	}

  	if( jju('.ju_preview_3.ju-tab-location-1.ju-tab-alignment-3').length && !ju_svgmode ) {
  		var positionTop = jju_getju_windowHeight()-1;
  		var fullWidth = (jju_getju_windowHeight() - juBorder*2 - padding*2)*((ju_config.ju_cmid_version<3.52 && ju_mobile_scale) ? 2 : 1)-2;
  		var positionLeft = 0 - juBorder;
  		juStartingPosition = positionLeft-juHeight-padding*2-juBorder-20
  		juFinalPosition = positionLeft;
  		previewTab.css({
  			'top' : positionTop,
  			'left' : juStartingPosition,
  			'width': fullWidth
  		});
  	}

  	if( jju('.ju_preview_3.ju-tab-location-1.ju-tab-alignment-3').length && ju_svgmode ) {
  		var fullWidth = jju_getju_windowHeight() - juBorder*2 - padding*2;
  		var positionLeft = 0;
  		juStartingPosition = positionLeft-juWidth-juBorder-20
  		juFinalPosition = positionLeft;
  		previewTab.css({
  			'top' : 0,
  			'left' : juStartingPosition,
  			'height': fullWidth,
  			'padding-top': (fullWidth-juHeight)/2
  		});
  	}

  //start top
  	if( jju('.ju_preview_3.ju-tab-location-2.ju-tab-alignment-0').length ) {
  		var positionTop = 0 - juBorder -((ju_config.ju_cmid_version<3.52 && ju_mobile_scale && !ju_svgmode) ? ((juHeight+totalpadding+juBorder)/2) : 0);
  		var positionLeft = 0 - ((ju_config.ju_cmid_version<3.52 && ju_mobile_scale && !ju_svgmode) ? (juWidth/2 + padding + juBorder) : 0);
  		juStartingPosition = positionTop-juHeight-padding*2-juBorder-20
  		juFinalPosition = positionTop;
  		previewTab.css({
  			'top' : juStartingPosition,
  			'left' : positionLeft+TabOffset
  		});
  		closebtn.css({
  			'right' : -26,
  			'top' : 0
  		});
  		openbtn.css({
  			'top' : -25,
  			'left' : positionLeft+TabOffset+(juWidth/2)
  		});
  	}

  	if( jju('.ju_preview_3.ju-tab-location-2.ju-tab-alignment-1').length ) {
  		var positionTop = 0 - juBorder -((ju_config.ju_cmid_version<3.52 && ju_mobile_scale && !ju_svgmode) ? ((juHeight+totalpadding+juBorder)/2) : 0);
  		var ju_windowWidth = jju(window).width()/2;
  		var positionLeft = ju_windowWidth - juWidth/2 - juBorder - padding - ((ju_config.ju_cmid_version<3.52 && ju_mobile_scale && !ju_svgmode) ? ((juWidth/2 + padding + juBorder)/2) : 0) + ((ju_config.ju_cmid_version<3.52 && ju_mobile_scale && ju_config.ju_custombutton!="") ? juWidth/3 : 0);
  		juStartingPosition = positionTop-juHeight-padding*2-juBorder-20
  		juFinalPosition = positionTop;
  		previewTab.css({
  			'top' : juStartingPosition,
  			'left' : positionLeft+TabOffset
  		});
  		closebtn.css({
  			'right' : -26,
  			'top' : 0
  		});
  		openbtn.css({
  			'top' : -25,
  			'left' : positionLeft+TabOffset+(juWidth/2)
  		});
  	}

  	if( jju('.ju_preview_3.ju-tab-location-2.ju-tab-alignment-2').length ) {
  		var positionTop = 0 - juBorder -((ju_config.ju_cmid_version<3.52 && ju_mobile_scale && !ju_svgmode) ? ((juHeight+totalpadding+juBorder)/2) : 0);
  		var positionRight = 0;
  		juStartingPosition = positionTop-juHeight-padding*2-juBorder-20
  		juFinalPosition = positionTop;
  		previewTab.css({
  			'top' : juStartingPosition,
  			'right' : positionRight+TabOffset
  		});
  		closebtn.css({
  			'left' : -26,
  			'top' : 0
  		});
  		openbtn.css({
  			'top' : -25,
  			'right' : positionRight+TabOffset+(juWidth/2)
  		});
  	}

  	if( jju('.ju_preview_3.ju-tab-location-2.ju-tab-alignment-3').length ) {
  		var positionTop = 0 - juBorder -((ju_config.ju_cmid_version<3.52 && ju_mobile_scale && !ju_svgmode) ? ((juHeight+totalpadding+juBorder)/2) : 0);
  		var fullju_windowWidth = jju(window).width()*((ju_config.ju_cmid_version<3.52 && ju_mobile_scale && !ju_svgmode) ? 2 : 1);
  		juStartingPosition = positionTop-juHeight-padding*2-juBorder-20
  		juFinalPosition = positionTop;
  		previewTab.css({
  			'top' : juStartingPosition,
  			'left' : 0-((ju_config.ju_cmid_version<3.52 && ju_mobile_scale && !ju_svgmode) ? jju(window).width() : 0),
  			'width': fullju_windowWidth - juBorder*2
  		});
  	}

  //start Bottom
  	if( jju('.ju_preview_3.ju-tab-location-3.ju-tab-alignment-0').length ) {
  		var positionLeft = 0 - ((ju_config.ju_cmid_version<3.52 && ju_mobile_scale && !ju_svgmode) ? (juWidth/2 + padding + juBorder) : 0);
  		var positionBottom = 0 - juBorder;
  		juStartingPosition = positionBottom-juHeight-padding*2-juBorder-20
  		juFinalPosition = positionBottom;
  		previewTab.css({
  			'left' : positionLeft+TabOffset,
  			'bottom' : juStartingPosition
  		});
  		closebtn.css({
  			'right' : -26,
  			'bottom' : 0
  		});
  		openbtn.css({
  			'bottom' : -25,
  			'left' : positionLeft+TabOffset+(juWidth/2)
  		});
  	}

  	if( jju('.ju_preview_3.ju-tab-location-3.ju-tab-alignment-1').length ) {
  		var ju_windowWidth = jju(window).width()/2;
  		var positionLeft = ju_windowWidth - juWidth/2 - juBorder - padding - ((ju_config.ju_cmid_version<3.52 && ju_mobile_scale && !ju_svgmode) ? ((juWidth/2 + padding + juBorder)/2) : 0) + ((ju_config.ju_cmid_version<3.52 && ju_mobile_scale && ju_config.ju_custombutton!="") ? juWidth/3 : 0);
  		var positionBottom = 0 - juBorder;
  		juStartingPosition = positionBottom-juHeight-padding*2-juBorder-20
  		juFinalPosition = positionBottom;
  		previewTab.css({
  			'left' : positionLeft+TabOffset,
  			'bottom' : juStartingPosition
  		});
  		closebtn.css({
  			'right' : -26,
  			'bottom' : 0
  		});
  		openbtn.css({
  			'bottom' : -25,
  			'left' : positionLeft+TabOffset+(juWidth/2)
  		});
  	}

  	if( jju('.ju_preview_3.ju-tab-location-3.ju-tab-alignment-2').length ) {
  		var positionRight = 0;
  		var positionBottom = 0 - juBorder;
  		juStartingPosition = positionBottom-juHeight-padding*2-juBorder-20
  		juFinalPosition = positionBottom;
  		previewTab.css({
  			'right' : positionRight+TabOffset,
  			'bottom' : juStartingPosition
  		});
  		closebtn.css({
  			'left' : -26,
  			'bottom' : 0
  		});
  		openbtn.css({
  			'bottom' : -25,
  			'right' : positionRight+TabOffset+(juWidth/2)
  		});
  	}

  	if( jju('.ju_preview_3.ju-tab-location-3.ju-tab-alignment-3').length ) {
  		var fullju_windowWidth = jju(window).width()*((ju_config.ju_cmid_version<3.52 && ju_mobile_scale && !ju_svgmode) ? 2 : 1);
  		var positionBottom = 0 - juBorder;
  		juStartingPosition = positionBottom-juHeight-padding*2-juBorder-20
  		juFinalPosition = positionBottom;
  		previewTab.css({
  			'left' : 0-((ju_config.ju_cmid_version<3.52 && ju_mobile_scale && !ju_svgmode) ? jju(window).width() : 0),
  			'bottom' : juStartingPosition,
  			'width': fullju_windowWidth - juBorder*2
  		});
  	}

  } // end tab position


  //TAB OPTIONS ======
  function tabOptions() {
  	//console.log("call tabOptions");
  	jju('#ju_bbox').css('width','auto');

  	var previewTab = jju('.ju_preview_3');
  //Text Functions
  	var tabText = ju_config.ju_button_text;
  	var tabColor = ju_config.ju_color;
  	var tabCloseColor = ju_config.ju_close_color;
  	var tabColor2 = ju_config.ju_gradientcolor;
  	var tabBorderColor = ju_config.ju_bordercolor;
  	var tabBorderWidth = ju_config.ju_bordersize;
  	var tabBorderStyle = ju_config.ju_borderstyle;

  	if (ju_config.ju_custombutton!=''){

  		switch(ju_config.ju_location)
  		{
  		case "ju-tab-location-0":
  			var ju_carat = '&#9668;';
  		  break;
  		case "ju-tab-location-1":
  			var ju_carat = '&#9658;';
  		  break;
  		case "ju-tab-location-2":
  			var ju_carat = '&#9660;';
  		  break;
  		case "ju-tab-location-3":
  			var ju_carat = '&#9650;';
  		  break;
  		}
  		jju('#ju_bbox').after('<a href="Javascript:void(0);" id="ju_custom_open_btn">'+ju_carat+'</a>');

  		var closebutton = jju('#ju_custom_close_btn');
  		var openbutton = jju('#ju_custom_open_btn');

  		jju(closebutton).css({
  			//'color' : tabTextColor,
  			'background': tabColor,
  			'border': tabBorderWidth + 'px solid ' + tabBorderColor,
  			'border-radius': ju_config.ju_corners+"px",
  			'color': tabCloseColor
  		});

  		jju(openbutton).css({
  			//'color' : tabTextColor,
  			'background': tabColor,
  			'border': tabBorderWidth + 'px solid ' + tabBorderColor,
  			'border-radius': ju_config.ju_corners+"px",
  			'color': tabCloseColor
  		});

  		jju('#ju_bbox').addClass(ju_config.ju_location);
  		jju('#ju_bbox').addClass(ju_config.ju_alignment);



  	} else {
  		var previewText = jju('.ju_tab_text');

  	//Tab Borders
  		jju(previewTab).css('border', tabBorderWidth + 'px' + " "+tabBorderStyle+" " + tabBorderColor);

  		jju(previewTab).css('background', tabColor);

  		if( tabColor2!="" ) {
  			var gradient = 'linear-gradient(top, ' + tabColor + ', ' + tabColor2 + ')';
  			jju.each(['', '-o-', '-moz-', '-webkit-', '-ms-'], function() {
  			    jju(".ju_preview_3").css({ 'background-image': this + gradient });
  		  });
  		}

  		jju('#ju_bbox').addClass(ju_config.ju_location);
  		jju('#ju_bbox').addClass(ju_config.ju_alignment);

  		jju('#ju_bbox').css({'padding':ju_config.ju_size+'px','box-shadow':'0px 0px '+ju_config.ju_shadow+'px 0px rgba(50, 50, 50, 0.75)'});
  		switch (ju_config.ju_location){
  			case 'ju-tab-location-0':
  			case 'ju-tab-location-3':
  				jju('#ju_bbox').css({"border-bottom-left-radius":"0px","border-bottom-right-radius":"0px","border-top-left-radius":ju_config.ju_corners+"px","border-top-right-radius":ju_config.ju_corners+"px"});
  				break;
  			case 'ju-tab-location-1':
  			case 'ju-tab-location-2':
  				jju('#ju_bbox').css({"border-bottom-left-radius":ju_config.ju_corners+"px","border-bottom-right-radius":ju_config.ju_corners+"px","border-top-left-radius":"0px","border-top-right-radius":"0px"});
  				break;
  		}
  		jju('#ju_bbox').width(jju('#ju_bbox').outerWidth() + 10);
  	}


  } //end tabOptions

  function jju_getParameterByName(name) {
      name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
      var regex = new RegExp("[\\?&]" + name + "=([^&#]*)", "i"),
          results = regex.exec(location.search);
      return results == null ? "" : decodeURIComponent(results[1].replace(/\+/gi, " "));
  }

  function jju_getju_windowHeight(){
  	if (jju('#ju_overlay').height()>50){
  		return jju('#ju_overlay').height()
  	} else {
  		return ju_windowHeight;
  	}
	}

	window.ju_removeProfile = function(){
		if (ju_current_url.indexOf('preview-popup.html') >= 0) return false;
		clearInterval(ju_target_interval);
		ju_stopupdating = true;
		ju_Cookie.setCookies("_ju_dn", '-1', 30, '/', '.' + ju_config.root);
		ju_Cookie.setCookies("_ju_pn", '', -1, '/', '.' + ju_config.root);
		ju_beaconsend('https://'+ju_profileUrl+'/api/session/remove', {
			"guid": _ju_dt,
			"accid": ju_active_ju_num
		}, false);
		if (typeof(ju_optout) === 'function') {
			ju_optout();
		}
		setTimeout(function () {
			ju_setup_cookie_data(true);
		}, 1000)
	}

  function ju_record_event(email, eventname, promotitle, cmid, options, step, form){
    ju_listrak_event(email, eventname, promotitle, step, cmid, options);
    ju_ga_event(eventname, promotitle, cmid, step);
    ju_heap_event(eventname, promotitle, cmid, step);
  	ju_sgio_event(email, eventname, promotitle, step, options);
  	ju_rejoiner_event(email, eventname, promotitle, step, options);
		ju_drip_event(email, eventname, promotitle, step, options);
    ju_bluecore_event(email, eventname, promotitle, step, options);
  	ju_optimizely_event(eventname, step);
  	ju_gtm_event(eventname, promotitle, cmid, step);
    ju_zaius_event(email, eventname, promotitle, step, options);
    ju_ibm_analytics_event(email, eventname, promotitle, step, cmid, options);
    ju_klaviyo_event(email, eventname, promotitle, step, cmid, options, form);
		ju_postscript_event(email, eventname, promotitle, step, cmid, options, form);
    ju_resci_event(email, eventname, promotitle, step, cmid, options);
    ju_recart_event(email, eventname, promotitle, step, options);
    ju_hubspot_event(email, eventname, promotitle, step, cmid, options);
    ju_adobe_event(email, eventname, promotitle, step, cmid, options);
    ju_cordial_event(email, eventname, promotitle, step, cmid, options);
    ju_optimove_event(email, eventname, promotitle, step, cmid, options, form);
    ju_braze_event(email, eventname, promotitle, step, cmid, options);
    ju_field_event(email, eventname, promotitle, step, cmid, options, form);
		if (typeof (ju_custom_event) === 'function') ju_custom_event(email, eventname, promotitle, step, cmid, options, form);
    try{
      jju.each(ju_config.trackFunc,function(i,v){
        if (step==1 && v.impression) v.impression(email, eventname, promotitle, cmid, options, form);
        if (step==2 && v.engagement) v.engagement(email, eventname, promotitle, cmid, options, form);
      });
    } catch(e){

    }
  }

  function ju_optimizely_event(a){
  	// fire optimizely event
  	try {
  		var ju_opt_event = document.createEvent('HTMLEvents');
  		ju_opt_event.initEvent(a, true, true);
  		document.dispatchEvent(ju_opt_event);
  	}
  	catch(err) {
  	  console.log('caught error trying to push to optimizely');
  	}
  }

  function ju_gtm_event(a, b, cmid, step){
    if (ju_config.disableEventGtm) return;
    b = b.replace(/%/g,'');
  	if (typeof(dataLayer) !== "undefined") {
  		if (step==1){
        dataLayer.push({
          'promoTitle': b,
          'promoID': cmid,
          'event': 'JustunoImpression'
        });
      }
      if (step==2){
        dataLayer.push({
          'promoEvent': a,
          'promoTitle': b,
          'promoID': cmid,
          'event': 'JustunoEvent'
        });
      }
  	}
  }

  function ju_zaius_event(email, a, b, step, options) {
    if (ju_config.disableEventZaius) return;
    if (typeof(zaius) !== "undefined") {
      try {
          if (email!=''){
            zaius.subscribe(
              {
                email:email,
                list_id:'newsletter',
                source:'Justuno',
                coupon: (options.promo_coupon != '' && options.promo_coupon!==undefined ? options.promo_coupon : '')
              }
            );
          }
      }
      catch(err) {
          console.log('caught error trying to push to zaius');
      }
    }
  }

  function ju_ga_event(a, b, cmid, step) {
    if (ju_config.disableEventGa) return;
    b = b.replace(/%/g,'');
    if (typeof(ga) === "function") {
      try {
        var trackerName = ga.getAll();
        if(ju_gaTracker !='' || (trackerName.length && trackerName.length > 0)) {
          trackerName = ju_gaTracker!='' ? ju_gaTracker : trackerName[0].get('name');
          if (trackerName !== '' && trackerName !== 'undefined' && trackerName !== 't0') {
            ga(trackerName + ".send", "event", "Justuno", a, b, {'nonInteraction': 1});
          } else {
            ga("send", "event", "Justuno", a, b, {'nonInteraction': 1});
          }
        }
      } catch(err) {
        // error
      }
    } else if (typeof(__gaTracker) !== "undefined") { // because yoast decided to rename the tracker name
      try {
        var trackerName = __gaTracker.getAll();
        if(ju_gaTracker !='' || (trackerName.length && trackerName.length > 0)) {
          trackerName = ju_gaTracker!='' ? ju_gaTracker : trackerName[0].get('name');
          if (trackerName!='' && trackerName!='undefined' && trackerName!='t0'){
            __gaTracker(trackerName+".send", "event", "Justuno", a, b, {'nonInteraction': 1});
          } else {
            __gaTracker("send", "event", "Justuno", a, b, {'nonInteraction': 1});
          }
        }
      } catch(err) {
        // error
      }
    } else {
      try{
        if (typeof(pageTracker) != "undefined" && pageTracker !== null && typeof(pageTracker._trackEvent) != "undefined") {
          pageTracker._trackEvent("Justuno", a, b, true)
        } else {
          if (typeof(_gaq) != "undefined" && _gaq !== null) {
            trackerName = ju_gaTracker!='' ? ju_gaTracker+'.' : '';
            _gaq.push([trackerName+"_trackEvent", "Justuno", a, b, 0, true])
          }
        }
      } catch(err){
        // error
      }
    }
  }

  function ju_heap_event(a, b, cmid, step) {
    if (ju_config.disableEventHeap) return;
    if (typeof(heap) === "object") {
      try {
        heap.track('Justuno', {type: a, title: b});
      } catch(err) {
        // error
      }
    }
  }

  function ju_sgio_event(email, a, b, step, options) {
    if (ju_config.disableEventSgio) return;
    if (typeof(analytics) !== "undefined") {
      try {
        if (email!=''){
          analytics.identify({
            email: email,
            coupon: (options.promo_coupon != '' && options.promo_coupon!==undefined ? options.promo_coupon : ''),
          });
          analytics.track(a, {
            title: b,
            email: email,
            nonInteraction: 1
          }, {
            integrations: {
              'Google Analytics': false
            }
          });
        }
        analytics.track(a, {
            title: b,
            nonInteraction: 1
          }, {
          integrations: {
            'Google Analytics': false
          }
        });
      }
      catch(err) {
          console.log('caught error trying to push to segment');
      }
    }
  }

  function ju_rejoiner_event(email, a, b, step, options) {
    if (ju_config.disableEventRejoiner) return;
    if (typeof(_rejoiner) !== "undefined") {
      try {
        if (email!=''){
          _rejoiner.push(['setCustomerEmail', {'email': email}]);
        }
        if (options.promo_coupon != '' && options.promo_coupon!==undefined){
          _rejoiner.push(['setCartData', {'promo': options.promo_coupon}]);
        }
      } catch(err) {
        console.log('caught error trying to push to rejoiner');
      }
    }
  }

	function ju_drip_event(email, a, b, step, options) {
    if (ju_config.disableEventDrip) return;
    if (typeof(_dcq) !== "undefined") {
      try {
        if (email!=''){
          _dcq.push(["identify", {
						email: email
					}]);
        }
      } catch(err) {
        console.log('caught error trying to push to drip');
      }
    }
  }

  function ju_bluecore_event(email, a, b, step, options) {
    if (ju_config.disableEventBc) return;
    if (typeof(triggermail) !== "undefined") {
      try {
        if (email!=''){
          var pOpt = options.promo_options
          triggermail.identify({
              email: email,
              opt_in: true,
              list_name: (pOpt.bluecore_source && pOpt.bluecore_lists != '' ? pOpt.bluecore_lists : b),
              source: (pOpt.bluecore_source && pOpt.bluecore_source != '' ? pOpt.bluecore_source : 'justuno')
          });
        }
      }
      catch(err) {
        console.log('caught error trying to push to bluecore');
      }
    }
  }

  function ju_ibm_analytics_event(email, a, b, step, cmid, options) {
    if (ju_config.disableEventIbm) return;
    if (typeof(cmCreateConversionEventTag) !== "undefined") {
      try {
        var pOpt = options.promo_options
        if (step==1){
          cmCreateConversionEventTag (b+' - '+cmid,step,(pOpt.ibm_analytics_category && pOpt.ibm_analytics_category != '' ? pOpt.ibm_analytics_category : 'JUSTUNO'));
        }
        if (step==2 && email!=''){
          cmCreateConversionEventTag (b+' - '+cmid,step,(pOpt.ibm_analytics_category && pOpt.ibm_analytics_category != '' ? pOpt.ibm_analytics_category : 'JUSTUNO'),(pOpt.ibm_analytics_points && pOpt.ibm_analytics_points != '' ? pOpt.ibm_analytics_points : '0'));
        }
      }
      catch(err) {
          console.log('caught error trying to push to ibm analytics');
      }
    }
  }

  function ju_klaviyo_event(email, a, b, step, cmid, options, form) {
    if (ju_config.disableEventKlaviyo) return;
    if (typeof(_learnq) !== "undefined") {
      try {
        var identity = {};
        var phone_number = [];
        if (Array.isArray(form) && form.length>0){
          phone_number = form.filter(function(field) {
            return field.name === 'phone_number';
          });
          if (phone_number.length>0) {
			var phoneNumber = phone_number[0].value;
			// Remove all non-numeric characters from phone string
			phoneNumber = phoneNumber.replace(/\D/g, "");
			
			if (phoneNumber.length>=10){
				// If the length is 10 then that's a phone number without the country code
				// Add the US country code to the beginning of phoneNumber
				if (phoneNumber && phoneNumber.length === 10) {
					phoneNumber = '+1'+phoneNumber;
				}

				// If the length is not 10 then check for the + and add + to beginning
				if (phoneNumber && !phoneNumber.includes("+")) {
					phoneNumber = '+'+phoneNumber;
				}
				identity.$phone_number = phoneNumber;
			}
		  }
        };
        if (email!='') identity.$email = email;
        if (identity.$email || identity.$phone_number){
          identity.coupon = options.promo_coupon;
          _learnq.push(['identify', identity]);
        };
				if (email=='') {
					_learnq.push(['track', 'Justuno '+a, {
						'Promo Title' : b,
						'Promo ID' : cmid
					}]);
				}
      }
      catch(err) {
          console.log('caught error trying to push to klaviyo');
      }
    }
  }

	function ju_postscript_event(email, a, b, step, cmid, options, form) {
    if (ju_config.disableEventPostscript) return;
    if (window.Postscript) {
      try {
				var smsNumber = ju_getPhone(form);
				var identity = {}
				if (email!='') identity.email = email;
        if (smsNumber){
					identity.phone = smsNumber;
					window.Postscript.identify(identity);
				}
      }
      catch(err) {
          console.log('caught error trying to push to postscript');
      }
    }
  }

  function ju_resci_event(email, a, b, step, cmid, options) {
    if (ju_config.disableEventResci) return;
    if (typeof(_rsq) !== "undefined") {
      try {
        if (email!=''){
          window._rsq.push(['_setUserEmail',email]);
          window._rsq.push(['_setUserProperties', { 'record_id': ju_md5(email.toLowerCase()),'email':email, 'registration_source':'justuno'}]);
          window._rsq.push(['_setAction', 'email_entered']);
          window._rsq.push(['_track']);
        };
      }
      catch(err) {
          console.log('caught error trying to push to resci');
      }
    }
  }

  function ju_field_event(email, a, b, step, cmid, options, form) {
    try {
      var phone_number = [];
      var phone = '';
      if (Array.isArray(form) && form.length>0){
        phone_number = form.filter(function(field) {
          return field.name.toLowerCase().indexOf('phone') != -1 || field.name.toLowerCase().indexOf('sms') != -1 || field.value.replace(/[^0-9]/g, "").length==10;
        });
        if (phone_number.length>0) phone = phone_number[0].value;
      };
      if (email!='' || phone!=''){
        if (!jju('#ju_extras').length){
          jju('body').append('<div id="ju_extras" style="visibility:hidden;"></div>');
        };
				jju('#ju_extras').append('<input id="ju_hidden_source" name="ju_hidden_source" value="justuno">');
        if (!jju('#ju_hidden_email').length){
          jju('#ju_extras').append('<input id="ju_hidden_email" name="ju_hidden_email">');
          jju('#ju_extras').append('<input id="ju_hidden_sms" name="ju_hidden_sms">');
          jju('#ju_extras').append('<button id="ju_hidden_btn" name="ju_hidden_btn">button</button>');
        }
        jju('#ju_extras').show();
        if (email!='') jju('#ju_hidden_email').val(email).trigger('change');
        if (phone!='') {
          jju('#ju_hidden_sms').val(phone).trigger('change');
					setTimeout(function(){
						jju('#ju_hidden_btn').click();
					},200)
        }
        jju('#ju_extras').hide();
      };
    }
    catch(err) {
        console.log('caught error trying to push to bronto');
    }
  }

  function ju_listrak_event(email, a, b, step, cmid, options) {
    if (ju_config.disableEventListrak) return;
    if (typeof(_ltk) !== "undefined") {
      try {
        if (email!=''){
          _ltk.SCA.CaptureEmail('ju_hidden_email');
        };
        _ltk.Signup.New("ju_hidden_sms", "ju_hidden_sms", _ltk.Signup.TYPE.CLICK, "ju_hidden_btn", "sms");
				_ltk.Signup.SetField("ju_hidden_sms", "ju_hidden_source");
      }
      catch(err) {
          console.log('caught error trying to push to listrak');
      }
    }
  }

  function ju_recart_event(email, a, b, step, options) {
    if (ju_config.disableEventRecart) return;
    if (typeof(recart_ju_callback) !== "undefined") {
      try {
        if (email!=''){
          recart_ju_callback(email,(options.promo_coupon != '' && options.promo_coupon!==undefined ? options.promo_coupon : ''));
        }
      }
      catch(err) {
          console.log('caught error trying to push to recart');
      }
    }
  }

  function ju_hubspot_event(email, a, b, step, cmid, options) {
    if (ju_config.disableEventHubspot) return;
    if (typeof(_hsq) !== "undefined") {
      try {
        if (step==1){
          // do something
        }
        if (step==2 && email!=''){
          _hsq.push(["identify", {  email: email }]);
          _hsq.push(["trackEvent", {
            id: "Engaged with Justuno : " + b
          }]);
        }
      }
      catch(err) {
          console.log('caught error trying to push to hubspot');
      }
    }
  }

  function ju_adobe_event(email, a, b, step, cmid, options) {
    if (ju_config.disableEventAdobe) return;
    if (typeof(_satellite) !== "undefined") {
      try {
        if (step==1){
          _satellite.track('email:modal');
        }
        if (step==2 && email!=''){
          _satellite.track('email:signup', { emailMd5 : ju_md5(email.trim().toLowerCase()) });
        }
      }
      catch(err) {
          console.log('caught error trying to push to adobe');
      }
    }
  }

  function ju_cordial_event(email, a, b, step, cmid, options) {
    if (ju_config.disableEventCordial) return;
    if (typeof(cordial) !== "undefined") {
      try {
        if (step==2 && email!=''){
          cordial.identify(email);
          cordial.contact({});
        }
      }
      catch(err) {
          console.log('caught error trying to push to cordial');
      }
    }
  }

  function ju_optimove_event(email, a, b, step, cmid, options, form) {
    if (ju_config.disableEventOptimove) return;
    if (typeof(optimoveSDK) !== "undefined") {
      var params = {
        'id':cmid,
        'justuno':b,
        'source': "newsletter popup"
      };
      try {
        if (step==1){
          params.engagement = a;
          optimoveSDK.API.reportEvent('Justuno_promotion_triggered', params);
        }
        if (step==2 && email!=''){
          var first_name = [];
          var last_name = [];
          var optin = [];
          if (Array.isArray(form) && form.length>0){
            first_name = form.filter(function(field) {
              return field.name === 'first_name';
            });
            last_name = form.filter(function(field) {
              return field.name === 'last_name';
            });
            optin = form.filter(function(field) {
              return field.name === 'optin';
            });
            if (first_name.length>0) params.first_name = first_name[0].value;
            if (last_name.length>0) params.last_name = last_name[0].value;
            if (optin.length>0) params.opt_in = optin[0].value.toLowerCase() == 'true' ? true : false;
          };
					//registerUser() function sends both the SDK_ID and one custom event to Optimove
					optimoveSDK.API.registerUser("" + email + "", "" + email + "", "signup", params);
        }
      }
      catch(err) {
          console.log('caught error trying to push to optimove');
      }
    }
  }

  function ju_braze_event(email, a, b, step, cmid, options) {
    if (ju_config.disableEventBraze) return;
    if (typeof(appboy) !== "undefined") {
      try {
        if (step==2 && email!=''){
          appboy.getUser().setEmail(email);
          appboy.getUser().addAlias(email, "alias_email");
          appboy.getUser().addToCustomAttributeArray("source", "Justuno");
          appboy.getUser().addToCustomAttributeArray("campaign", "Justuno - "+b);
        }
      }
      catch(err) {
          console.log('caught error trying to push to braze');
      }
    }
  }

  function ju_hasTouch() {
    if (navigator.userAgent.match(/ipad|ipod|iphone|android|silk/i)) {
      return window.ontouchstart !== undefined;
    } else {
      return false;
    }
	}

	function ju_getPhone(form){
		var phone_number = [];
		if (Array.isArray(form) && form.length>0){
			phone_number = form.filter(function(field) {
				return field.name.toLowerCase() === 'phone' ||
					field.name.toLowerCase() === 'phone_number' ||
					field.name.toLowerCase() === 'mobilenumber' ||
					field.name.toLowerCase() === '$phone_number' ||
					field.name.toLowerCase() === 'phonenumber' ||
					field.name.toLowerCase() === 'mobile_number_' ||
					field.name.toLowerCase() === 'mobile' ||
					field.name.toLowerCase() === 'cell' ||
					field.name.toLowerCase() === 'cellphone' ||
					field.name.toLowerCase() === 'sms' ||
					field.name.toLowerCase() === 'smsnumber';
			});
			return (phone_number.length>0 ? phone_number[0].value : false);
		};
	}

  function ju_generateUID() {
    // I generate the UID from two parts here
    // to ensure the random number provide enough bits.
    var firstPart = (Math.random() * 46656) | 0;
    var secondPart = (Math.random() * 46656) | 0;
    firstPart = ("000" + firstPart.toString(36)).slice(-3);
    secondPart = ("000" + secondPart.toString(36)).slice(-3);
    return firstPart + secondPart;
  }

  function ju_genPageId(){
    window.ju_pageid = ju_generateUID()
  }

  function sendPushBody(){
    juPushWindow.postMessage(safeToJSON(ju_pushBody), "*");
  }

  function ju_initpush(cmID,cpID,Lists){
    console.log('is this working',Lists)

    window.ju_pushBody = {
      promoId: cmID,
      couponId: cpID.toString(),
      lists: Lists && Lists.length>0 ? Lists : [0],
      website: ju_current_domain,
      url:ju_current_domain,
      filters: {
        lang: ju_language,
        country: ju_config.ju_country,
        region: ju_config.ju_region,
        city: ju_config.ju_city,
        postcode: ju_config.ju_zip,
        segment: ju_config.ju_mobile
      },
      userAgent: navigator.userAgent,
      accid: ju_active_ju_num,
      guid: _ju_dt,
      ip: ju_config.ju_ip,
      sessionKey: ju_config.ju_sessionkey,
      pageId: ju_pageid
    };

    ju_readyAskPerm();

    fetch(ju_config.swPath)
      .then(function (response) {
        //ju_readyAskPerm();
      })
      ["catch"](function (err) {
        console.log('service worker doesn\'t exist.',err);
        ju_pns = 'backup';
        //ju_readyAskPerm();
      });

    setTimeout(ju_readyAskPerm,1000);
  }

  function ju_readyAskPerm(){
    switch (ju_pns) {
      case 'safari':
      console.log('perm1')
        var permissionData = top.window.safari.pushNotification.permission('web.com.justuno.push');
        ju_checkRemotePermission(permissionData);
        break;
      case 'other':
        console.log('Service Worker and Push is supported');
        ju_askPermission()
          .then(ju_subscribeUserToPush)
          .then(ju_sendSubscriptionToBackEnd)
          ["catch"](function (err) {
            //console.error('Error Happened:', err)
          });
        break;
      case 'backup':
        var d = ju_config.root.split('.')[0];
        window.juPushWindow = window.open('https://'+d+'.p.'+window.ju_host, d);
        break;
      default:
        console.log('push notifications not supported');
    }
  }

  function ju_askPermission() {
    return new Promise(function (resolve, reject) {
      var permissionResult = window.Notification.requestPermission(function (result) {
        resolve(result);
      });

      if (permissionResult) {
        permissionResult.then(resolve, reject);
      }
    })
      .then(function (permissionResult) {
        if (permissionResult == 'granted') {
          jju('#ju_iframe_'+ju_pushBody.promoId)[0].contentWindow.getpromocode('19','',ju_pushBody.cpID,1,1);
        } else if (permissionResult == 'denied') {
          jju_receiveMessage({
            'close':true,
            'promoid':ju_pushBody.promoId
          });
        }
        juDs.notif.perm = permissionResult;
        juDa.notif.perm = permissionResult;
        write_data_cookies(false,100,false);
      });
  }

  function ju_pushSupport(){
    try{
      if ('safari' in top.window && 'pushNotification' in top.window.safari) {
        return 'safari';
      } else if ('serviceWorker' in navigator && 'PushManager' in window) {
        return 'other';
      } else {
        return 'none';
      }
    } catch(e){
      return 'none';
    }
  }

  function ju_registerServiceWorker() {
    if (ju_pns!='none'){
      if(ju_current_url_protocol=='https://'){
        return fetch(ju_config.swPath)
        .then(function (response) {
          return navigator.serviceWorker.register(ju_config.swPath)
          .then(function (registration) {
            console.log('Service worker successfully registered.');
            return registration;
          })
          ["catch"](function (err) {
            console.log('Unable to register service worker.', err);
            ju_pns = 'backup';
          });
        })
        ["catch"](function (err) {
          console.log('service worker doesn\'t exist.',err);
          ju_pns = 'backup';
        });
      } else {
        console.log('service worker requires https');
          ju_pns = 'backup';
      }
    }
  }

  function ju_UrlExists(url)
  {
      var http = new XMLHttpRequest();
      http.open('HEAD', url, false);
      http.send();
      return http.status!=404;
  }

  function ju_checkRemotePermission(permissionData) {
    console.log(permissionData)
    if (permissionData.permission === 'default') {
      console.log('default',ju_pushBody)
      // This is a new web service URL and its validity is unknown.
      ju_pushBody.lists = safeToJSON(ju_pushBody.lists);
      ju_pushBody.filters = safeToJSON(ju_pushBody.filters);
      ju_pushBody.webServiceURL = ju_pushDomain+'/api/push/safari/post';
      //console.log(ju_pushBody)
      top.window.safari.pushNotification.requestPermission(
        ju_pushDomain+'/api/push/safari/post', // The web service URL.
        'web.com.justuno.push',     // The Website Push ID.
        ju_pushBody, // Data that you choose to send to your server to help you identify the user.
        ju_checkRemotePermission         // The callback function.
      );
    }
    else if (permissionData.permission === 'denied') {
      console.log('denied')
      jju_receiveMessage({
        'close':true,
        'promoid':ju_pushBody.promoId
      });
    }
    else if (permissionData.permission === 'granted') {
      console.log('granted', permissionData)
      jju('#ju_iframe_'+ju_pushBody.promoId)[0].contentWindow.getpromocode('19','',ju_pushBody.cpID,1,1);
      // The web service URL is a valid push provider, and the user said yes.
      // permissionData.deviceToken is now available to use.
      ju_pushBody.deviceToken = permissionData.deviceToken;
      fetch(ju_pushDomain+'/api/push/safari/post/subscribe/list', {
        method: 'POST',
        headers: {
          "Content-Type": "application/json; charset=utf-8"
        },
        body: safeToJSON(ju_pushBody)
      })
        .then(function (response) {
          if (response.status !== 200) console.error('Error:', response.statusText)
        })
        ["catch"](function(error) {
          console.error('Error: ', error);
        })
    }
    juDs.notif.perm = permissionData.permission;
    juDa.notif.perm = permissionData.permission;
    write_data_cookies(false,100,false);
  };

  function ju_subscribeUserToPush() {
    return ju_registerServiceWorker()
      .then(function (registration) {
        var subscribeOptions = {
          userVisibleOnly: true,
          applicationServerKey: urlBase64ToUint8Array(
            'BBp-aEqr8K4-yINm3NXIKOgfldCI-9PPlHlg82TJzQ1UQlx086iDsN1AvbL8Yyxp7NdwJbfhGFRvg5GWEqaVEfo'
          )
        };

        return registration.pushManager.subscribe(subscribeOptions)
        .then(function(e){
          console.log('push worker subscription success',e)
          return e
        })["catch"](function(n) {
          console.log('failed to subscriber worker',n)
          throw 'failed to subscriber worker'
        })
      })
      .then(function (pushSubscription) {
        console.log('Received PushSubscription 1: ', safeToJSON(pushSubscription));
        return pushSubscription;
      })
  }

  function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }

  function urlBase64ToUint8Array(base64String) {
    var padding = '='.repeat((4 - base64String.length % 4) % 4);
    var base64 = (base64String + padding).replace(/\-/g, '+').replace(/_/g, '/');
    var rawData = window.atob(base64);
    return Uint8Array.from([].concat(_toConsumableArray(rawData)).map(function (char) {
      return char.charCodeAt(0);
    }));
  }

  function ju_sendSubscriptionToBackEnd(subscription) {
    ju_pushBody.subscription = subscription;
    console.log(ju_pushBody, ju_domain)
    return fetch(ju_pushDomain+'/api/push/subscribe/', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: safeToJSON(ju_pushBody)
    })
      .then(function (response) {
        if (!response.ok) {
          throw new Error('Bad status code from server.');
        }

        return response.json();
      })
      .then(function (responseData) {
        if (!(responseData.data && responseData.data.success)) {
          throw new Error('Bad response from server.');
        }
      });
  }

  function ju_detectCompetitors () {
		var w = window;
		var competitors = [[w.bouncex,'Bounce Exchange'],[w._d_site,'Privy'],[w.sumo,'Sumo Me'],[w.beeketingWPJP,'Better Coupon Box'],[w.fsb_bars,'Free Shipping Bar'],[typeof window.ExitPopContent !== "undefined",'Spin A Sale'],[w.wheelio_ver,'Wheelio'],[w.BOLD && w.BOLD.upsell,'Product Upsell'],[w.OptinMonsterApp,'OptinMonster']];
    var detected = {
      competitors: []
		};
		competitors.forEach(function(arr){
			if(arr[0]){
				detected.competitors.push({
					competitor: arr[1],
					date: Date.now()
				});
			}
		})

    return detected;
  }

  function ju_compareDetected(detected, previousComp){
    var changes = [];
    try{
      var oldCompetitors = Object.keys(previousComp);
      var numCurrent = detected.length;
      var numOld = oldCompetitors.length;
      var changes = [];
      // console.log('oldCompetitors:', oldCompetitors);

      if(numOld > 0){
        if (numCurrent > 0) {
          detected.forEach(function(competitor){
            //console.log(competitor);
            if(oldCompetitors.indexOf(competitor.competitor) === -1 || (new Date()).getTime()-competitor.date > 86400000){
              changes.push(competitor);
            }
          })
        } else if(oldCompetitors.indexOf('Removed') === -1){
          changes.push({competitor: 'Removed', date: Date.now()});
        }
      } else if (numCurrent > 0){
        detected.forEach(function(competitor){
          changes.push(competitor);
        })
      }

      if(changes.length === 0){
        changes = undefined;
      }

    }catch(er){
      //
    }

    return changes;

  }
}
