!function(t){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).pica=t()}}(function(){return function a(o,A,s){function u(e,t){if(!A[e]){if(!o[e]){var i="function"==typeof require&&require;if(!t&&i)return i(e,!0);if(h)return h(e,!0);var r=new Error("Cannot find module '"+e+"'");throw r.code="MODULE_NOT_FOUND",r}var n=A[e]={exports:{}};o[e][0].call(n.exports,function(t){return u(o[e][1][t]||t)},n,n.exports,a,o,A,s)}return A[e].exports}for(var h="function"==typeof require&&require,t=0;t<s.length;t++)u(s[t]);return u}({1:[function(t,e,i){"use strict";var r=t("inherits"),n=t("multimath"),a=t("multimath/lib/unsharp_mask"),o=t("./mm_resize");function A(t){var e=t||[],i={js:0<=e.indexOf("js"),wasm:0<=e.indexOf("wasm")};n.call(this,i),this.features={js:i.js,wasm:i.wasm&&this.has_wasm},this.use(a),this.use(o)}r(A,n),A.prototype.resizeAndUnsharp=function(t,e){var i=this.resize(t,e);return t.unsharpAmount&&this.unsharp_mask(i,t.toWidth,t.toHeight,t.unsharpAmount,t.unsharpRadius,t.unsharpThreshold),i},e.exports=A},{"./mm_resize":4,inherits:15,multimath:16,"multimath/lib/unsharp_mask":19}],2:[function(t,e,i){"use strict";function w(t){return t<0?0:255<t?255:t}e.exports={convolveHorizontally:function(t,e,i,r,n,a){var o,A,s,u,h,f,c,g,l,I,d,m=0,p=0;for(l=0;l<r;l++){for(I=h=0;I<n;I++){for(f=a[h++],c=a[h++],g=m+4*f|0,o=A=s=u=0;0<c;c--)u=u+(d=a[h++])*t[g+3]|0,s=s+d*t[g+2]|0,A=A+d*t[g+1]|0,o=o+d*t[g]|0,g=g+4|0;e[p+3]=w(u+8192>>14),e[p+2]=w(s+8192>>14),e[p+1]=w(A+8192>>14),e[p]=w(o+8192>>14),p=p+4*r|0}p=4*(l+1)|0,m=(l+1)*i*4|0}},convolveVertically:function(t,e,i,r,n,a){var o,A,s,u,h,f,c,g,l,I,d,m=0,p=0;for(l=0;l<r;l++){for(I=h=0;I<n;I++){for(f=a[h++],c=a[h++],g=m+4*f|0,o=A=s=u=0;0<c;c--)u=u+(d=a[h++])*t[g+3]|0,s=s+d*t[g+2]|0,A=A+d*t[g+1]|0,o=o+d*t[g]|0,g=g+4|0;e[p+3]=w(u+8192>>14),e[p+2]=w(s+8192>>14),e[p+1]=w(A+8192>>14),e[p]=w(o+8192>>14),p=p+4*r|0}p=4*(l+1)|0,m=(l+1)*i*4|0}}}},{}],3:[function(t,e,i){"use strict";e.exports="AGFzbQEAAAABFAJgBn9/f39/fwBgB39/f39/f38AAg8BA2VudgZtZW1vcnkCAAEDAwIAAQQEAXAAAAcZAghjb252b2x2ZQAACmNvbnZvbHZlSFYAAQkBAArmAwLBAwEQfwJAIANFDQAgBEUNACAFQQRqIRVBACEMQQAhDQNAIA0hDkEAIRFBACEHA0AgB0ECaiESAn8gBSAHQQF0IgdqIgZBAmouAQAiEwRAQQAhCEEAIBNrIRQgFSAHaiEPIAAgDCAGLgEAakECdGohEEEAIQlBACEKQQAhCwNAIBAoAgAiB0EYdiAPLgEAIgZsIAtqIQsgB0H/AXEgBmwgCGohCCAHQRB2Qf8BcSAGbCAKaiEKIAdBCHZB/wFxIAZsIAlqIQkgD0ECaiEPIBBBBGohECAUQQFqIhQNAAsgEiATagwBC0EAIQtBACEKQQAhCUEAIQggEgshByABIA5BAnRqIApBgMAAakEOdSIGQf8BIAZB/wFIG0EQdEGAgPwHcUEAIAZBAEobIAtBgMAAakEOdSIGQf8BIAZB/wFIG0EYdEEAIAZBAEobciAJQYDAAGpBDnUiBkH/ASAGQf8BSBtBCHRBgP4DcUEAIAZBAEobciAIQYDAAGpBDnUiBkH/ASAGQf8BSBtB/wFxQQAgBkEAShtyNgIAIA4gA2ohDiARQQFqIhEgBEcNAAsgDCACaiEMIA1BAWoiDSADRw0ACwsLIQACQEEAIAIgAyAEIAUgABAAIAJBACAEIAUgBiABEAALCw=="},{}],4:[function(t,e,i){"use strict";e.exports={name:"resize",fn:t("./resize"),wasm_fn:t("./resize_wasm"),wasm_src:t("./convolve_wasm_base64")}},{"./convolve_wasm_base64":3,"./resize":5,"./resize_wasm":8}],5:[function(t,e,i){"use strict";var d=t("./resize_filter_gen"),m=t("./convolve").convolveHorizontally,p=t("./convolve").convolveVertically;e.exports=function(t){var e=t.src,i=t.width,r=t.height,n=t.toWidth,a=t.toHeight,o=t.scaleX||t.toWidth/t.width,A=t.scaleY||t.toHeight/t.height,s=t.offsetX||0,u=t.offsetY||0,h=t.dest||new Uint8Array(n*a*4),f=void 0===t.quality?3:t.quality,c=t.alpha||!1,g=d(f,i,n,o,s),l=d(f,r,a,A,u),I=new Uint8Array(n*r*4);return m(e,I,i,r,n,g),p(I,h,r,n,a,l),c||function(t,e,i){for(var r=3,n=e*i*4|0;r<n;)t[r]=255,r=r+4|0}(h,n,a),h}},{"./convolve":2,"./resize_filter_gen":6}],6:[function(t,e,i){"use strict";var M=t("./resize_filter_info"),r=14;function U(t){return Math.round(t*((1<<r)-1))}e.exports=function(t,e,i,r,n){var a,o,A,s,u,h,f,c,g,l,I,d,m,p,w,B,b,E=M[t].filter,_=1/r,y=Math.min(1,r),C=M[t].win/y,Q=Math.floor(2*(C+1)),v=new Int16Array((Q+2)*i),x=0,D=!v.subarray||!v.set;for(a=0;a<i;a++){for(o=(a+.5)*_+n,A=Math.max(0,Math.floor(o-C)),u=(s=Math.min(e-1,Math.ceil(o+C)))-A+1,h=new Float32Array(u),f=new Int16Array(u),g=A,l=c=0;g<=s;g++,l++)c+=I=E((g+.5-o)*y),h[l]=I;for(l=d=0;l<h.length;l++)d+=m=h[l]/c,f[l]=U(m);for(f[i>>1]+=U(1-d),p=0;p<f.length&&0===f[p];)p++;if(p<f.length){for(w=f.length-1;0<w&&0===f[w];)w--;if(B=A+p,b=w-p+1,v[x++]=B,v[x++]=b,D)for(l=p;l<=w;l++)v[x++]=f[l];else v.set(f.subarray(p,w+1),x),x+=b}else v[x++]=0,v[x++]=0}return v}},{"./resize_filter_info":7}],7:[function(t,e,i){"use strict";e.exports=[{win:.5,filter:function(t){return-.5<=t&&t<.5?1:0}},{win:1,filter:function(t){if(t<=-1||1<=t)return 0;if(-1.1920929e-7<t&&t<1.1920929e-7)return 1;var e=t*Math.PI;return Math.sin(e)/e*(.54+.46*Math.cos(e/1))}},{win:2,filter:function(t){if(t<=-2||2<=t)return 0;if(-1.1920929e-7<t&&t<1.1920929e-7)return 1;var e=t*Math.PI;return Math.sin(e)/e*Math.sin(e/2)/(e/2)}},{win:3,filter:function(t){if(t<=-3||3<=t)return 0;if(-1.1920929e-7<t&&t<1.1920929e-7)return 1;var e=t*Math.PI;return Math.sin(e)/e*Math.sin(e/3)/(e/3)}}]},{}],8:[function(t,e,i){"use strict";var _=t("./resize_filter_gen");var A=!0;try{A=1===new Uint32Array(new Uint8Array([1,0,0,0]).buffer)[0]}catch(t){}function y(t,e,i){if(A)e.set((r=t,new Uint8Array(r.buffer,0,r.byteLength)),i);else for(var r,n=i,a=0;a<t.length;a++){var o=t[a];e[n++]=255&o,e[n++]=o>>8&255}}e.exports=function(t){var e=t.src,i=t.width,r=t.height,n=t.toWidth,a=t.toHeight,o=t.scaleX||t.toWidth/t.width,A=t.scaleY||t.toHeight/t.height,s=t.offsetX||0,u=t.offsetY||0,h=t.dest||new Uint8Array(n*a*4),f=void 0===t.quality?3:t.quality,c=t.alpha||!1,g=_(f,i,n,o,s),l=_(f,r,a,A,u),I=this.__align(0+Math.max(e.byteLength,h.byteLength)),d=this.__align(I+r*n*4),m=this.__align(d+g.byteLength),p=m+l.byteLength,w=this.__instance("resize",p),B=new Uint8Array(this.__memory.buffer),b=new Uint32Array(this.__memory.buffer),E=new Uint32Array(e.buffer);return b.set(E),y(g,B,d),y(l,B,m),(w.exports.convolveHV||w.exports._convolveHV)(d,m,I,i,r,n,a),new Uint32Array(h.buffer).set(new Uint32Array(this.__memory.buffer,0,a*n)),c||function(t,e,i){for(var r=3,n=e*i*4|0;r<n;)t[r]=255,r=r+4|0}(h,n,a),h}},{"./resize_filter_gen":6}],9:[function(t,e,i){"use strict";function r(t,e){this.create=t,this.available=[],this.acquired={},this.lastId=1,this.timeoutId=0,this.idle=e||2e3}r.prototype.acquire=function(){var t,e=this;return 0!==this.available.length?t=this.available.pop():((t=this.create()).id=this.lastId++,t.release=function(){return e.release(t)}),this.acquired[t.id]=t},r.prototype.release=function(t){var e=this;delete this.acquired[t.id],t.lastUsed=Date.now(),this.available.push(t),0===this.timeoutId&&(this.timeoutId=setTimeout(function(){return e.gc()},100))},r.prototype.gc=function(){var e=this,i=Date.now();this.available=this.available.filter(function(t){return!(i-t.lastUsed>e.idle)||(t.destroy(),!1)}),0!==this.available.length?this.timeoutId=setTimeout(function(){return e.gc()},100):this.timeoutId=0},e.exports=r},{}],10:[function(t,e,i){"use strict";e.exports=function(t,e,i,r,n,a){var o=i/t,A=r/e,s=(2*a+2+1)/n;if(.5<s)return[[i,r]];var u=Math.ceil(Math.log(Math.min(o,A))/Math.log(s));if(u<=1)return[[i,r]];for(var h=[],f=0;f<u;f++){var c=Math.round(Math.pow(Math.pow(t,u-f-1)*Math.pow(i,f+1),1/u)),g=Math.round(Math.pow(Math.pow(e,u-f-1)*Math.pow(r,f+1),1/u));h.push([c,g])}return h}},{}],11:[function(t,e,i){"use strict";var r=1e-5;function g(t){var e=Math.round(t);return Math.abs(t-e)<r?e:Math.floor(t)}function l(t){var e=Math.round(t);return Math.abs(t-e)<r?e:Math.ceil(t)}e.exports=function(t){var e,i,r,n,a,o,A=t.toWidth/t.width,s=t.toHeight/t.height,u=g(t.srcTileSize*A)-2*t.destTileBorder,h=g(t.srcTileSize*s)-2*t.destTileBorder;if(u<1||h<1)throw new Error("Internal error in pica: target tile width/height is too small.");var f,c=[];for(n=0;n<t.toHeight;n+=h)for(r=0;r<t.toWidth;r+=u)(e=r-t.destTileBorder)<0&&(e=0),e+(a=r+u+t.destTileBorder-e)>=t.toWidth&&(a=t.toWidth-e),(i=n-t.destTileBorder)<0&&(i=0),i+(o=n+h+t.destTileBorder-i)>=t.toHeight&&(o=t.toHeight-i),f={toX:e,toY:i,toWidth:a,toHeight:o,toInnerX:r,toInnerY:n,toInnerWidth:u,toInnerHeight:h,offsetX:e/A-g(e/A),offsetY:i/s-g(i/s),scaleX:A,scaleY:s,x:g(e/A),y:g(i/s),width:l(a/A),height:l(o/s)},c.push(f);return c}},{}],12:[function(t,e,i){"use strict";function r(t){return Object.prototype.toString.call(t)}e.exports.isCanvas=function(t){var e=r(t);return"[object HTMLCanvasElement]"===e||"[object Canvas]"===e},e.exports.isImage=function(t){return"[object HTMLImageElement]"===r(t)},e.exports.limiter=function(t){var r=0,n=[];function a(){r<t&&n.length&&(r++,n.shift()())}return function(t){return new Promise(function(e,i){n.push(function(){t().then(function(t){e(t),r--,a()},function(t){i(t),r--,a()})}),a()})}},e.exports.cib_quality_name=function(t){switch(t){case 0:return"pixelated";case 1:return"low";case 2:return"medium"}return"high"},e.exports.cib_support=function(){return Promise.resolve().then(function(){if("undefined"==typeof createImageBitmap||"undefined"==typeof document)return!1;var i=document.createElement("canvas");return i.width=100,i.height=100,createImageBitmap(i,0,0,100,100,{resizeWidth:10,resizeHeight:10,resizeQuality:"high"}).then(function(t){var e=10===t.width;return t.close(),i=null,e})}).catch(function(){return!1})}},{}],13:[function(t,e,i){"use strict";e.exports=function(){var r,n=t("./mathlib");onmessage=function(t){var e=t.data.opts;r||(r=new n(t.data.features));var i=r.resizeAndUnsharp(e);postMessage({result:i},[i.buffer])}}},{"./mathlib":1}],14:[function(t,e,i){var A,s,u,h,f,c;function g(t,e,i,r,n,a){var o,A,s,u,h,f,c,g,l,I,d,m,p,w;for(l=0;l<a;l++){for(g=0,u=h=(o=t[f=(c=l)*n])*r[6],d=r[0],m=r[1],p=r[4],w=r[5],I=0;I<n;I++)s=(A=t[f])*d+o*m+u*p+h*w,h=u,u=s,o=A,i[g]=u,g++,f++;for(g--,c+=a*(n-1),u=h=(o=t[--f])*r[7],A=o,d=r[2],m=r[3],I=n-1;0<=I;I--)s=A*d+o*m+u*p+h*w,h=u,u=s,o=A,A=t[f],e[c]=i[g]+u,f--,g--,c-=a}}e.exports=function(t,e,i,r){if(r){var n=new Uint16Array(t.length),a=new Float32Array(Math.max(e,i)),o=function(t){t<.5&&(t=.5);var e=Math.exp(.527076)/t,i=Math.exp(-e),r=Math.exp(-2*e),n=(1-i)*(1-i)/(1+2*e*i-r);return s=(A=n)*(e-1)*i,u=n*(e+1)*i,h=-n*r,f=2*i,c=-r,new Float32Array([A,s,u,h,f,c,(A+s)/(1-f-c),(u+h)/(1-f-c)])}(r);g(t,n,a,o,e,i),g(n,t,a,o,i,e)}}},{}],15:[function(t,e,i){"function"==typeof Object.create?e.exports=function(t,e){t.super_=e,t.prototype=Object.create(e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}})}:e.exports=function(t,e){t.super_=e;var i=function(){};i.prototype=e.prototype,t.prototype=new i,t.prototype.constructor=t}},{}],16:[function(t,e,i){"use strict";var a=t("object-assign"),r=t("./lib/base64decode"),n=t("./lib/wa_detect"),o={js:!0,wasm:!0};function A(t){if(!(this instanceof A))return new A(t);var e=a({},o,t||{});if(this.options=e,this.__cache={},this.has_wasm=n(),this.__init_promise=null,this.__modules=e.modules||{},this.__memory=null,this.__wasm={},this.__isLE=1===new Uint32Array(new Uint8Array([1,0,0,0]).buffer)[0],!this.options.js&&!this.options.wasm)throw new Error('mathlib: at least "js" or "wasm" should be enabled')}A.prototype.use=function(t){return this.__modules[t.name]=t,this.has_wasm&&this.options.wasm&&t.wasm_fn?this[t.name]=t.wasm_fn:this[t.name]=t.fn,this},A.prototype.init=function(){if(this.__init_promise)return this.__init_promise;if(!this.options.js&&this.options.wasm&&!this.has_wasm)return Promise.reject(new Error('mathlib: only "wasm" was enabled, but it\'s not supported'));var i=this;return this.__init_promise=Promise.all(Object.keys(i.__modules).map(function(e){var t=i.__modules[e];return i.has_wasm&&i.options.wasm&&t.wasm_fn?i.__wasm[e]?null:WebAssembly.compile(i.__base64decode(t.wasm_src)).then(function(t){i.__wasm[e]=t}):null})).then(function(){return i}),this.__init_promise},A.prototype.__base64decode=r,A.prototype.__reallocate=function(t){if(!this.__memory)return this.__memory=new WebAssembly.Memory({initial:Math.ceil(t/65536)}),this.__memory;var e=this.__memory.buffer.byteLength;return e<t&&this.__memory.grow(Math.ceil((t-e)/65536)),this.__memory},A.prototype.__instance=function(t,e,i){if(e&&this.__reallocate(e),!this.__wasm[t]){var r=this.__modules[t];this.__wasm[t]=new WebAssembly.Module(this.__base64decode(r.wasm_src))}if(!this.__cache[t]){var n={memoryBase:0,memory:this.__memory,tableBase:0,table:new WebAssembly.Table({initial:0,element:"anyfunc"})};this.__cache[t]=new WebAssembly.Instance(this.__wasm[t],{env:a(n,i||{})})}return this.__cache[t]},A.prototype.__align=function(t,e){var i=t%(e=e||8);return t+(i?e-i:0)},e.exports=A},{"./lib/base64decode":17,"./lib/wa_detect":23,"object-assign":24}],17:[function(t,e,i){"use strict";e.exports=function(t){for(var e=t.replace(/[\r\n=]/g,""),i=e.length,r=new Uint8Array(3*i>>2),n=0,a=0,o=0;o<i;o++)o%4==0&&o&&(r[a++]=n>>16&255,r[a++]=n>>8&255,r[a++]=255&n),n=n<<6|"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".indexOf(e.charAt(o));var A=i%4*6;return 0===A?(r[a++]=n>>16&255,r[a++]=n>>8&255,r[a++]=255&n):18===A?(r[a++]=n>>10&255,r[a++]=n>>2&255):12===A&&(r[a++]=n>>4&255),r}},{}],18:[function(t,e,i){"use strict";e.exports=function(t,e,i){for(var r,n,a,o,A,s=e*i,u=new Uint16Array(s),h=0;h<s;h++)r=t[4*h],n=t[4*h+1],a=t[4*h+2],A=n<=r&&a<=r?r:a<=n&&r<=n?n:a,o=r<=n&&r<=a?r:n<=a&&n<=r?n:a,u[h]=257*(A+o)>>1;return u}},{}],19:[function(t,e,i){"use strict";e.exports={name:"unsharp_mask",fn:t("./unsharp_mask"),wasm_fn:t("./unsharp_mask_wasm"),wasm_src:t("./unsharp_mask_wasm_base64")}},{"./unsharp_mask":20,"./unsharp_mask_wasm":21,"./unsharp_mask_wasm_base64":22}],20:[function(t,e,i){"use strict";var C=t("glur/mono16"),Q=t("./hsl_l16");e.exports=function(t,e,i,r,n,a){var o,A,s,u,h,f,c,g,l,I,d,m,p;if(!(0===r||n<.5)){2<n&&(n=2);var w=Q(t,e,i),B=new Uint16Array(w);C(B,e,i,n);for(var b=r/100*4096+.5|0,E=257*a|0,_=e*i,y=0;y<_;y++)m=2*(w[y]-B[y]),Math.abs(m)>=E&&(o=t[p=4*y],A=t[p+1],s=t[p+2],f=257*((g=A<=o&&s<=o?o:o<=A&&s<=A?A:s)+(c=o<=A&&o<=s?o:A<=o&&A<=s?A:s))>>1,u=c===g?h=0:(h=f<=32767?4095*(g-c)/(g+c)|0:4095*(g-c)/(510-g-c)|0,o===g?65535*(A-s)/(6*(g-c))|0:A===g?21845+(65535*(s-o)/(6*(g-c))|0):43690+(65535*(o-A)/(6*(g-c))|0)),65535<(f+=b*m+2048>>12)?f=65535:f<0&&(f=0),0===h?o=A=s=f>>8:(l=2*f-(I=f<=32767?f*(4096+h)+2048>>12:f+((65535-f)*h+2048>>12))>>8,I>>=8,o=43690<=(d=u+21845&65535)?l:32767<=d?l+(6*(I-l)*(43690-d)+32768>>16):10922<=d?I:l+(6*(I-l)*d+32768>>16),A=43690<=(d=65535&u)?l:32767<=d?l+(6*(I-l)*(43690-d)+32768>>16):10922<=d?I:l+(6*(I-l)*d+32768>>16),s=43690<=(d=u-21845&65535)?l:32767<=d?l+(6*(I-l)*(43690-d)+32768>>16):10922<=d?I:l+(6*(I-l)*d+32768>>16)),t[p]=o,t[p+1]=A,t[p+2]=s)}}},{"./hsl_l16":18,"glur/mono16":14}],21:[function(t,e,i){"use strict";e.exports=function(t,e,i,r,n,a){if(!(0===r||n<.5)){2<n&&(n=2);var o=e*i,A=4*o,s=2*o,u=2*o,h=4*Math.max(e,i),f=A,c=f+s,g=c+u,l=g+u,I=l+h,d=this.__instance("unsharp_mask",A+s+2*u+h+32,{exp:Math.exp}),m=new Uint32Array(t.buffer);new Uint32Array(this.__memory.buffer).set(m);var p=d.exports.hsl_l16||d.exports._hsl_l16;p(0,f,e,i),(p=d.exports.blurMono16||d.exports._blurMono16)(f,c,g,l,I,e,i,n),(p=d.exports.unsharp||d.exports._unsharp)(0,0,f,c,e,i,r,a),m.set(new Uint32Array(this.__memory.buffer,0,o))}}},{}],22:[function(t,e,i){"use strict";e.exports="AGFzbQEAAAABMQZgAXwBfGACfX8AYAZ/f39/f38AYAh/f39/f39/fQBgBH9/f38AYAh/f39/f39/fwACGQIDZW52A2V4cAAAA2VudgZtZW1vcnkCAAEDBgUBAgMEBQQEAXAAAAdMBRZfX2J1aWxkX2dhdXNzaWFuX2NvZWZzAAEOX19nYXVzczE2X2xpbmUAAgpibHVyTW9ubzE2AAMHaHNsX2wxNgAEB3Vuc2hhcnAABQkBAAqJEAXZAQEGfAJAIAFE24a6Q4Ia+z8gALujIgOaEAAiBCAEoCIGtjgCECABIANEAAAAAAAAAMCiEAAiBbaMOAIUIAFEAAAAAAAA8D8gBKEiAiACoiAEIAMgA6CiRAAAAAAAAPA/oCAFoaMiArY4AgAgASAEIANEAAAAAAAA8L+gIAKioiIHtjgCBCABIAQgA0QAAAAAAADwP6AgAqKiIgO2OAIIIAEgBSACoiIEtow4AgwgASACIAegIAVEAAAAAAAA8D8gBqGgIgKjtjgCGCABIAMgBKEgAqO2OAIcCwu3AwMDfwR9CHwCQCADKgIUIQkgAyoCECEKIAMqAgwhCyADKgIIIQwCQCAEQX9qIgdBAEgiCA0AIAIgAC8BALgiDSADKgIYu6IiDiAJuyIQoiAOIAq7IhGiIA0gAyoCBLsiEqIgAyoCALsiEyANoqCgoCIPtjgCACACQQRqIQIgAEECaiEAIAdFDQAgBCEGA0AgAiAOIBCiIA8iDiARoiANIBKiIBMgAC8BALgiDaKgoKAiD7Y4AgAgAkEEaiECIABBAmohACAGQX9qIgZBAUoNAAsLAkAgCA0AIAEgByAFbEEBdGogAEF+ai8BACIIuCINIAu7IhGiIA0gDLsiEqKgIA0gAyoCHLuiIg4gCrsiE6KgIA4gCbsiFKKgIg8gAkF8aioCALugqzsBACAHRQ0AIAJBeGohAiAAQXxqIQBBACAFQQF0ayEHIAEgBSAEQQF0QXxqbGohBgNAIAghAyAALwEAIQggBiANIBGiIAO4Ig0gEqKgIA8iECAToqAgDiAUoqAiDyACKgIAu6CrOwEAIAYgB2ohBiAAQX5qIQAgAkF8aiECIBAhDiAEQX9qIgRBAUoNAAsLCwvfAgIDfwZ8AkAgB0MAAAAAWw0AIARE24a6Q4Ia+z8gB0MAAAA/l7ujIgyaEAAiDSANoCIPtjgCECAEIAxEAAAAAAAAAMCiEAAiDraMOAIUIAREAAAAAAAA8D8gDaEiCyALoiANIAwgDKCiRAAAAAAAAPA/oCAOoaMiC7Y4AgAgBCANIAxEAAAAAAAA8L+gIAuioiIQtjgCBCAEIA0gDEQAAAAAAADwP6AgC6KiIgy2OAIIIAQgDiALoiINtow4AgwgBCALIBCgIA5EAAAAAAAA8D8gD6GgIgujtjgCGCAEIAwgDaEgC6O2OAIcIAYEQCAFQQF0IQogBiEJIAIhCANAIAAgCCADIAQgBSAGEAIgACAKaiEAIAhBAmohCCAJQX9qIgkNAAsLIAVFDQAgBkEBdCEIIAUhAANAIAIgASADIAQgBiAFEAIgAiAIaiECIAFBAmohASAAQX9qIgANAAsLC7wBAQV/IAMgAmwiAwRAQQAgA2shBgNAIAAoAgAiBEEIdiIHQf8BcSECAn8gBEH/AXEiAyAEQRB2IgRB/wFxIgVPBEAgAyIIIAMgAk8NARoLIAQgBCAHIAIgA0kbIAIgBUkbQf8BcQshCAJAIAMgAk0EQCADIAVNDQELIAQgByAEIAMgAk8bIAIgBUsbQf8BcSEDCyAAQQRqIQAgASADIAhqQYECbEEBdjsBACABQQJqIQEgBkEBaiIGDQALCwvTBgEKfwJAIAazQwAAgEWUQwAAyEKVu0QAAAAAAADgP6CqIQ0gBSAEbCILBEAgB0GBAmwhDgNAQQAgAi8BACADLwEAayIGQQF0IgdrIAcgBkEASBsgDk8EQCAAQQJqLQAAIQUCfyAALQAAIgYgAEEBai0AACIESSIJRQRAIAYiCCAGIAVPDQEaCyAFIAUgBCAEIAVJGyAGIARLGwshCAJ/IAYgBE0EQCAGIgogBiAFTQ0BGgsgBSAFIAQgBCAFSxsgCRsLIgogCGoiD0GBAmwiEEEBdiERQQAhDAJ/QQAiCSAIIApGDQAaIAggCmsiCUH/H2wgD0H+AyAIayAKayAQQYCABEkbbSEMIAYgCEYEQCAEIAVrQf//A2wgCUEGbG0MAQsgBSAGayAGIARrIAQgCEYiBhtB//8DbCAJQQZsbUHVqgFBqtUCIAYbagshCSARIAcgDWxBgBBqQQx1aiIGQQAgBkEAShsiBkH//wMgBkH//wNIGyEGAkACfwJAIAxB//8DcSIFBEAgBkH//wFKDQEgBUGAIGogBmxBgBBqQQx2DAILIAZBCHYiBiEFIAYhBAwCCyAFIAZB//8Dc2xBgBBqQQx2IAZqCyIFQQh2IQcgBkEBdCAFa0EIdiIGIQQCQCAJQdWqAWpB//8DcSIFQanVAksNACAFQf//AU8EQEGq1QIgBWsgByAGa2xBBmxBgIACakEQdiAGaiEEDAELIAchBCAFQanVAEsNACAFIAcgBmtsQQZsQYCAAmpBEHYgBmohBAsCfyAGIgUgCUH//wNxIghBqdUCSw0AGkGq1QIgCGsgByAGa2xBBmxBgIACakEQdiAGaiAIQf//AU8NABogByIFIAhBqdUASw0AGiAIIAcgBmtsQQZsQYCAAmpBEHYgBmoLIQUgCUGr1QJqQf//A3EiCEGp1QJLDQAgCEH//wFPBEBBqtUCIAhrIAcgBmtsQQZsQYCAAmpBEHYgBmohBgwBCyAIQanVAEsEQCAHIQYMAQsgCCAHIAZrbEEGbEGAgAJqQRB2IAZqIQYLIAEgBDoAACABQQFqIAU6AAAgAUECaiAGOgAACyADQQJqIQMgAkECaiECIABBBGohACABQQRqIQEgC0F/aiILDQALCwsL"},{}],23:[function(t,e,i){"use strict";var r;e.exports=function(){if(void 0!==r)return r;if(r=!1,"undefined"==typeof WebAssembly)return r;try{var t=new Uint8Array([0,97,115,109,1,0,0,0,1,6,1,96,1,127,1,127,3,2,1,0,5,3,1,0,1,7,8,1,4,116,101,115,116,0,0,10,16,1,14,0,32,0,65,1,54,2,0,32,0,40,2,0,11]),e=new WebAssembly.Module(t);return 0!==new WebAssembly.Instance(e,{}).exports.test(4)&&(r=!0),r}catch(t){}return r}},{}],24:[function(t,e,i){"use strict";var s=Object.getOwnPropertySymbols,u=Object.prototype.hasOwnProperty,h=Object.prototype.propertyIsEnumerable;e.exports=function(){try{if(!Object.assign)return!1;var t=new String("abc");if(t[5]="de","5"===Object.getOwnPropertyNames(t)[0])return!1;for(var e={},i=0;i<10;i++)e["_"+String.fromCharCode(i)]=i;if("0123456789"!==Object.getOwnPropertyNames(e).map(function(t){return e[t]}).join(""))return!1;var r={};return"abcdefghijklmnopqrst".split("").forEach(function(t){r[t]=t}),"abcdefghijklmnopqrst"===Object.keys(Object.assign({},r)).join("")}catch(t){return!1}}()?Object.assign:function(t,e){for(var i,r,n=function(t){if(null==t)throw new TypeError("Object.assign cannot be called with null or undefined");return Object(t)}(t),a=1;a<arguments.length;a++){for(var o in i=Object(arguments[a]))u.call(i,o)&&(n[o]=i[o]);if(s){r=s(i);for(var A=0;A<r.length;A++)h.call(i,r[A])&&(n[r[A]]=i[r[A]])}}return n}},{}],25:[function(t,e,i){var m=arguments[3],p=arguments[4],w=arguments[5],B=JSON.stringify;e.exports=function(t,e){for(var i,r=Object.keys(w),n=0,a=r.length;n<a;n++){var o=r[n],A=w[o].exports;if(A===t||A&&A.default===t){i=o;break}}if(!i){i=Math.floor(Math.pow(16,8)*Math.random()).toString(16);var s={};for(n=0,a=r.length;n<a;n++){s[o=r[n]]=o}p[i]=["function(require,module,exports){"+t+"(self); }",s]}var u=Math.floor(Math.pow(16,8)*Math.random()).toString(16),h={};h[i]=i,p[u]=["function(require,module,exports){var f = require("+B(i)+");(f.default ? f.default : f)(self);}",h];var f={};!function t(e){f[e]=!0;for(var i in p[e][1]){var r=p[e][1][i];f[r]||t(r)}}(u);var c="("+m+")({"+Object.keys(f).map(function(t){return B(t)+":["+p[t][0]+","+B(p[t][1])+"]"}).join(",")+"},{},["+B(u)+"])",g=window.URL||window.webkitURL||window.mozURL||window.msURL,l=new Blob([c],{type:"text/javascript"});if(e&&e.bare)return l;var I=g.createObjectURL(l),d=new Worker(I);return d.objectURL=I,d}},{}],"/":[function(a,t,e){"use strict";function d(t,e){return function(t){if(Array.isArray(t))return t}(t)||function(t,e){var i=[],r=!0,n=!1,a=void 0;try{for(var o,A=t[Symbol.iterator]();!(r=(o=A.next()).done)&&(i.push(o.value),!e||i.length!==e);r=!0);}catch(t){n=!0,a=t}finally{try{r||null==A.return||A.return()}finally{if(n)throw a}}return i}(t,e)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance")}()}var m=a("object-assign"),i=a("webworkify"),o=a("./lib/mathlib"),A=a("./lib/pool"),p=a("./lib/utils"),r=a("./lib/worker"),s=a("./lib/stepper"),w=a("./lib/tiler"),u={},B=!1;try{"undefined"!=typeof navigator&&navigator.userAgent&&(B=0<=navigator.userAgent.indexOf("Safari"))}catch(t){}var n=1;"undefined"!=typeof navigator&&(n=Math.min(navigator.hardwareConcurrency||1,4));var b,E,h={tile:1024,concurrency:n,features:["js","wasm","ww"],idle:2e3},f={quality:3,alpha:!1,unsharpAmount:0,unsharpRadius:0,unsharpThreshold:0};function c(){return{value:i(r),destroy:function(){if(this.value.terminate(),"undefined"!=typeof window){var t=window.URL||window.webkitURL||window.mozURL||window.msURL;t&&t.revokeObjectURL&&this.value.objectURL&&t.revokeObjectURL(this.value.objectURL)}}}}function g(t){if(!(this instanceof g))return new g(t);this.options=m({},h,t||{});var e="lk_".concat(this.options.concurrency);this.__limit=u[e]||p.limiter(this.options.concurrency),u[e]||(u[e]=this.__limit),this.features={js:!1,wasm:!1,cib:!1,ww:!1},this.__workersPool=null,this.__requested_features=[],this.__mathlib=null}g.prototype.init=function(){var e=this;if(this.__initPromise)return this.__initPromise;if(!1!==b&&!0!==b&&(b=!1,"undefined"!=typeof ImageData&&"undefined"!=typeof Uint8ClampedArray))try{new ImageData(new Uint8ClampedArray(400),10,10),b=!0}catch(t){}!1!==E&&!0!==E&&(E=!1,"undefined"!=typeof ImageBitmap&&(ImageBitmap.prototype&&ImageBitmap.prototype.close?E=!0:this.debug("ImageBitmap does not support .close(), disabled")));var i=this.options.features.slice();if(0<=i.indexOf("all")&&(i=["cib","wasm","js","ww"]),this.__requested_features=i,this.__mathlib=new o(i),0<=i.indexOf("ww")&&"undefined"!=typeof window&&"Worker"in window)try{a("webworkify")(function(){}).terminate(),this.features.ww=!0;var t="wp_".concat(JSON.stringify(this.options));u[t]?this.__workersPool=u[t]:(this.__workersPool=new A(c,this.options.idle),u[t]=this.__workersPool)}catch(t){}var r,n=this.__mathlib.init().then(function(t){m(e.features,t.features)});return r=E?p.cib_support().then(function(t){e.features.cib&&i.indexOf("cib")<0?e.debug("createImageBitmap() resize supported, but disabled by config"):0<=i.indexOf("cib")&&(e.features.cib=t)}):Promise.resolve(!1),this.__initPromise=Promise.all([n,r]).then(function(){return e}),this.__initPromise},g.prototype.resize=function(t,a,e){var c=this;this.debug("Start resize...");var o=m({},f);if(isNaN(e)?e&&(o=m(o,e)):o=m(o,{quality:e}),o.toWidth=a.width,o.toHeight=a.height,o.width=t.naturalWidth||t.width,o.height=t.naturalHeight||t.height,0===a.width||0===a.height)return Promise.reject(new Error("Invalid output size: ".concat(a.width,"x").concat(a.height)));2<o.unsharpRadius&&(o.unsharpRadius=2);var g=!1,l=null;o.cancelToken&&(l=o.cancelToken.then(function(t){throw g=!0,t},function(t){throw g=!0,t}));var I=Math.ceil(Math.max(3,2.5*o.unsharpRadius|0));return this.init().then(function(){if(g)return l;if(c.features.cib){var n=a.getContext("2d",{alpha:Boolean(o.alpha)});return c.debug("Resize via createImageBitmap()"),createImageBitmap(t,{resizeWidth:o.toWidth,resizeHeight:o.toHeight,resizeQuality:p.cib_quality_name(o.quality)}).then(function(t){if(g)return l;if(!o.unsharpAmount)return n.drawImage(t,0,0),t.close(),n=null,c.debug("Finished!"),a;c.debug("Unsharp result");var e=document.createElement("canvas");e.width=o.toWidth,e.height=o.toHeight;var i=e.getContext("2d",{alpha:Boolean(o.alpha)});i.drawImage(t,0,0),t.close();var r=i.getImageData(0,0,o.toWidth,o.toHeight);return c.__mathlib.unsharp(r.data,o.toWidth,o.toHeight,o.unsharpAmount,o.unsharpRadius,o.unsharpThreshold),n.putImageData(r,0,0),r=i=e=n=null,c.debug("Finished!"),a})}var h={},f=function(a,i,o){var A,s,u,r=function(n){return c.__limit(function(){if(g)return l;var r;if(p.isCanvas(a))c.debug("Get tile pixel data"),r=A.getImageData(n.x,n.y,n.width,n.height);else{c.debug("Draw tile imageBitmap/image to temporary canvas");var t=document.createElement("canvas");t.width=n.width,t.height=n.height;var e=t.getContext("2d",{alpha:Boolean(o.alpha)});e.globalCompositeOperation="copy",e.drawImage(s||a,n.x,n.y,n.width,n.height,0,0,n.width,n.height),c.debug("Get tile pixel data"),r=e.getImageData(0,0,n.width,n.height),e=t=null}var i={src:r.data,width:n.width,height:n.height,toWidth:n.toWidth,toHeight:n.toHeight,scaleX:n.scaleX,scaleY:n.scaleY,offsetX:n.offsetX,offsetY:n.offsetY,quality:o.quality,alpha:o.alpha,unsharpAmount:o.unsharpAmount,unsharpRadius:o.unsharpRadius,unsharpThreshold:o.unsharpThreshold};return c.debug("Invoke resize math"),Promise.resolve().then(function(){return t=i,Promise.resolve().then(function(){return c.features.ww?new Promise(function(e,i){var r=c.__workersPool.acquire();l&&l.catch(function(t){return i(t)}),r.value.onmessage=function(t){r.release(),t.data.err?i(t.data.err):e(t.data.result)},r.value.postMessage({opts:t,features:c.__requested_features,preload:{wasm_nodule:c.__mathlib.__}},[t.src.buffer])}):c.__mathlib.resizeAndUnsharp(t,h)});var t}).then(function(t){if(g)return l;var e;if(r=null,c.debug("Convert raw rgba tile result to ImageData"),b)e=new ImageData(new Uint8ClampedArray(t),n.toWidth,n.toHeight);else if((e=u.createImageData(n.toWidth,n.toHeight)).data.set)e.data.set(t);else for(var i=e.data.length-1;0<=i;i--)e.data[i]=t[i];return c.debug("Draw tile"),B?u.putImageData(e,n.toX,n.toY,n.toInnerX-n.toX,n.toInnerY-n.toY,n.toInnerWidth+1e-5,n.toInnerHeight+1e-5):u.putImageData(e,n.toX,n.toY,n.toInnerX-n.toX,n.toInnerY-n.toY,n.toInnerWidth,n.toInnerHeight),null})})};return Promise.resolve().then(function(){if(u=i.getContext("2d",{alpha:Boolean(o.alpha)}),p.isCanvas(a))return A=a.getContext("2d",{alpha:Boolean(o.alpha)}),null;if(p.isImage(a))return E?(c.debug("Decode image via createImageBitmap"),createImageBitmap(a).then(function(t){s=t})):null;throw new Error('".from" should be image or canvas')}).then(function(){if(g)return l;c.debug("Calculate tiles");var t=w({width:o.width,height:o.height,srcTileSize:c.options.tile,toWidth:o.toWidth,toHeight:o.toHeight,destTileBorder:I}).map(function(t){return r(t)});function e(){s&&(s.close(),s=null)}return c.debug("Process tiles"),Promise.all(t).then(function(){return c.debug("Finished!"),e(),i},function(t){throw e(),t})})};return function t(e,i,r,n){if(g)return l;var a,o=d(e.shift(),2),A=o[0],s=o[1],u=0===e.length;return n=m({},n,{toWidth:A,toHeight:s,quality:u?n.quality:Math.min(1,n.quality)}),u||((a=document.createElement("canvas")).width=A,a.height=s),f(i,u?r:a,n).then(function(){return u?r:(n.width=A,n.height=s,t(e,a,r,n))})}(s(o.width,o.height,o.toWidth,o.toHeight,c.options.tile,I),t,a,o)})},g.prototype.resizeBuffer=function(t){var e=this,i=m({},f,t);return this.init().then(function(){return e.__mathlib.resizeAndUnsharp(i)})},g.prototype.toBlob=function(a,o,A){return o=o||"image/png",new Promise(function(e){if(a.toBlob)a.toBlob(function(t){return e(t)},o,A);else{for(var t=atob(a.toDataURL(o,A).split(",")[1]),i=t.length,r=new Uint8Array(i),n=0;n<i;n++)r[n]=t.charCodeAt(n);e(new Blob([r],{type:o}))}})},g.prototype.debug=function(){},t.exports=g},{"./lib/mathlib":1,"./lib/pool":9,"./lib/stepper":10,"./lib/tiler":11,"./lib/utils":12,"./lib/worker":13,"object-assign":24,webworkify:25}]},{},[])("/")});

/* Modernizr 2.7.1 (Custom Build) | MIT & BSD
 * Build: http://modernizr.com/download/#-flexbox-flexboxlegacy-multiplebgs-opacity-rgba-textshadow-cssanimations-csscolumns-generatedcontent-csstransforms-csstransforms3d-csstransitions-applicationcache-canvas-history-audio-video-localstorage-postmessage-sessionstorage-websockets-webworkers-geolocation-svg-touch-webgl-printshiv-cssclasses-prefixed-teststyles-testprop-testallprops-prefixes-domprefixes-load-cssclassprefix:modernizr!
 */
;window.Modernizr=function(a,b,c){function B(a){j.cssText=a}function C(a,b){return B(n.join(a+";")+(b||""))}function D(a,b){return typeof a===b}function E(a,b){return!!~(""+a).indexOf(b)}function F(a,b){for(var d in a){var e=a[d];if(!E(e,"-")&&j[e]!==c)return b=="pfx"?e:!0}return!1}function G(a,b,d){for(var e in a){var f=b[a[e]];if(f!==c)return d===!1?a[e]:D(f,"function")?f.bind(d||b):f}return!1}function H(a,b,c){var d=a.charAt(0).toUpperCase()+a.slice(1),e=(a+" "+p.join(d+" ")+d).split(" ");return D(b,"string")||D(b,"undefined")?F(e,b):(e=(a+" "+q.join(d+" ")+d).split(" "),G(e,b,c))}var d="2.7.1",e={},f=!0,g=b.documentElement,h="modernizr",i=b.createElement(h),j=i.style,k,l=":)",m={}.toString,n=" -webkit- -moz- -o- -ms- ".split(" "),o="Webkit Moz O ms",p=o.split(" "),q=o.toLowerCase().split(" "),r={svg:"http://www.w3.org/2000/svg"},s={},t={},u={},v=[],w=v.slice,x,y=function(a,c,d,e){var f,i,j,k,l=b.createElement("div"),m=b.body,n=m||b.createElement("body");if(parseInt(d,10))while(d--)j=b.createElement("div"),j.id=e?e[d]:h+(d+1),l.appendChild(j);return f=["&#173;",'<style id="s',h,'">',a,"</style>"].join(""),l.id=h,(m?l:n).innerHTML+=f,n.appendChild(l),m||(n.style.background="",n.style.overflow="hidden",k=g.style.overflow,g.style.overflow="hidden",g.appendChild(n)),i=c(l,a),m?l.parentNode.removeChild(l):(n.parentNode.removeChild(n),g.style.overflow=k),!!i},z={}.hasOwnProperty,A;!D(z,"undefined")&&!D(z.call,"undefined")?A=function(a,b){return z.call(a,b)}:A=function(a,b){return b in a&&D(a.constructor.prototype[b],"undefined")},Function.prototype.bind||(Function.prototype.bind=function(b){var c=this;if(typeof c!="function")throw new TypeError;var d=w.call(arguments,1),e=function(){if(this instanceof e){var a=function(){};a.prototype=c.prototype;var f=new a,g=c.apply(f,d.concat(w.call(arguments)));return Object(g)===g?g:f}return c.apply(b,d.concat(w.call(arguments)))};return e}),s.flexbox=function(){return H("flexWrap")},s.flexboxlegacy=function(){return H("boxDirection")},s.canvas=function(){var a=b.createElement("canvas");return!!a.getContext&&!!a.getContext("2d")},s.webgl=function(){return!!a.WebGLRenderingContext},s.touch=function(){var c;return"ontouchstart"in a||a.DocumentTouch&&b instanceof DocumentTouch?c=!0:y(["@media (",n.join("touch-enabled),("),h,")","{#modernizr{top:9px;position:absolute}}"].join(""),function(a){c=a.offsetTop===9}),c},s.geolocation=function(){return"geolocation"in navigator},s.postmessage=function(){return!!a.postMessage},s.history=function(){return!!a.history&&!!history.pushState},s.websockets=function(){return"WebSocket"in a||"MozWebSocket"in a},s.rgba=function(){return B("background-color:rgba(150,255,150,.5)"),E(j.backgroundColor,"rgba")},s.multiplebgs=function(){return B("background:url(https://),url(https://),red url(https://)"),/(url\s*\(.*?){3}/.test(j.background)},s.textshadow=function(){return b.createElement("div").style.textShadow===""},s.opacity=function(){return C("opacity:.55"),/^0.55$/.test(j.opacity)},s.cssanimations=function(){return H("animationName")},s.csscolumns=function(){return H("columnCount")},s.csstransforms=function(){return!!H("transform")},s.csstransforms3d=function(){var a=!!H("perspective");return a&&"webkitPerspective"in g.style&&y("@media (transform-3d),(-webkit-transform-3d){#modernizr{left:9px;position:absolute;height:3px;}}",function(b,c){a=b.offsetLeft===9&&b.offsetHeight===3}),a},s.csstransitions=function(){return H("transition")},s.generatedcontent=function(){var a;return y(["#",h,"{font:0/0 a}#",h,':after{content:"',l,'";visibility:hidden;font:3px/1 a}'].join(""),function(b){a=b.offsetHeight>=3}),a},s.video=function(){var a=b.createElement("video"),c=!1;try{if(c=!!a.canPlayType)c=new Boolean(c),c.ogg=a.canPlayType('video/ogg; codecs="theora"').replace(/^no$/,""),c.h264=a.canPlayType('video/mp4; codecs="avc1.42E01E"').replace(/^no$/,""),c.webm=a.canPlayType('video/webm; codecs="vp8, vorbis"').replace(/^no$/,"")}catch(d){}return c},s.audio=function(){var a=b.createElement("audio"),c=!1;try{if(c=!!a.canPlayType)c=new Boolean(c),c.ogg=a.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,""),c.mp3=a.canPlayType("audio/mpeg;").replace(/^no$/,""),c.wav=a.canPlayType('audio/wav; codecs="1"').replace(/^no$/,""),c.m4a=(a.canPlayType("audio/x-m4a;")||a.canPlayType("audio/aac;")).replace(/^no$/,"")}catch(d){}return c},s.localstorage=function(){try{return localStorage.setItem(h,h),localStorage.removeItem(h),!0}catch(a){return!1}},s.sessionstorage=function(){try{return sessionStorage.setItem(h,h),sessionStorage.removeItem(h),!0}catch(a){return!1}},s.webworkers=function(){return!!a.Worker},s.applicationcache=function(){return!!a.applicationCache},s.svg=function(){return!!b.createElementNS&&!!b.createElementNS(r.svg,"svg").createSVGRect};for(var I in s)A(s,I)&&(x=I.toLowerCase(),e[x]=s[I](),v.push((e[x]?"":"no-")+x));return e.addTest=function(a,b){if(typeof a=="object")for(var d in a)A(a,d)&&e.addTest(d,a[d]);else{a=a.toLowerCase();if(e[a]!==c)return e;b=typeof b=="function"?b():b,typeof f!="undefined"&&f&&(g.className+=" modernizr-"+(b?"":"no-")+a),e[a]=b}return e},B(""),i=k=null,e._version=d,e._prefixes=n,e._domPrefixes=q,e._cssomPrefixes=p,e.testProp=function(a){return F([a])},e.testAllProps=H,e.testStyles=y,e.prefixed=function(a,b,c){return b?H(a,b,c):H(a,"pfx")},g.className=g.className.replace(/(^|\s)no-js(\s|$)/,"$1$2")+(f?" modernizr-js modernizr-"+v.join(" modernizr-"):""),e}(this,this.document),function(a,b){function l(a,b){var c=a.createElement("p"),d=a.getElementsByTagName("head")[0]||a.documentElement;return c.innerHTML="x<style>"+b+"</style>",d.insertBefore(c.lastChild,d.firstChild)}function m(){var a=s.elements;return typeof a=="string"?a.split(" "):a}function n(a){var b=j[a[h]];return b||(b={},i++,a[h]=i,j[i]=b),b}function o(a,c,d){c||(c=b);if(k)return c.createElement(a);d||(d=n(c));var g;return d.cache[a]?g=d.cache[a].cloneNode():f.test(a)?g=(d.cache[a]=d.createElem(a)).cloneNode():g=d.createElem(a),g.canHaveChildren&&!e.test(a)&&!g.tagUrn?d.frag.appendChild(g):g}function p(a,c){a||(a=b);if(k)return a.createDocumentFragment();c=c||n(a);var d=c.frag.cloneNode(),e=0,f=m(),g=f.length;for(;e<g;e++)d.createElement(f[e]);return d}function q(a,b){b.cache||(b.cache={},b.createElem=a.createElement,b.createFrag=a.createDocumentFragment,b.frag=b.createFrag()),a.createElement=function(c){return s.shivMethods?o(c,a,b):b.createElem(c)},a.createDocumentFragment=Function("h,f","return function(){var n=f.cloneNode(),c=n.createElement;h.shivMethods&&("+m().join().replace(/\w+/g,function(a){return b.createElem(a),b.frag.createElement(a),'c("'+a+'")'})+");return n}")(s,b.frag)}function r(a){a||(a=b);var c=n(a);return s.shivCSS&&!g&&!c.hasCSS&&(c.hasCSS=!!l(a,"article,aside,dialog,figcaption,figure,footer,header,hgroup,main,nav,section{display:block}mark{background:#FF0;color:#000}template{display:none}")),k||q(a,c),a}function w(a){var b,c=a.getElementsByTagName("*"),d=c.length,e=RegExp("^(?:"+m().join("|")+")$","i"),f=[];while(d--)b=c[d],e.test(b.nodeName)&&f.push(b.applyElement(x(b)));return f}function x(a){var b,c=a.attributes,d=c.length,e=a.ownerDocument.createElement(u+":"+a.nodeName);while(d--)b=c[d],b.specified&&e.setAttribute(b.nodeName,b.nodeValue);return e.style.cssText=a.style.cssText,e}function y(a){var b,c=a.split("{"),d=c.length,e=RegExp("(^|[\\s,>+~])("+m().join("|")+")(?=[[\\s,>+~#.:]|$)","gi"),f="$1"+u+"\\:$2";while(d--)b=c[d]=c[d].split("}"),b[b.length-1]=b[b.length-1].replace(e,f),c[d]=b.join("}");return c.join("{")}function z(a){var b=a.length;while(b--)a[b].removeNode()}function A(a){function g(){clearTimeout(d._removeSheetTimer),b&&b.removeNode(!0),b=null}var b,c,d=n(a),e=a.namespaces,f=a.parentWindow;return!v||a.printShived?a:(typeof e[u]=="undefined"&&e.add(u),f.attachEvent("onbeforeprint",function(){g();var d,e,f,h=a.styleSheets,i=[],j=h.length,k=Array(j);while(j--)k[j]=h[j];while(f=k.pop())if(!f.disabled&&t.test(f.media)){try{d=f.imports,e=d.length}catch(m){e=0}for(j=0;j<e;j++)k.push(d[j]);try{i.push(f.cssText)}catch(m){}}i=y(i.reverse().join("")),c=w(a),b=l(a,i)}),f.attachEvent("onafterprint",function(){z(c),clearTimeout(d._removeSheetTimer),d._removeSheetTimer=setTimeout(g,500)}),a.printShived=!0,a)}var c="3.7.0",d=a.html5||{},e=/^<|^(?:button|map|select|textarea|object|iframe|option|optgroup)$/i,f=/^(?:a|b|code|div|fieldset|h1|h2|h3|h4|h5|h6|i|label|li|ol|p|q|span|strong|style|table|tbody|td|th|tr|ul)$/i,g,h="_html5shiv",i=0,j={},k;(function(){try{var a=b.createElement("a");a.innerHTML="<xyz></xyz>",g="hidden"in a,k=a.childNodes.length==1||function(){b.createElement("a");var a=b.createDocumentFragment();return typeof a.cloneNode=="undefined"||typeof a.createDocumentFragment=="undefined"||typeof a.createElement=="undefined"}()}catch(c){g=!0,k=!0}})();var s={elements:d.elements||"abbr article aside audio bdi canvas data datalist details dialog figcaption figure footer header hgroup main mark meter nav output progress section summary template time video",version:c,shivCSS:d.shivCSS!==!1,supportsUnknownElements:k,shivMethods:d.shivMethods!==!1,type:"default",shivDocument:r,createElement:o,createDocumentFragment:p};a.html5=s,r(b);var t=/^$|\b(?:all|print)\b/,u="html5shiv",v=!k&&function(){var c=b.documentElement;return typeof b.namespaces!="undefined"&&typeof b.parentWindow!="undefined"&&typeof c.applyElement!="undefined"&&typeof c.removeNode!="undefined"&&typeof a.attachEvent!="undefined"}();s.type+=" print",s.shivPrint=A,A(b)}(this,document),function(a,b,c){function d(a){return"[object Function]"==o.call(a)}function e(a){return"string"==typeof a}function f(){}function g(a){return!a||"loaded"==a||"complete"==a||"uninitialized"==a}function h(){var a=p.shift();q=1,a?a.t?m(function(){("c"==a.t?B.injectCss:B.injectJs)(a.s,0,a.a,a.x,a.e,1)},0):(a(),h()):q=0}function i(a,c,d,e,f,i,j){function k(b){if(!o&&g(l.readyState)&&(u.r=o=1,!q&&h(),l.onload=l.onreadystatechange=null,b)){"img"!=a&&m(function(){t.removeChild(l)},50);for(var d in y[c])y[c].hasOwnProperty(d)&&y[c][d].onload()}}var j=j||B.errorTimeout,l=b.createElement(a),o=0,r=0,u={t:d,s:c,e:f,a:i,x:j};1===y[c]&&(r=1,y[c]=[]),"object"==a?l.data=c:(l.src=c,l.type=a),l.width=l.height="0",l.onerror=l.onload=l.onreadystatechange=function(){k.call(this,r)},p.splice(e,0,u),"img"!=a&&(r||2===y[c]?(t.insertBefore(l,s?null:n),m(k,j)):y[c].push(l))}function j(a,b,c,d,f){return q=0,b=b||"j",e(a)?i("c"==b?v:u,a,b,this.i++,c,d,f):(p.splice(this.i++,0,a),1==p.length&&h()),this}function k(){var a=B;return a.loader={load:j,i:0},a}var l=b.documentElement,m=a.setTimeout,n=b.getElementsByTagName("script")[0],o={}.toString,p=[],q=0,r="MozAppearance"in l.style,s=r&&!!b.createRange().compareNode,t=s?l:n.parentNode,l=a.opera&&"[object Opera]"==o.call(a.opera),l=!!b.attachEvent&&!l,u=r?"object":l?"script":"img",v=l?"script":u,w=Array.isArray||function(a){return"[object Array]"==o.call(a)},x=[],y={},z={timeout:function(a,b){return b.length&&(a.timeout=b[0]),a}},A,B;B=function(a){function b(a){var a=a.split("!"),b=x.length,c=a.pop(),d=a.length,c={url:c,origUrl:c,prefixes:a},e,f,g;for(f=0;f<d;f++)g=a[f].split("="),(e=z[g.shift()])&&(c=e(c,g));for(f=0;f<b;f++)c=x[f](c);return c}function g(a,e,f,g,h){var i=b(a),j=i.autoCallback;i.url.split(".").pop().split("?").shift(),i.bypass||(e&&(e=d(e)?e:e[a]||e[g]||e[a.split("/").pop().split("?")[0]]),i.instead?i.instead(a,e,f,g,h):(y[i.url]?i.noexec=!0:y[i.url]=1,f.load(i.url,i.forceCSS||!i.forceJS&&"css"==i.url.split(".").pop().split("?").shift()?"c":c,i.noexec,i.attrs,i.timeout),(d(e)||d(j))&&f.load(function(){k(),e&&e(i.origUrl,h,g),j&&j(i.origUrl,h,g),y[i.url]=2})))}function h(a,b){function c(a,c){if(a){if(e(a))c||(j=function(){var a=[].slice.call(arguments);k.apply(this,a),l()}),g(a,j,b,0,h);else if(Object(a)===a)for(n in m=function(){var b=0,c;for(c in a)a.hasOwnProperty(c)&&b++;return b}(),a)a.hasOwnProperty(n)&&(!c&&!--m&&(d(j)?j=function(){var a=[].slice.call(arguments);k.apply(this,a),l()}:j[n]=function(a){return function(){var b=[].slice.call(arguments);a&&a.apply(this,b),l()}}(k[n])),g(a[n],j,b,n,h))}else!c&&l()}var h=!!a.test,i=a.load||a.both,j=a.callback||f,k=j,l=a.complete||f,m,n;c(h?a.yep:a.nope,!!i),i&&c(i)}var i,j,l=this.yepnope.loader;if(e(a))g(a,0,l,0);else if(w(a))for(i=0;i<a.length;i++)j=a[i],e(j)?g(j,0,l,0):w(j)?B(j):Object(j)===j&&h(j,l);else Object(a)===a&&h(a,l)},B.addPrefix=function(a,b){z[a]=b},B.addFilter=function(a){x.push(a)},B.errorTimeout=1e4,null==b.readyState&&b.addEventListener&&(b.readyState="loading",b.addEventListener("DOMContentLoaded",A=function(){b.removeEventListener("DOMContentLoaded",A,0),b.readyState="complete"},0)),a.yepnope=k(),a.yepnope.executeStack=h,a.yepnope.injectJs=function(a,c,d,e,i,j){var k=b.createElement("script"),l,o,e=e||B.errorTimeout;k.src=a;for(o in d)k.setAttribute(o,d[o]);c=j?h:c||f,k.onreadystatechange=k.onload=function(){!l&&g(k.readyState)&&(l=1,c(),k.onload=k.onreadystatechange=null)},m(function(){l||(l=1,c(1))},e),i?k.onload():n.parentNode.insertBefore(k,n)},a.yepnope.injectCss=function(a,c,d,e,g,i){var e=b.createElement("link"),j,c=i?h:c||f;e.href=a,e.rel="stylesheet",e.type="text/css";for(j in d)e.setAttribute(j,d[j]);g||(n.parentNode.insertBefore(e,n),m(c,0))}}(this,document),Modernizr.load=function(){yepnope.apply(window,[].slice.call(arguments,0))};
/**
@file
Classes to add to the <html> element, kinda like a custom extension to what Modernizr already does.
*/


globalGetParams = window.location.search.length <= 1 ?
    {hash: window.location.hash} :
    function(a) {
        var i = a.length,
            r = /%25/g,  // Ensure '%' is properly represented 
            h = {};      // (Safari auto-encodes '%', Firefox 1.5 does not)
        while(i--) {
            var p = a[i].split('=');
            h[ p[0] ] = r.test( p[1] ) ? decodeURIComponent( p[1] ) : p[1];
        }

        h.hash = window.location.hash;

        return h;
    }(window.location.search.substr(1).split('&'));


// add some classes so simple CSS-based hide/show can be done
new function() {

    var ua = navigator.userAgent;
    if (globalGetParams.ua) ua = globalGetParams.ua;

    if ((/iPhone/i).test(ua)) document.documentElement.className += ' device-iphone';
    if ((/iPad/i).test(ua)) document.documentElement.className += ' device-ipad';
    if ((/iPod/i).test(ua)) document.documentElement.className += ' device-ipod';
    if ((/iPhone/i).test(ua) || (/iPad/i).test(ua) || (/iPod/i).test(ua)) {
        document.documentElement.className += ' device-ios';
        globalIsIOS = true;
    } else {
        document.documentElement.className += ' device-not-ios';
        globalIsIOS = false;
    }
    if ((/Android/i).test(ua)) document.documentElement.className += ' device-android';

    globalIsSafari = false;
    if (ua.toLowerCase().indexOf('safari') != -1) { 
        if (ua.toLowerCase().indexOf('chrome') > -1) {
            // chrome actually
        } else {
            // safari
            globalIsSafari = true;
            document.documentElement.className += ' browser-safari';
        }
    }

    globalIsIE = (document.documentElement.className.indexOf('ie678') > -1);

    var mobile_user_agent_strings = [
        'Android',
        'iPhone',
        'iPad',
        'iPod',
        'Opera Mobi',
        'BlackBerry',
        'AvantGo',
        'DoCoMo',
        'KDDI',
        'Vodafone',
        'J-PHONE',
        'DDIPOCKET',
        'PDXGW',
        'ASTEL',
        'EudoraWeb',
        'Windows CE',
        'Minimo',
        'OPWV-SDK',
        'UP.Browser',
        'PLink',
        'Plucker',
        'NetFront',
        'WM5 PIE',
        'Xiino',
        'BenQ',
        'Cricket',
        'IEMobile',
        'Nintendo Wii',
        'nook browser',
        'Nook',
        'Kindle'
    ];

    // loop through the mobile browsers
    globalIsMobile = false;
    for (var nu in mobile_user_agent_strings) {
        if (ua.toLowerCase().match(new RegExp(mobile_user_agent_strings[nu].toLowerCase()))) {
            // mobile browser
            document.documentElement.className += ' device-mobile';
            globalIsMobile = true;
            break;
        }
    }

}

// some more convenience here ...


var globalTransitionTransformProps = {
    'WebkitTransform': '-webkit-transform',
    'MozTransform': '-moz-transform',
    'msTransform': '-ms-transform',
    'OTransform': '-o-transform',
    'transform': 'transform'
};

/**
CSS manipulation big time.
@from http://www.hunlock.com/blogs/Totally_Pwn_CSS_with_Javascript
*/
if (!window.getCSSRule) {
    function getCSSRule(ruleName, deleteFlag, filter) {
        ruleName=ruleName.toLowerCase();
        if (document.styleSheets) {
            for (var i=0; i<document.styleSheets.length; i++) {
              var styleSheet=document.styleSheets[i];
              var ii=0;
              var cssRule=false;
              do {
            // console.log('styleSheet = ', styleSheet);
            // if(getLocation(styleSheet.href))
            // console.log(getLocation(styleSheet.href).hostname);
            if(getLocation(styleSheet.href).hostname != window.location.hostname) {
                continue;
            }
            
            // TREMENDOUSLY speeds up parsing stylesheets ...
            if(filter) {
                if(!styleSheet || !styleSheet.href || !filter.exec(styleSheet.href)) {
                    continue;
                }
            }

               if (styleSheet.cssRules) {
                   cssRule = styleSheet.cssRules[ii];
               } else if (styleSheet.rules) {
                   cssRule = styleSheet.rules[ii];
               }
               if (cssRule)  {
                   if (cssRule.selectorText && cssRule.selectorText.toLowerCase()==ruleName) {
                    if (deleteFlag=='delete') {
                     if (styleSheet.cssRules) {
                      styleSheet.deleteRule(ii);
                  } else {
                      styleSheet.removeRule(ii);
                  }
                  return true;
              } else {
                 return cssRule;
             }
         }
     }
     ii++;
    } while (cssRule)
    }
    }
    return false;
    }
}


/**
Deferred-loading CSS.
(because sometimes things like sprites can wait...)
@from https://developers.google.com/speed/docs/insights/OptimizeCSSDelivery
*/

function deferCSS(href) {
    var cb = function() {
        var l = document.createElement('link'); l.rel = 'stylesheet';
        l.href = href;
        var h = document.getElementsByTagName('head')[0]; h.parentNode.insertBefore(l, h);
    };
    var raf = requestAnimationFrame || mozRequestAnimationFrame ||
    webkitRequestAnimationFrame || msRequestAnimationFrame;
    if (raf) raf(cb);
    else window.addEventListener('load', cb);
}





// polyfill
if (!window.logger) {
    logger = function(){};
    logger.debug = function(){
        if (window.console && window.console.debug) {
            console.debug.apply(console, arguments);
        } else {
            console.log.apply(console, arguments);
        }
    };
    logger.error = function(){
        if (window.console && window.console.error) {
            console.error.apply(console, arguments);
        } else {
            console.log.apply(console, arguments);
        }
    };
}

// @from http://stackoverflow.com/questions/5227909/get-element-padding-value-using-javascript
if (!window.getStyle) {
    function getStyle(oElm, strCssRule) {
        var strValue = "";
        if (document.defaultView && document.defaultView.getComputedStyle){
            strValue = document.defaultView.getComputedStyle(oElm, "").getPropertyValue(strCssRule);
        }
        else if (oElm.currentStyle){
            strCssRule = strCssRule.replace(/\-(\w)/g, function (strMatch, p1){
                return p1.toUpperCase();
            });
            strValue = oElm.currentStyle[strCssRule];
        }
        return strValue;
    }
}

// wire up the total control over touches for an element (class)
// Note: can be called before $(document).ready and doesn't require jQuery
if (!window.wireupTotalTouchControl) {
    function wireupTotalTouchControl(aClass, aCallback, aTransparent) {
        // console.log("Hey, 2");

        // if (!globalIsIOS) return;
        if (!globalIsMobile) return;
        for (var elem in {'touchstart': 1, 'touchmove': 1, 'touchcancel': 1}) {
            document.addEventListener(elem, function(e) {

                if (e && e.target && e.target.classList &&
                    (e.target.classList.contains(aClass) || e.target.parentNode.classList.contains(aClass))) {
                    if (!aTransparent) {
                        e.stopPropagation();
                        e.stopImmediatePropagation();
                        e.preventDefault();
                        return false;
                    } else {
                        return true;
                    }
                }

                return true;

            }, true);
        }

        document.addEventListener('touchend', function(e) {

            if (e && e.target && e.target.classList &&
                (e.target.classList.contains(aClass) || e.target.parentNode.classList.contains(aClass))) {
                if (!aTransparent) {
                    aCallback(e);
                    e.stopPropagation();
                    e.stopImmediatePropagation();
                    e.preventDefault();
                    return false;
                } else {
                    return aCallback(e);
                }
            }

            return true;

        }, true);

    }
}




/**

@file
A responsive, touch- and developer-friendly slideshow.
@documentation http://wiki.goldeneraproductions.org/wiki/Gsc_headers

*/

if($('body').hasClass('templated-slider-slideset-tokyo-grand-opening') ||
    $('body').hasClass('templated-slider-slideset-nnuk-opening') ||
    $('body').hasClass('templated-slider-slideset-nnojai-opening') ||
    $('body').hasClass('templated-slider-slideset-nnlatam-opening') || 
    $('body').hasClass('templated-slider-slideset-nneu-opening') || 
    window.location.pathname == "/scientology-today/grand-opening-fountain-building.html" ||
    window.location.pathname == "/scientology-today/grand-opening-golden-crest.html" ||
    window.location.pathname == "/david-miscavige/cornerstone-members.html" ||
    window.location.pathname == "/scientology-today/clearwater-united-for-human-rights-center-opening.html" ||
    // window.location.pathname == "/scientology-today/church-openings/scientology-cuts-ribbon-on-first-south-american-ideal-org-bogota-colombia.html" ||
    window.location.pathname == "/scientology-today/events/ias-2013-celebration.html" ||
    window.location.pathname == "/scientology-today/events/maiden-voyage-2015.html" ||
    window.location.pathname == "/info-center/clearwater-united-for-human-rights-center.html"
    ) {
    var cancelVerticalCaptionCentering = true;
}

var getLocation = function(href) {
    var l = document.createElement("a");
    l.href = href;
    return l;
};

// in case this is not (yet) defined somewhere else
if (!window.loadJS) {
    // load a JS file asynchronously.
    // @ref https://github.com/filamentgroup/loadJS
    function loadJS(src, cb) {
        var ref = window.document.getElementsByTagName( "script" )[ 0 ];
        var script = window.document.createElement( "script" );
        script.src = src;
        script.async = true;
        ref.parentNode.insertBefore( script, ref );
        if (cb && typeof(cb) === "function") {
            script.onload = cb;
        }
        return script;
    }
}

var GscResponsiveSlider = function(opts) {
    // mix in the options
    for (var key in opts) this[key] = opts[key];
}

GscResponsiveSlider.prototype = (function() {

    var me = {};

    var picaR = pica();

    // options

    // SEE http://wiki.goldeneraproductions.org/wiki/Gsc_headers for full exmplanation

    me.domParent = '.header'; // used to limit selectors to avoid accidentally hitting other slideshow-like elements on the page
    me.fsoSliderZoomHeight = 575;
    var fsoSlideWidth = 860;

    // me.zoomEnabled = true; // whether to provide zoom controls
    // me.zoomOnClick = true; // whether click anywhere on the slide should zoom (this is turned on on the org opening press releases, for example)
    // me.hasLeftSidebar = false; // if true, resizing logic changes appropriately
    // me.startSlide = 1; // slide to start on (this starts counting the slides at '1', not '0')
    // me.useSimpleSliding = false; // changes the fancy sliding logic (developed for the org opening press releases, whereas elements from the slides animate separately) to a simple translate on the slide holder elem
    me.addControls = true; // if true, the slideshow will create the DOM elements for the various controls such as arrows, apple dots, prev/next buttons, etc.
    me.autoplayVideos = true; // autoplay video for first slide (for first time, cookie it per video ID) or if started with ?video=... (for first time, cookie it per video ID)
    me.circularClone = false; // set true to allow infinite, magical, circular sliding (implemented by cloning the slideshow)
    me.slidesMax860 = false; // if true, limit the <slide> elements to 860px (never go wider than that) - currently this is what we use on press releases
    me.animationGracePeriod = 1000; // how long before we consider that all piece (of a slide) have finished animation (in ms)

    // default will be set later
    // me.touchMode = 'default';

    // optimizations
    var $mySlides,
        animationGracePeriod,
        totalSlides,
        fsoSliderTop,
        slideholderDelta = 0;

    var ipAnimation = 0;
    var $mySlide,
        // subanimations,
        myDirection,
        extraMotion;

    var fsoSlideWidth2; //  = fsoSlideWidth + 50;

    var fsoSliderZoomTimeout = 0;
    var fsoSliderZoomedIn = false;
    var fsoSliderZoomedInScaled = false;

    var fsoSliderResizeTimer = 0;

    var $allNonImageElems,
        $allImageElems;
    var xRatio = 1;
    var attrs = ['top', 'bottom', 'left', 'right', 'width', 'height'];
    var dotHolderWidth;

    var currentActiveSlideIdx = 0;
    var slideshowScrollTop,
        fsoSliderZoomedIn,
        lastSlideOffset,
        containerWideEnoughForNoSliding;

    var allZoomedInAppleDots,
        allNormalAppleDots,
        myTransform,
        mySlideholderElem,
        tooManyAppleDots,
        midwaySlideNumLow = 0,
        leftHolderOffset = 0,
        midwaySlideNum = 0;

    var isIpad;

    var textAnimationQueue = [];

    // optimization
    var $slideshowMainElem,
        slideshowMainElem,
        $slideSelectorElem,
        slideSelectorElem,
        $slideArrowHolder,
        slideArrowHolder,
        $slideArrowLeft,
        slideArrowLeft,
        $slideHolderDom,
        slideHolderDom;

    var customLeftPanel = false;

    var isCloned = false;

    var $mySlideshowHolder,
        $mySlideshowWrapper,
        plusOne,
        minusOne;


    var scaledImages = {};

    // defaults

    var timeline = new TimelineMax({});

    // call this after document.ready
    me.init = function() {
        /**


         ###  #     #  ###  #######
          #   ##    #   #      #
          #   # #   #   #      #
          #   #  #  #   #      #
          #   #   # #   #      #
          #   #    ##   #      #
         ###  #     #  ###     #


        */        

        if (window.globalLang && globalLang == "he") {
            plusOne = -1;
            minusOne = 1;
        } else {
            plusOne = 1;
            minusOne = -1;
        }

        var that = this;

        if (!(this.domParent instanceof jQuery)) {
            this.domParent = $(this.domParent);
        }

        // sanity checks
        $slideshowMainElem = this.domParent.find('.slideshow-main');
        slideshowMainElem = $slideshowMainElem[0];
        if (!slideshowMainElem) return logger.error('There is no ".slideshow-main"!');
        if (!(this.domParent.find('.slide-wrapper')[0])) return logger.error('There is no ".slide-wrapper" on ".slideshow-main"!');

        // turn off PhotoSwipe for any slideshow with videos - since it won't work reliably
        if (this.touchMode === void 0 && this.domParent.find('.video-slide').length) {
            this.touchMode = 'default';
            if (window.deviceCustomType != 'desktop') this.zoomEnabled = false;
        }

        if (this.touchMode === void 0) this.touchMode = 'default';

        // don't need zooming if we have photoswipe
        if (window.deviceCustomType != 'desktop' && this.touchMode == 'photoswipe') this.zoomEnabled = false;

        if (this.zoomEnabled && !this.addControls) return logger.error('Conflicting options (zoomEnabled && !addControls): how am I supposed to enable zoom without adding controls?', 'error');

        // intelligent guesses
        if (this.zoomOnClick === void 0) {
            if ($slideshowMainElem.find('slide .video-js').length) {
                this.zoomOnClick = false;
                logger.debug('setting zoomOnClick to false');
            } else {
                this.zoomOnClick = true;
                logger.debug('setting zoomOnClick to true');
            }
        }
        if (this.hasLeftSidebar === void 0) {
            if (!this.domParent.find('.slideshow-left-nav').length) {
                this.hasLeftSidebar = false;
                logger.debug('setting hasLeftSidebar to false');
            } else {
                this.hasLeftSidebar = true;
                logger.debug('setting hasLeftSidebar to true');
            }
        }
        if (this.useSimpleSliding === void 0) {
            if ($slideshowMainElem.find('slide .item:not(.left-panel-mobile-caption)').length) {
                this.useSimpleSliding = false;
                this.slidesMax860 = (this.slidesMax860 === void 0 ? true : this.slidesMax860);
                logger.debug('setting useSimpleSliding to false');
            } else {
                this.useSimpleSliding = true;
                logger.debug('setting useSimpleSliding to true');
            }
        }
        if (this.zoomEnabled === void 0) {
            if (!$slideshowMainElem.find('slide .item:not(.left-panel-mobile-caption)').length) {
                this.zoomEnabled = false;
                logger.debug('setting zoomEnabled to false');
            } else {
                this.zoomEnabled = true;
                logger.debug('setting zoomEnabled to true');
            }
        }

        $mySlideshowHolder = this.domParent.find('.slideshow-holder');
        $mySlideshowWrapper = this.domParent.find('.slideshow-wrapper');

        $slideHolderDom = this.domParent.find('.slide-holder');
        slideHolderDom = $slideHolderDom[0];
        if (!slideHolderDom) return logger.error('There is no ".slide-holder"!');

        if (this.domParent.find('slide').length === 1) {
            $mySlideshowWrapper.addClass('slideshow-single-slide');
        }

        var tempThis = this;

        // init photoswipe

        /**


         ######   #     #  #######  #######  #######   #####   #     #  ###  ######   #######
         #     #  #     #  #     #     #     #     #  #     #  #  #  #   #   #     #  #
         #     #  #     #  #     #     #     #     #  #        #  #  #   #   #     #  #
         ######   #######  #     #     #     #     #   #####   #  #  #   #   ######   #####
         #        #     #  #     #     #     #     #        #  #  #  #   #   #        #
         #        #     #  #     #     #     #     #  #     #  #  #  #   #   #        #
         #        #     #  #######     #     #######   #####    ## ##   ###  #        #######


        */        
        if (window.deviceCustomType != 'desktop' && this.touchMode == 'photoswipe') {

            // load up photoswipe
            loadJS('/plugins/photoswipe/photoswipe.min.js?_=' + new Date().getTime());
            loadJS('/plugins/photoswipe/photoswipe-ui-default.min.js?_=' + new Date().getTime());

            loadjs(['css!/plugins/photoswipe/photoswipe.css?_=' + cacheId, 'css!/plugins/photoswipe/default-skin/default-skin.css?_=' + cacheId]);
            
            // build items array
            window.galleryItems = [];

            $('slide').each(function() {

                /*
                $(this).find('.image-holder').each(function() {
                    // TODO account for viewport difference
                    $(this).width(Math.round(parseInt($(this).attr('data-width')) / 860 * 100) + '%');
                });

                $(this).find('img:not([src])').each(function() {
                    $(this).attr('src', $(this).attr('data-src'));
                });

                */

                var $clone = $(this).clone();
                $clone.find('.image-holder').each(function() {
                    // $(this).height($(this).attr('data-height')).width($(this).attr('data-width'));
                    $(this).css('width', (Math.round(parseFloat($(this).attr('data-width')) / 860 * 1000000) / 10000) + '%');
                    $(this).css('height', (Math.round(parseFloat($(this).attr('data-height')) / 575 * 1000000) / 10000) + '%');
                });

                if ($clone.find('.image-holder').length == 1) {
                    $clone.addClass('js-single-image-slide');
                    var $imgHolder = $clone.find('.image-holder').eq(0);
                    var slideDims = [window.innerWidth, window.innerWidth * 0.6686];
                    var imageDims = [window.innerWidth * 0.6686 * parseFloat($imgHolder.attr('data-width')) / parseFloat($imgHolder.attr('data-height')), window.innerWidth * 0.6686];
                    
                    // dont let overflow happens - breaks mobile landscape slideshows
                    if (imageDims[0] > $imgHolder.attr('data-width') ) {
                        imageDims[0] = $imgHolder.attr('data-width');
                    }

                        if(window.location.pathname != "/scientology-today/church-openings/grand-opening-scientology-media-productions.html" && window.location.pathname != "/churches/bringing-scientology-world/scientology-media-productions.html") {
                             $imgHolder.css('min-width', Math.floor(imageDims[0]) + 'px');
                    }

                }

                $clone.find('img[data-src]').each(function() {
                    var imgSrc = determineImageSources(this);
                    // HACK: we are not setting the `src` attribute, as that would result in the image loaded at this point
                    if (imgSrc) $(this).attr('srca', imgSrc[1]).removeAttr('data-src').removeAttr('src');
                });

                // for the initial slide, the class `js-preview` might be already gone (if the images loaded in really fast), so put it back here
                var theSlideHtml = $clone[0].outerHTML;
                if (!theSlideHtml.match(/js-preview/)) theSlideHtml = theSlideHtml.replace(/image-holder/g, 'image-holder js-preview');

                var slideObj = {
                    html: theSlideHtml.replace(/srca=/g, 'src='),
                }
                if (deviceCustomType == 'mobile') slideObj.title = $clone.find('.text-item').html();
                galleryItems.push(slideObj);

            });

            $('.pswp')[0].className += ' zoomedIn slide-wrapper bs-slideshow';
            document.body.className += ' photoswipe-on';
            $('.pswp .pswp__container').html('<div class="pswp__item"></div> <div class="pswp__item"></div> <div class="pswp__item"></div>');

        }

        // quick caption shortening
        if (
                (window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth) > 767 &&
                (
                    (window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth) < 1025 ||
                    !document.body.className.match(/locale-en/)
                ) &&
                window.slideshowCaptionsOverflow
           ) {
            slideshowCaptionsOverflow();
        }

        if($('body').hasClass('narconon-nepal-grand-opening-slideshow')) {
            slideshowCaptionsOverflow();
        }

        if (this.domParent.find('slide').length === 0) window.console && console.error && console.error('ERROR: slideshow has no slides!');

        // decorate with controls
        /**


          #####   #######  #     #  #######  ######   #######  #         #####
         #     #  #     #  ##    #     #     #     #  #     #  #        #     #
         #        #     #  # #   #     #     #     #  #     #  #        #
         #        #     #  #  #  #     #     ######   #     #  #         #####
         #        #     #  #   # #     #     #   #    #     #  #              #
         #     #  #     #  #    ##     #     #    #   #     #  #        #     #
          #####   #######  #     #     #     #     #  #######  #######   #####


        */        
        if (this.addControls) {
            $mySlideshowHolder.append('\
                <div class="slide-controls">\
                    <div class="slide-arrow-holder right-arrow draw-border draw-border__arrow--white slide-left-arrow2">\
                        <arrow></arrow>\
                    </div>\
                    <div class="slide-arrow-holder right-arrow draw-border draw-border__arrow--white slide-right-arrow2">\
                        <arrow></arrow>\
                    </div>\
                </div>\
                <div class="slide-selectors"></div>\
                ');
            if (this.zoomEnabled) {
                $mySlideshowHolder.append('\
                    <div class="slide-zoomer">\
                        <span class="click-to-expand">'+strings.nav_expand+'</span>\
                    </div>\
                    ');
                $mySlideshowWrapper.before('\
                    <div class="fso-custom-slider-overlay fso-custom-slider-fader"></div>\
                    <div class="fso-slide-upper-bg fso-custom-slider-fader">\
                        <a href="#" class="closebtn"><span class="icon-cancel-circle"></span></a>\
                    </div>\
                    <div class="fso-slide-lower-bg fso-custom-slider-fader">\
                        <div class="fso-slide-selectors slide-selectors"></div>\
                    </div>\
                    <div class="fso-custom-zoomer">\
                        <div class="slide-zoomer">\
                            <span class="click-to-expand">'+strings.nav_close+'</span>\
                        </div>\
                    </div>\
                    ');
            }
            $slideHolderDom.after('\
                <div class="fso-slide-mobile-numbers">\
                    <span class="slide-num"></span> / <span class="slide-total"></span>\
                </div>\
                ');
        }

        $slideSelectorElem = this.domParent.find('.slide-selectors');
        slideSelectorElem = $slideSelectorElem[0];
        // TODO maybe there should be an explicit no-apple-dots option
        if (!slideSelectorElem && this.addControls) return logger.error('There is no ".slide-selectors"!');

        $slideArrowHolder = this.domParent.find('.slide-arrow-holder');
        slideArrowHolder = $slideArrowHolder[0];
        if (!slideArrowHolder) return logger.error('There is no ".slide-arrow-holder"!');

        $slideArrowLeft = this.domParent.find('.slide-left-arrow2');
        slideArrowLeft = $slideArrowLeft[0];
        if (!slideArrowLeft) return logger.error('There is no left arrow: ".slide-left-arrow2"!');

        if (!(this.domParent.find('.slide-controls')[0])) return logger.error('There is no ".slide-controls"!');
        if (!(this.domParent.find('.slide-right-arrow2')[0])) return logger.error('There is no ".slide-right-arrow2"!');

        $mySlides = this.domParent.find('.slide-holder slide');
        animationGracePeriod = this.animationGracePeriod;
        totalSlides = this.domParent.find('slide').length;
        $allNonImageElems = $mySlides.find('div.item,h3.item,.inactive-dot');
        $allImageElems = $mySlides.find('img.item');
        myMinSlideLeft = -10 - (fsoSlideWidth * (totalSlides - 1));
        slideshowScrollTop = slideshowMainElem.offsetTop;

        myTransform = Modernizr.prefixed('transform');
        mySlideholderElem = this.domParent.find('.slide-holder')[0];

        isIpad = $('html').hasClass('device-ipad');
        simpleAnimation = this.useSimpleSliding;

        isCloned = this.circularClone;

        // no cloning on the iphone - no need (since the slideshow will always be full width)
        if ($('html').hasClass('device-iphone') || globalIsIE) isCloned = this.circularClone = false;
        if (globalIsIOS) isCloned = this.circularClone = false;

        if (isCloned) {
            $mySlideshowWrapper.addClass('slideshow-been-cloned');
        } else {
            $mySlideshowWrapper.addClass('slideshow-not-cloned');
        }

        customLeftPanel = !! this.domParent.find('.custom-slide-leftnav').length;

        // $slideHolderDom.width(totalSlides + '00%');
        // var stretcherPaddingBottom = parseInt(getStyle($('.slide-stretcher')[0], "padding-bottom").replace(/px/, ''));
        // var stretchPercent = stretcherPaddingBottom / $('.slide-stretcher').width() * 100;
        // $mySlides.width((100 / totalSlides) + '%').css('padding-bottom', (stretchPercent / totalSlides) + '%');

        // figure out the aspect ratio for the slides - this will be useful for zooming
        if (this.domParent.find('.slide-stretcher').length) {
            var paddingBottom = getStyle(this.domParent.find('.slide-stretcher')[0], "padding-bottom");
            if (paddingBottom) {
                var stretcherPaddingBottom = parseInt(paddingBottom.replace(/px/, ''));
                if (!isNaN(stretcherPaddingBottom)) {
                    var stretchPercent = stretcherPaddingBottom / this.domParent.find('.slide-stretcher').width() * 100;
                    this.fsoSliderZoomHeight = fsoSlideWidth * stretchPercent / 100;
                    // console.log(this.fsoSliderZoomHeight);
                }
            }
        }

        // wire up video play on caption and video play button clicks
        $(document).on('click', '.new-age-caption-overlay, .video-slide-overlay.center-playbutton-overlay', function(e) {
            var videlem = $(this).siblings('.video-js');
            playVideoJS(videlem);
            fireEvent('userInteraction', 'video-play');
        });

        if (!this.domParent.find('.fso-slide-active')) $mySlides.eq(0).addClass('fso-slide-active');

        // TODO maybe there should be an explicit no-apple-dots option
        if (totalSlides > 35 && this.domParent.find('.slide-selectors').length) {
            tooManyAppleDots = true;
            $('body').addClass('fso-slider-too-many-apple-dots');
        } else {
            tooManyAppleDots = false;
            $('body').addClass('fso-slider-not-too-many-apple-dots');
        }

        //  fsoSliderTop not used anyway, causes perfomance bottleneck
        // setTimeout(function() {
        //     fsoSliderTop = $slideshowMainElem.position().top;
        // }, 1000);

        // hook up the zoomer images, set up image holders
        for (var i = 0; i < totalSlides; i++) {
            (function() {

                var $thisSlide = $mySlides.eq(i);

                $thisSlide.find('.image-holder').each(function() {

                    if ($(this).hasClass('js-dynamic-size-set')) return;
                    $(this).addClass('js-dynamic-size-set').css('width', (Math.round(parseFloat($(this).attr('data-width')) / 860 * 1000000000) / 10000000) + '%');
                    $(this).css('height', (Math.round(parseFloat($(this).attr('data-height')) / 575 * 1000000) / 10000) + '%');

                });

                if (window.deviceCustomType == 'desktop' || tempThis.touchMode != 'photoswipe') {
                    $thisSlide.find('.image-holder img[data-src]').each(function() {
                        var tempSize = determineImageSources(this);
                        if (tempSize && tempSize[1] != tempSize[0]) {
                            $(this).after($(this).clone().removeAttr('src').removeAttr('data-src').attr('data-double-src', tempSize[1]).addClass('zoomer-image'));
                        }
                    });

                    // immediately load the double-rez image for the starting slide
                    if ($thisSlide.hasClass('js-starting-slide')) {
                        $thisSlide.addClass('double-loaded').find('.zoomer-image').each(function() {
                            $(this).attr('src', $(this).attr('data-double-src')).addClass('loaded');
                        });
                    }

                } else {

                    if ($thisSlide.find('.image-holder').length == 1) $thisSlide.addClass('js-single-image-slide');

                }

            })();
        }

        /**


         ######   ######   #######  #        #######     #     ######
         #     #  #     #  #        #        #     #    # #    #     #
         #     #  #     #  #        #        #     #   #   #   #     #
         ######   ######   #####    #        #     #  #     #  #     #
         #        #   #    #        #        #     #  #######  #     #
         #        #    #   #        #        #     #  #     #  #     #
         #        #     #  #######  #######  #######  #     #  ######


        */

        if(this.touchMode != "photoswipe") {
            // wait for active slide to load and then preload other slides
            this.waitForActiveSlide(function(){
                that.preloadSlides(that); 
            });
        } else {
            loadSurroundingSlides(Math.max(0, 1))
        }
        

        /**


          #####   #        #######  #     #  ###  #     #   #####
         #     #  #        #     #  ##    #   #   ##    #  #     #
         #        #        #     #  # #   #   #   # #   #  #
         #        #        #     #  #  #  #   #   #  #  #  #  ####
         #        #        #     #  #   # #   #   #   # #  #     #
         #     #  #        #     #  #    ##   #   #    ##  #     #
          #####   #######  #######  #     #  ###  #     #   #####


        */

        // clone the slides
        if (this.circularClone) {

            logger.debug('cloning slides and sheep');
            var slideRefs = [];

            $mySlides.each(function() {

                slideRefs.push(this);
                var $cloned = $(this).clone();

                // take out any <video> elements, as these seem to mess up video
                // playback in different ways (per actual tests)
                $cloned.find('video').each(function() {
                    var myPoster = $(this).attr('poster');
                    if (!myPoster) return;
                    var posterDom = document.createElement("img");
                    posterDom.src = myPoster;
                    posterDom.style.position = 'absolute';
                    this.parentNode.replaceChild(posterDom, this);
                    if (this.parentNode && this.parentNode.tagName && this.parentNode.tagName.toLowerCase() === 'div') this.parentNode.style.position = 'absolute';
                });

                // id mangling
                $cloned.find('[id]').each(function() {
                    $(this).attr('id', $(this).attr('id') + '_cloned_after');
                });
                if ($cloned.attr('id')) $cloned.attr('id', $cloned.attr('id') + '_cloned_after');

                // class mangling
                if ($cloned.attr('class')) {
                    $cloned.attr('class', $cloned.attr('class').replace(/fso-slide-([0-9]*)/, function(match1) {
                        return match1 + '_cloned_after';
                    }));
                }

                // attr mangling
                if ($cloned.attr('data-slide-id')) {
                    $cloned.attr('data-slide-id', $cloned.attr('data-slide-id') + '_cloned_after');
                }

                $cloned.appendTo($slideHolderDom);

            });

            for (var i = slideRefs.length - 1; i >= 0; i--) {

                var $cloned = $(slideRefs[i]).clone();

                // take out any <video> elements, as these seem to mess up video
                // playback in different ways (per actual tests)

                $cloned.find('video').each(function() {
                    var myPoster = $(this).attr('poster');
                    if (!myPoster) return;
                    var posterDom = document.createElement("img");
                    posterDom.src = myPoster;
                    posterDom.style.position = 'absolute';
                    this.parentNode.replaceChild(posterDom, this);
                });

                // id mangling
                $cloned.find('[id]').each(function() {
                    $(this).attr('id', $(this).attr('id') + '_cloned_before');
                });
                if ($cloned.attr('id')) $cloned.attr('id', $cloned.attr('id') + '_cloned_before');

                // class mangling
                if ($cloned.attr('class')) {
                    $cloned.attr('class', $cloned.attr('class').replace(/fso-slide-([0-9]*)/, function(match1) {
                        return match1 + '_cloned_before';
                    }));
                }

                // attr mangling
                if ($cloned.attr('data-slide-id')) {
                    $cloned.attr('data-slide-id', $cloned.attr('data-slide-id') + '_cloned_before');
                }

                $cloned.prependTo($slideHolderDom);

            };

        }

        // // add activity indicators for the rest
        // $('.image-item[data-src]:not(.loaded)').each(function() {
        //  $(this).css('background', 'url(/sites/all/themes/gold_master/m_scientology_org/images/act_ind_small.gif) center center no-repeat')
        //      .css('min-width', '40px')
        //      .css('min-height', '40px');
        // });

        /**


            #     ######   ######   #        #######      ######   #######  #######   #####
           # #    #     #  #     #  #        #            #     #  #     #     #     #     #
          #   #   #     #  #     #  #        #            #     #  #     #     #     #
         #     #  ######   ######   #        #####        #     #  #     #     #      #####
         #######  #        #        #        #            #     #  #     #     #           #
         #     #  #        #        #        #            #     #  #     #     #     #     #
         #     #  #        #        #######  #######      ######   #######     #      #####


        */

        // dynamically put the dots in there - with dot scrolling
        var dots_html = '', thumb_class;
        for (var i = 0; i < totalSlides; i++) {
            dots_html += '<a class="slide-link" href="#slide' + (i+1) + '"><div class="slide-thumb';
            if (thumb_class = $mySlides.eq(i).attr('data-slide-thumb')) {
                dots_html += ' ' + thumb_class;
            }
            if (thumb_class = $mySlides.eq(i).attr('data-slide-thumb-style')) {
                dots_html += '" style="' + thumb_class;
            }
            dots_html += '"><div class="slide-thumb-image"></div></div></a> ';
        }
        $slideSelectorElem.addClass('scrolling-dots').html('\
        <div class="slide-dot-over slide-dot-over-left">\
            <!-- <a class="slide-first-link"></a> -->\
            <a class="slide-prev-next slide-prev slide-first-link" href="#"></a>\
        </div>\
        <div class="slide-dots-holder-counter">\
            <span class="input input--sae input--slide-number">\
                <input class="input__field input__field--sae" type="text" id="slibe-number-input" value="1"/>\
                <label class="input__label input__label--sae" for="slibe-number-input">\
                    <i class="fa fa-fw fa-pencil icon icon--sae"></i>\
                    <span class="input__label-content input__label-content--sae">Go to slide</span>\
                </label>\
            </span>\
            <div class="slide-dots-holder-counter-current"></div> / <div class="slide-dots-holder-counter-total"></div>\
        </div>\
        <div class="slide-dots-holder">\
            <div class="slide-dots-holder-outer">\
                <div class="slide-dots-holder-inner">' + dots_html + '</div>\
            </div>\
        </div>\
        <div class="slide-dot-over slide-dot-over-right">\
            <a class="slide-prev-next slide-next slide-last-link" href="#"></a>\
           <!-- <a class="slide-last-link"></a> -->\
        </div>\
        ');

        $('.slide-dot-over.slide-dot-over-left').eq(1).width($('.slide-prev-next.slide-prev').eq(1).width() + 27);
        $('.slide-dot-over.slide-dot-over-right').eq(1).width($('.slide-prev-next.slide-next').eq(1).width() + 37);

        if (this.zoomEnabled) {
            allZoomedInAppleDots = this.domParent.find('.slide-dots-holder').eq(0).find('.slide-link');
            allNormalAppleDots = this.domParent.find('.slide-dots-holder').eq(1).find('.slide-link');
        } else {
            allNormalAppleDots = this.domParent.find('.slide-dots-holder').eq(0).find('.slide-link');
        }

        var tempPos = allNormalAppleDots.eq(totalSlides - 1).position();
        if (!tempPos) {
            // TODO maybe there should be an explicit no-apple-dots option
            if (this.addControls)
                window.console && console.error && console.error('ERROR: slider dot error!');
        } else {
            lastSlideOffset = allNormalAppleDots.eq(totalSlides - 1).position().left;
            if (isRTL) lastSlideOffset = allNormalAppleDots.eq(0).position().left - lastSlideOffset;
        }

        // handle apple dot clicks
        this.domParent.find('.slide-link').on('click', function() {
            fireEvent('userInteraction', 'click-apple-dot');
            var myLink = $(this).attr('href');
            if (myLink[0] != '#') return true;
            replaceHash(myLink.substring(1));
            EventTracker.trackDotClick(myLink.replace("#slide", ""));
            return false;
        });

        var gotoInputActive = false;
        var lastNum = 0;
        $(this.domParent.find('.slide-dots-holder-counter')).click(function(event) {
            $('.input--slide-number').addClass('input--filled');
            TweenMax.set($('.slide-dots-holder-counter-current'), {autoAlpha: 0});
            $('.input--slide-number input').val(currentActiveSlideIdx+1);
            lastNum = currentActiveSlideIdx+1;
            gotoInputActive = true;
            setTimeout(function(){
                $('.input--slide-number input').focus();
            }, 100);
        });

        $(this.domParent.find('.input--slide-number .input__field--sae')).keypress(function(event){
            var keycode = (event.keyCode ? event.keyCode : event.which);

            // Enter pressed
            if(keycode == '13'){
                var slideNum = parseInt( $('.slideshow-wrapper .input--slide-number input').val() );
                if(isNaN(slideNum)) {
                    console.error('slideNum is NaN');
                    return;
                }
                fsoSliderGotoSlide(slideNum-1, true);
                location.hash = 'slide' + (slideNum);
                TweenMax.set($('.slide-dots-holder-counter-current'), {autoAlpha: 1});
                $('.input--slide-number').removeClass('input--filled');
                return;
            } else {
                if($('.slideshow-wrapper .input--slide-number input').val() == "") {
                    return;
                }
                
                var slideNum = parseInt( $('.slideshow-wrapper .input--slide-number input').val() );
                if(isNaN(slideNum) || lastNum < 1 || lastNum > totalSlides) {
                    console.error('slideNum is NaN');
                    $('.input--slide-number input').val(lastNum);
                    return;
                }
                lastNum = slideNum;
            }

        });

        $slideArrowHolder.on('click', function(e) {

            e.preventDefault();
            e.stopPropagation();

            var isLeftArrow = $(this).hasClass('slide-left-arrow2');

            if (isLeftArrow) {
                sliderMovePrev();
            }
            if (!isLeftArrow) {
                that.sliderMoveNext();
            }

            // var newSlideIdx = currentSlideIdx + (isLeftArrow ? -1 : 1);
            // location.hash = 'slide' + (newSlideIdx+1);

            fireEvent('userInteraction', 'arrow-click');

            return false;
        });

        this.domParent.find('.fso-slide-mobile-numbers .slide-total').text(totalSlides);
        this.domParent.find('.fso-slide-mobile-numbers .slide-num').text(1);

        $(window).on('hashchange', function() {
            fsoSliderHashChange();
        });

        /**


         #######  ###  ######    #####   #######       #####   #        ###  ######   #######
         #         #   #     #  #     #     #         #     #  #         #   #     #  #
         #         #   #     #  #           #         #        #         #   #     #  #
         #####     #   ######    #####      #          #####   #         #   #     #  #####
         #         #   #   #          #     #               #  #         #   #     #  #
         #         #   #    #   #     #     #         #     #  #         #   #     #  #
         #        ###  #     #   #####      #          #####   #######  ###  ######   #######


        */
        // Adds hover effects to toggle visibility class based on `.slide-link` position relative to `.slide-dots-holder-outer`
        // This is needed to fix windows hover cut off effect bug
         $(document).on('mouseenter', '.slide-link', function() {
            var $slideLink = $(this);
            var $containerInner = $slideLink.closest('.slide-dots-holder-inner');
            var $containerOuter = $containerInner.closest('.slide-dots-holder-outer');
        
            // Get the absolute left position of `.slide-link` and `.slide-dots-holder-outer`
            var slideLinkOffsetLeft = $slideLink.offset().left;
            var containerOuterOffsetLeft = $containerOuter.offset().left;
        
            // Calculate the left position relative to `.slide-dots-holder-outer`
            var relativeLeft = slideLinkOffsetLeft - containerOuterOffsetLeft;
            var width = $slideLink.outerWidth();
            var containerWidth = $containerOuter.outerWidth();
        
            var positionPlus = relativeLeft + width + 125 / 2;
            var positionMinus = relativeLeft - 125 / 2;
        
            if (positionPlus > containerWidth || positionMinus < 0) {
                $containerInner.closest('.slide-dots-holder').addClass('slide-dots-holder__visible');
            }
        });
        
        $(document).on('mouseleave', '.slide-link', function() {
            var $container = $(this).closest('.slide-dots-holder');
            $container.removeClass('slide-dots-holder__visible');
        });        
        

        var myFirstSlide = this.determineFirstSlide();
        if (myFirstSlide === 1) {

            // no need to slide and stuff for the first slide
            $('.header-container').addClass('on-first-slide');
            $mySlideshowHolder.addClass('slider-first-slide');
            $slideshowMainElem.attr('data-slide-active', 0);
            this.slideHasChanged();
            $('.slide-link[href="#slide1"]').addClass('selected');


            // autoplay as needed
            // if (this.autoplayVideos && $mySlides.eq(0).find('.video-js').length) startVideoForSlide(0);

        } else {

            if (!isIpad) {

                fsoSliderGotoSlide(myFirstSlide - 1, !($slideshowMainElem.hasClass('js-slideshow-preinited')));

                // autoplay as needed
                // if (this.autoplayVideos && $mySlides.eq(myFirstSlide - 1).find('.video-js').length) startVideoForSlide(myFirstSlide - 1);

            } else {
                fsoSliderGotoSlide(myFirstSlide - 1, false);
                sliderPositionSlides(true);
            }

        }

        this.domParent.find('.fso-slide-mobile-numbers').css('opacity', 1);

        this.domParent.find('.slide-prev').on('click', function(e) {
            e.preventDefault();
            that.sliderGotoFirst();
            fireEvent('userInteraction', 'prev-click');
        });

        this.domParent.find('.slide-next').on('click', function(e) {
            e.preventDefault();;
            that.sliderGotoLast();
            fireEvent('userInteraction', 'next-click');
        });

        /**


         #######  #######  #######  #     #  ###  #     #   #####
              #   #     #  #     #  ##   ##   #   ##    #  #     #
             #    #     #  #     #  # # # #   #   # #   #  #
            #     #     #  #     #  #  #  #   #   #  #  #  #  ####
           #      #     #  #     #  #     #   #   #   # #  #     #
          #       #     #  #     #  #     #   #   #    ##  #     #
         #######  #######  #######  #     #  ###  #     #   #####


        */

        ////////////////////
        // Zoom-in, zoom-out
        // set up the zooming elements (elements to hide when we're going full-screen)

        if (this.zoomEnabled) {

            $('#pre_banner_wrapper').addClass('fso-zoomer');
            $('#addthis').addClass('fso-zoomer');
            $('#banner').addClass('fso-zoomer');
            $('#content_container').addClass('fso-zoomer');
            $('#admin-menu').addClass('fso-zoomer');

            if (this.zoomOnClick) {
                $slideHolderDom.on('click', function(e) {
                    if ($('body').hasClass('editing')) return true;
                    if ($('body').hasClass('slide-captions-only')) return true;

                    
                    // if target has target blank, return true
                    if(e.target.tagName == "A" && e.target.target == "_blank") {
                        return true;
                    }

                    if(e.target.classList.contains("image-code") || e.target.classList.contains("item-replay-button")){
                        return true;
                    }

                    if($(e.target).closest('.cd-image-container').length > 0) {
                        return true;
                    }

                    if($(event.target).hasClass('caption-overlay-button__open') || 
                       $(event.target).parent().hasClass('caption-overlay-button__open')) {
                        return true;
                    }

                    //no zoom for video
                    if (!globalIsMobile && e && e.target && $(e.target).attr('class') && ($(e.target).attr('class').indexOf('vjs') >= 0 || $(e.target).parent().attr('class').indexOf('templated-video-slide') >= 0 ) ) return true;
                    if (e && e.target && $(e.target).hasClass('ignore-zoom')) return true;
                    if (e && e.target && $(e.target).parents('.ignore-zoom').length) return true;
                    if (!fsoSliderZoomedIn) {
                        that.fsoSliderZoomIn();
                        fireEvent('userInteraction', 'zoom-in');
                    } else {
                        that.fsoSliderZoomOut();
                        fireEvent('userInteraction', 'zoom-out');
                    }
                });
            }

            this.domParent.find('.slide-zoomer').on('click', function(e) {
                // if ($('body').hasClass('editing')) return true;
                if (!fsoSliderZoomedIn) {
                    that.fsoSliderZoomIn();
                    fireEvent('userInteraction', 'zoom-in');
                } else {
                    that.fsoSliderZoomOut();
                    fireEvent('userInteraction', 'zoom-out');
                }
            });

            if(globalGetParams.gallery == "true") {
                setTimeout(() => {
                    that.fsoSliderZoomIn();
                }, 200);
            }

            // $('.fso-slide-lower-bg').on('click', function(e) {
            //  if (!fsoSliderZoomedIn) {
            //      that.fsoSliderZoomIn();
            //  } else {
            //      that.fsoSliderZoomOut();
            //  }
            // });

            this.domParent.find('.fso-slide-upper-bg .closebtn').on('click', function(e) {
                fireEvent('userInteraction', 'zoom-out');
                that.fsoSliderZoomOut();
            });


            $(window).on('resize', function(e) {

                if (fsoSliderZoomedIn) {
                    // throttle it a bit
                    if (fsoSliderResizeTimer > 0) clearTimeout(fsoSliderResizeTimer);
                    fsoSliderResizeTimer = setTimeout(function() {

                        $('.fso-slide-lower-bg .slide-selectors').css('left', $(window).width() / 2 - fsoSlideWidth / 2)
                        var zoomRatio = that.fsoSliderCalculateZoomRatio();
                        $slideshowMainElem.find('.slide-stretcher-outer')
                            .css('-moz-transform', '-moz-translate3d(0px, ' + -zoomRatio.verticalDelta + 'px, 0px) scale3d(' + zoomRatio.scaleRatio + ',' + zoomRatio.scaleRatio + ', 1.0)')
                            .css('-ms-transform', '-ms-translate3d(0px, ' + -zoomRatio.verticalDelta + 'px, 0px) scale3d(' + zoomRatio.scaleRatio + ',' + zoomRatio.scaleRatio + ', 1.0)')
                            .css('-o-transform', '-o-translate(0px, ' + -zoomRatio.verticalDelta + 'px) scale3d(' + zoomRatio.scaleRatio + ',' + zoomRatio.scaleRatio + ', 1.0)')
                            .css('transform', 'translate3d(0px, ' + -zoomRatio.verticalDelta + 'px, 0px) scale3d(' + zoomRatio.scaleRatio + ',' + zoomRatio.scaleRatio + ', 1.0)')
                            .css('-webkit-transform', 'translate3d(0px, ' + -zoomRatio.verticalDelta + 'px, 0px) scale3d(' + zoomRatio.scaleRatio + ',' + zoomRatio.scaleRatio + ', 1.0)');
                        $('.additional-zoomer-elem')
                            .css('-moz-transform', '-moz-translate3d(0px, ' + -zoomRatio.verticalDelta + 'px, 0px) scale3d(' + zoomRatio.scaleRatio + ',' + zoomRatio.scaleRatio + ', 1.0)')
                            .css('-ms-transform', '-ms-translate3d(0px, ' + -zoomRatio.verticalDelta + 'px, 0px) scale3d(' + zoomRatio.scaleRatio + ',' + zoomRatio.scaleRatio + ', 1.0)')
                            .css('-o-transform', '-o-translate(0px, ' + -zoomRatio.verticalDelta + 'px) scale3d(' + zoomRatio.scaleRatio + ',' + zoomRatio.scaleRatio + ', 1.0)')
                            .css('transform', 'translate3d(0px, ' + -zoomRatio.verticalDelta + 'px, 0px) scale3d(' + zoomRatio.scaleRatio + ',' + zoomRatio.scaleRatio + ', 1.0)')
                            .css('-webkit-transform', 'translate3d(0px, ' + -zoomRatio.verticalDelta + 'px, 0px) scale3d(' + zoomRatio.scaleRatio + ',' + zoomRatio.scaleRatio + ', 1.0)');
                    }, 300);
                }

            });

        }

        ////////////////////
        // Screencapper hack
        if ((document.location.host.match(/hotline.org/) || document.location.host.match(/firechrome.org/)) &&
            navigator.userAgent.match(/Autoscreencapper/) && document.location.hash.match(/slide/)) {
            $('#content_container,#wide_footer,#footer').css('display', 'none');
            $('#header').css('overflow', 'hidden');
        }

        /*
        $('slide').hover(
            function() {
                $('.slide-zoomer').css('opacity', 1);
            },
            function() {
                $('.slide-zoomer').css('opacity', 0);
            }
        );

        $('.slide-zoomer').hover(
            function() {
                $('.slide-zoomer').css('opacity', 1);
            },
            function() {
                $('.slide-zoomer').css('opacity', 0);
            }
        );
        */

        /*
        $('.fso-slide-lower-bg').hover(
            function() {
                $('.slide-zoomer').css('opacity', 1);
            },
            function() {
                $('.slide-zoomer').css('opacity', 0);
            }
        );
        */

        /**


         #######  #     #   #####   #        ###   #####   #    #   #####
         #     #  ##    #  #     #  #         #   #     #  #   #   #     #
         #     #  # #   #  #        #         #   #        #  #    #
         #     #  #  #  #  #        #         #   #        ###      #####
         #     #  #   # #  #        #         #   #        #  #          #
         #     #  #    ##  #     #  #         #   #     #  #   #   #     #
         #######  #     #   #####   #######  ###   #####   #    #   #####


        */

        // keyboard navigation
        $(document).on('keydown', function(e) {

            if ($('body').hasClass('editing-ip') || $('body').hasClass('editing') || $('body').hasClass('slide-captions-only')) return;
            
            var d = e.srcElement || e.target;

            // eschew input fields
            if ((d.tagName.toUpperCase() === 'INPUT' && (d.type.toUpperCase() === 'TEXT' || d.type.toUpperCase() === 'PASSWORD' || d.type.toUpperCase() === 'FILE')) || d.tagName.toUpperCase() === 'TEXTAREA') {
                return;
            }

            // left arrow key
            if ((e.which == 37 && !isRTL) || (e.which == 39 && isRTL)) {
                e.preventDefault();
                sliderMovePrev();
                fireEvent('userInteraction', 'key-prev');

                var arrow = $slideshowMainElem.find('.slide-left-arrow2');
                arrow.addClass('draw-border__arrow__pressed');
                setTimeout(function(){
                    arrow.removeClass('draw-border__arrow__pressed');
                }, 500);
            }
            // right arrow key
            else if ((e.which == 39 && !isRTL) || (e.which == 37 && isRTL)) {
                e.preventDefault();
                that.sliderMoveNext();
                fireEvent('userInteraction', 'key-next');

                var arrow = $slideshowMainElem.find('.slide-right-arrow2');
                arrow.addClass('draw-border__arrow__pressed');
                setTimeout(function(){
                    arrow.removeClass('draw-border__arrow__pressed');
                }, 500);
            }
            // esc
            else if (that.zoomOnClick && e.which == 27) {
                e.preventDefault();
                if (fsoSliderZoomedIn) that.fsoSliderZoomOut();
                fireEvent('userInteraction', 'zoom-out');
            }
            // space
            else if (that.zoomOnClick && e.which == 32 && $('.search--open').length == 0) {
                e.preventDefault();
                if (fsoSliderZoomedIn) {
                    that.fsoSliderZoomOut();
                    fireEvent('userInteraction', 'zoom-out');
                } else {
                    that.fsoSliderZoomIn();
                    fireEvent('userInteraction', 'zoom-in');
                }
            }

        });

        this.domParent.find('.slide-first-link').on('click', function(e) {
            // location.hash = 'slide1';
            replaceHash('slide1');
            fireEvent('userInteraction', 'click-first');
            return false;
        });



        this.domParent.find('.slide-last-link').on('click', function(e) {
            // location.hash = 'slide' + totalSlides;
            replaceHash('slide' + totalSlides);
            fireEvent('userInteraction', 'click-last');
            return false;
        });

        /* this seems to just not work
        $('.device-iphone slide .vjs-poster').on('click', function(e) {
            var myId = $(e.target).parents('.video-js').attr('id');
            videojs(myId).play();
            $(e.target).parents('.video-js').find('video').play();
            console.log('playing one');
        });
        
        $('.device-iphone slide .vjs-poster').on('touchend', function(e) {
            var myId = $(e.target).parents('.video-js').attr('id');
            videojs(myId).play();
            $(e.target).parents('.video-js').find('video').play();
            console.log('playing two');
        });
        */


        /**


         ###  ######   #     #  #######  #     #  #######
          #   #     #  #     #  #     #  ##    #  #
          #   #     #  #     #  #     #  # #   #  #
          #   ######   #######  #     #  #  #  #  #####
          #   #        #     #  #     #  #   # #  #
          #   #        #     #  #     #  #    ##  #
         ###  #        #     #  #######  #     #  #######

         #     #  ###  ######   #######  #######
         #     #   #   #     #  #        #     #
         #     #   #   #     #  #        #     #
         #     #   #   #     #  #####    #     #
          #   #    #   #     #  #        #     #
           # #     #   #     #  #        #     #
            #     ###  ######   #######  #######


        */

        // video handling for the iPhone
        if ($('html').hasClass('device-iphone')) {


            setTimeout(function() {

                var videoStartTime,
                    videoInitialX;

                // HACK kinda gross, but we need to remove the touch event listeners that videojs has added
                // (which end up cancelling scrolling on the page if you touch the poster image)
                $('.vjs-poster').each(function() {
                    var clone = this.cloneNode(true);
                    this.parentNode.replaceChild(clone, this);
                });

                document.addEventListener('touchstart', function(e) {
                    if (e && e.target && e.target.classList && e.target.classList.contains('vjs-poster')) {
                        videoStartTime = (new Date()).getTime();
                        videoInitialX = e.changedTouches[0].pageX;
                    }
                }, true);

                document.addEventListener('touchend', function(e) {
                    
                    if (e && e.target && e.target.classList && e.target.classList.contains('vjs-poster')) {

                        // console.log((new Date()).getTime() - videoStartTime);
                        // console.log(Math.abs(videoInitialX - e.changedTouches[0].pageX));

                        if ( ((new Date()).getTime() - videoStartTime < 200) &&
                             (Math.abs(videoInitialX - e.changedTouches[0].pageX) < 20) ) {

                            e.preventDefault();
                            e.stopPropagation();
                            e.stopImmediatePropagation();

                            var thisVideo = $(e.target).parents('slide').removeClass('paused')
                                .addClass('playing').find('video')[0];
                            if (!thisVideo) return false;

                            thisVideo.play();
                            
                            // thisVideo.addEventListener('ended', function(e) {
                            // thisVideo.addEventListener('abort', function(e) {
                            if (!thisVideo.classList.contains('suspend-wired')) {
                                thisVideo.addEventListener('suspend', function(e) {
                                    setTimeout(function() {
                                        $(thisVideo).parents('slide').addClass('paused');
                                    }, 500);
                                });
                                thisVideo.classList.add('suspend-wired');
                            }

                            return false;

                        }
                    }
                }, true);

            }, 3000);

        }

        /**


         ###  ######      #     ######
          #   #     #    # #    #     #
          #   #     #   #   #   #     #
          #   ######   #     #  #     #
          #   #        #######  #     #
          #   #        #     #  #     #
         ###  #        #     #  ######

         #     #  ###  ######   #######  #######
         #     #   #   #     #  #        #     #
         #     #   #   #     #  #        #     #
         #     #   #   #     #  #####    #     #
          #   #    #   #     #  #        #     #
           # #     #   #     #  #        #     #
            #     ###  ######   #######  #######


        */

        // super-simple video handling for the iPad
        if ($('html').hasClass('device-ipad')) {

            new function() {

                /*
                    ** This is fix for ipad to hide the caption while you are watching the video
                    */
                    document.addEventListener('touchstart', function(e) {
                       if (e && e.target && (e.target.tagName === 'VIDEO' || e.target.classList.contains('vjs-poster'))) {

                           e.target.onplay = function() {
                               var all = document.getElementsByClassName('new-age-caption-overlay new-age-caption-overlay-reverse');

                               for (var i = 0, max = all.length; i < max; i++) {
                                   all[i].style.visibility = 'hidden';
                               }
                           };

                           e.target.onpause = function() {
                               var all = document.getElementsByClassName('new-age-caption-overlay new-age-caption-overlay-reverse');

                               for (var i = 0, max = all.length; i < max; i++) {
                                   all[i].style.visibility = 'visible';
                               }
                           };
                       }
                   }, true);

                // 26 Feb 2015 - taking this whole thing out, as it was
                // contributing to the video playback being funky on the iPad

                return;

                var videoStartTime,
                    videoInitialX;

                document.addEventListener('touchstart', function(e) {
                    if (e && e.target && (e.target.tagName === 'VIDEO' || e.target.classList.contains('vjs-poster'))) {
                        videoStartTime = (new Date()).getTime();
                        videoInitialX = e.changedTouches[0].pageX;
                    }
                }, true);

                document.addEventListener('touchend', function(e) {

                    if (e && e.target && e.target.tagName === 'VIDEO') {

                        // console.log((new Date()).getTime() - videoStartTime);
                        // console.log(Math.abs(videoInitialX - e.changedTouches[0].pageX));

                        if ( ((new Date()).getTime() - videoStartTime < 200) &&
                             (Math.abs(videoInitialX - e.changedTouches[0].pageX) < 20) ) {
                    
                            e.target.controls = true;
                            e.target.play();
                            e.target.parentNode.classList.add('ios-video-playing');
                            e.target.parentNode.parentNode.parentNode.classList.add('ios-video-playing');

                            var thisVideo = e.target;
                            e.target.addEventListener('pause', function(e) {
                                thisVideo.controls = false;
                                thisVideo.parentNode.classList.remove('ios-video-playing');
                                thisVideo.parentNode.parentNode.parentNode.classList.remove('ios-video-playing');
                            });

                        }

                    } else {

                        if (e && e.target && e.target.classList.contains('vjs-poster')) {

                            if ( ((new Date()).getTime() - videoStartTime < 200) &&
                             (Math.abs(videoInitialX - e.changedTouches[0].pageX) < 20) ) {

                                var thisVideo = $(e.target).parent().find('video')[0];

                                $(thisVideo).parent().addClass('ios-video-playing');
                                $(thisVideo).parent().parent().parent().addClass('ios-video-playing');
                                
                                thisVideo.addEventListener('pause', function(e) {
                                    thisVideo.controls = false;
                                    $(thisVideo).parent().removeClass('ios-video-playing');
                                    $(thisVideo).parent().parent().parent().removeClass('ios-video-playing');
                                });
                                
                            }

                        }
                    }

                }, true);

            }();

        }

        /**


         ######   #######   #####   ###  #######  ####### 
         #     #  #        #     #   #        #   #       
         #     #  #        #         #       #    #       
         ######   #####     #####    #      #     #####   
         #   #    #              #   #     #      #       
         #    #   #        #     #   #    #       #       
         #     #  #######   #####   ###  #######  ####### 
                                                          

        */

        // save the existing attrs in the DOM
        $mySlides.find('.item,.inactive-dot').each(function() {

            var $this = $(this);

            // normalize width's (to all use CSS, not image attrs)
            if ($this.attr('width')) {
                $this.css('width', $this.attr('width'));
                $this.removeAttr('width');
            }

            if ($this.attr('height')) {
                $this.css('height', $this.attr('height'));
                $this.removeAttr('height');
            }

            var myElem = $(this)[0];
            for (var a in attrs) {
                var myVal = myElem.style[attrs[a]];
                if (!myVal) continue;
                myVal = myVal.replace(/px/, '');
                if (attrs[a] == 'width' && myVal == 0) continue;
                if (attrs[a] == 'height' && myVal == 0) continue;
                if (myVal == 'auto' || parseInt(myVal) == NaN) continue;
                $this.attr('data-' + attrs[a], parseInt(myVal));
            }

        });

        // Modernizr.csstransforms3d has failed me for the last time ...
        // going to use globalHas3d instead
        if (globalHas3d)
            $slideshowMainElem.find('.slide-stretcher-outer').css(Modernizr.prefixed('transform'), 'none');

        this.resize();

        if (window.deviceCustomType == 'desktop') {
            $(window).on('resize', function() {
                that.resize();
            });
        }


        $active = $('.fso-slide-active .video-js:not(.video-js-inited)');
        if($active.length > 0) {
            initVideoJS($active[0]);
        }
        // init all the videos on the page (doesn't start playing yet)
        setTimeout(function(){

            $('slide .video-js:not(.video-js-inited)').each(function() {
                initVideoJS(this);
            });
        }, 3000);


        /* This is a hack to fix the size of the slide show for mobile devices. */
        $(window).on('orientationchange', function() {
            setTimeout(
                function() {
                    that.resize();
                }, 500);

        });

        if (globalHas3d && Modernizr.csstransitions)
            $slideshowMainElem.find('.slide-stretcher-outer').css(Modernizr.prefixed('transition'), globalTransitionTransformProps[Modernizr.prefixed('transform')] + ' 1s cubic-bezier(0.165, 0.840, 0.440, 1.000)');

        $slideshowMainElem.css('opacity', 1);

        var hammertime;

        if(!fsoSliderCanZoomIn()) {
            $('.slide-zoomer').remove();
        }

        if (Modernizr.touch) {

            if (window.deviceCustomType != 'desktop' && this.touchMode == 'photoswipe') {

                loadJS('/plugins/hammer.min.js', function() {
                    // hook up da M.C.
                    hammertime = new Hammer($mySlideshowWrapper[0]);
                    // hammertime.get('pinch').set({ enable: true });
                    // hammertime.get('pan').set({ direction: Hammer.DIRECTION_ALL });
                    hammertime.on('tap doubletap press swipe', function(e) {
                        // panleft panright

                        /* Someone, pls refactor this. It is terbbile, but I don't have time to mess with this. - AT */

                        if (e.target && e.target.classList) {

                            if (e.target.classList.contains('menu-label') && !e.target.classList.contains('no-mobile-interaction')) {
                                var $mySlideParent = $(e.target).parents('slide').addClass('show');
                                openLightbox($mySlideParent, '<div class="mobile-pac-menu"><div class="mobile-pac-menu--close"></div><ul></ul></div>');
                                $('.mobile-caption-lightbox-overlay').addClass('menu-lightbox');
                                $('.menu-bar-wrapper .menu-bar-item, .menu-bar-wrapper .mobile-menu li').each(function() {
                                    if( $(this).html().trim().length > 0) {
                                        $('.mobile-pac-menu ul').append('<li class="mobile-menu-link" data-class="' +
                                            $(this).attr('data-class') + '">' + $(this).html() + '</li>');
                                    }
                                });
                                // $('.mobile-pac-menu ul').append('<li class="mobile-menu-link" data-class="menu-show">Menu</li>');

                                e.preventDefault();

                                var closeBtn = new Hammer($('.mobile-pac-menu--close')[0]);
                                closeBtn.on('tap doubletap press swipe', function(e) {
                                    $('.mobile-caption-lightbox-overlay').remove();
                                });


                                _.each($('.mobile-pac-menu .mobile-menu-link a'), function(el, key, list){
                                    var mobileMenu = new Hammer(el);
                                    mobileMenu.on('tap doubletap press swipe', function(e) {
                                        var $el = $(e.target).closest('a');

                                        if($el.length > 0 && $el.attr('href').indexOf('#slide') > -1) {  
                                            var slideId = $el.attr('href').replace('#slide', '');

                                            fsoSliderGotoSlide(parseInt(slideId)-1, false);
                                            sliderPositionSlides(true);

                                            $('.mobile-caption-lightbox-overlay').remove();

                                            openPhotoswipe();
                                        }
                                        // return false;
                                    });
                                });


                                return false;
                            }

                            // mobile-pac-menu--close


                            if (e.target.classList.contains('mobile-menu-link')) {


                                switch ($(e.target).attr('data-class')) {
                                    case 'menu-show':
                                        if (currentActiveSlideIdx != 8) {
                                            inTouch = false;
                                            fsoSliderGotoSlide(7, false);
                                            sliderPositionSlides(true);
                                        }
                                        break;
                                    case 'lad-show':
                                        if (currentActiveSlideIdx != 10) {
                                            inTouch = false;
                                            fsoSliderGotoSlide(9, false);
                                            sliderPositionSlides(true);
                                        }
                                        break;
                                    case 'hi-show':
                                        if (currentActiveSlideIdx != 24) {
                                            inTouch = false;
                                            fsoSliderGotoSlide(23, false);
                                            sliderPositionSlides(true);
                                        }
                                        break;
                                    case 'aola-show':
                                        if (currentActiveSlideIdx != 53) {
                                            inTouch = false;
                                            fsoSliderGotoSlide(52, false);
                                            sliderPositionSlides(true);
                                        }
                                        break;
                                    case 'asho-show':
                                        if (currentActiveSlideIdx != 34) {
                                            inTouch = false;
                                            fsoSliderGotoSlide(33, false);
                                            sliderPositionSlides(true);
                                        }
                                        break;
                                }
                                /*
                                e.preventDefault();
                                e.stopPropagation();
                                e.stopImmediatePropagation();
                                return false;
                                */
                                return;
                            }
                            
                        }

                        /*
                        if (e.type == 'panup' || e.type == 'pandown') {
                            console.log(e);
                            document.body.scrollTop = -e.deltaY;
                            return;
                        }
                        */

                       // hammer might break if called too quickly, workaround 
                       try {
                           openPhotoswipe();
                       } catch (error) {
                            console.error(error);
                            Sentry.captureException(error);
                       }

                        return false;

                    });
                    that.openPhotoswipe = openPhotoswipe;
                    function openPhotoswipe(startSlideIndex) {

                        if (!window.galleryItems) return console.error('we are too early');
                        // if ($(e.target).hasClass('cancel-photoswipe-zoom') || $(e.target).parents('.cancel-photoswipe-zoom').length) return;

                        EventTracker.trackPhotoswipe("Open");

                        // console.log(e.type);

                        // e.preventDefault();
                        // e.stopPropagation();
                        // e.stopImmediatePropagation();

                        // $('.pswp .pswp__container').html($('.pswp .pswp__container').html().replace(/<slider /g, '<slide '));

                        // initialize PhotoSwipe
                        // @docs http://photoswipe.com/documentation/api.html
                        // @ref http://photoswipe.com/documentation/custom-html-in-slides.html
                        // @demo http://codepen.io/dimsemenov/pen/MYexrm
                        // @download https://github.com/dimsemenov/PhotoSwipe/tree/master/dist
                        var activeSlide = currentActiveSlideIdx;
                        if(startSlideIndex) {
                            activeSlide = startSlideIndex;
                        }
                        window.gallery = new PhotoSwipe(document.querySelectorAll('.pswp')[0], PhotoSwipeUI_Default, galleryItems, {
                            index: Math.max(0, activeSlide),
                            history: false,
                            maxSpreadZoom: 1,
                            getDoubleTapZoom: function (isMouseClick, item) {
                                return item.initialZoomLevel;
                            },
                            // UI options
                            zoomEl: false
                        });

                        var initedSlideChange = false;
                        
                        gallery.listen('afterChange', function() {

                            /*

                            fsoSliderGotoSlide(gallery.getCurrentIndex(), false);
                            sliderPositionSlides(true);

                            $mySlides.eq(currentActiveSlideIdx).find('img[data-src]:not([src])').each(function() {
                                $(this).attr('src', $(this).attr('data-src'));
                            });
                            
                            */

                            currentActiveSlideIdx = gallery.getCurrentIndex();
                            // history.pushState({}, '', '#slide' + (currentActiveSlideIdx+1) );
                            replaceHash('slide' + (currentActiveSlideIdx+1));
                            
                            // prevents from firing EventTracker.trackSlideView twice
                            if(initedSlideChange) {
                                EventTracker.trackSlideView(currentActiveSlideIdx+1);
                            }
                            initedSlideChange = true;
                            
                            var captionLength = $mySlides.eq(currentActiveSlideIdx).find('.text-item').text();
                            if (captionLength && captionLength.length > 500) {
                                $('.pswp .pswp__caption__center').addClass('small-captions');
                            } else {
                                $('.pswp .pswp__caption__center').removeClass('small-captions');
                            }

                            // add class to wrapper with active slide number
                            $(gallery.container).closest('.pswp').attr('active-slide', currentActiveSlideIdx + 1);

                         
                            /*
                                If device less then 768px then show nice captions which can be hidden/shown on tap and dont show caption 1 slide for smp slideshow. covers whole screen.
                            */
                            if($( document ).width() <= 768 && currentActiveSlideIdx != 0 && window.location.href  != "/churches/bringing-scientology-world/scientology-media-productions.html" ) {
                                var captionHtml = "";
                                // if($mySlides.eq(currentActiveSlideIdx).find('.text-item').length > 0) {
                                //     captionHtml += $mySlides.eq(currentActiveSlideIdx).find('.text-item').html()
                                // }
                                $mySlides.eq(currentActiveSlideIdx).find('.text-item').each(function() {
                                    if($(this).attr('marked') == 'true' || $(this).closest('[marked]').length > 0 || $(this).closest('.caption').length > 0 ) {
                                        return;
                                    }
                                    var classes = $(this).attr('class').split(' ').filter(function(c) {
                                        return c.indexOf('text-item-') == 0;
                                    }).join(' ');

                                    $(this).attr('marked','true');
                                    if(captionHtml != "") {
                                        captionHtml += "<br/>"
                                    }
                                    captionHtml += '<div class="photoswipe-text-caption ' + classes+'">' + $(this).html() + '</div>';
                                });

                                $mySlides.eq(currentActiveSlideIdx).find('.floater-texter').each(function() {
                                    if($(this).attr('marked') == 'true' || $(this).closest('[marked]').length > 0 || $(this).closest('.caption').length > 0 ) {
                                        return;
                                    }
                                    $(this).attr('marked','true');
                                    if(captionHtml != "") {
                                        captionHtml += "<br/>"
                                    }
                                    captionHtml += $(this).html();
                                });

                                $mySlides.eq(currentActiveSlideIdx).find('.text-item, .floater-texter').each(function() {
                                    $(this).removeAttr('marked');
                                });
                                
                                // $('.pswp__caption__center').html( $mySlides.eq(currentActiveSlideIdx).find('.text-item').html() );

                                // double captions, probably need to add attr to the slide
                                if(window.location.pathname == "/scientology-today/events/new-years-2020.html") {
                                    var html = "";
                                    $mySlides.eq(currentActiveSlideIdx).find('.text-item').each(function(index, el){
                                        if($(el).find('.lead-titleLine').length > 0) {
                                            var addHtml = $(el).html();
                                            if(index > 0) {
                                                addHtml = '<div class="mt-2">' + addHtml + '</div>';
                                            }
                                            html += addHtml;
                                        }
                                    });
                                    if(html != "") {
                                        $('.pswp__caption__center').html(html);
                                    }
                                }

                                // for band overlay
                                // if($mySlides.eq(currentActiveSlideIdx).find('.overlay-item--bar .floater-texter').length > 0 && 
                                // $mySlides.eq(currentActiveSlideIdx).find('.overlay-item--bar .floater-texter').closest('.text-item').length == 0) {
                                //     if(captionHtml != "") {
                                //         captionHtml += "<br/><br/> "
                                //     }
                                //     captionHtml += $mySlides.eq(currentActiveSlideIdx).find('.overlay-item--bar .floater-texter').html();
                                // }

                                $('.pswp__caption__center').html( captionHtml );

                                $('.pswp__caption').removeClass('pswp__caption--empty');
                                $mySlides.eq(currentActiveSlideIdx).find('.text-item').addClass('pswp__caption--empty');
                            }

                            if ($mySlides.eq(currentActiveSlideIdx).find('.cd-image-container').length) {
                                var $container = $(gallery.container).closest('.pswp').find('.cd-image-container');
                                $container.removeClass('cd-image-container__inited');
                                initComparison();
                                setTimeout(() => {
                                    $container.click();
                                }, 800);
                            }


                            // dont show a big smp caption for SMP slideshow
                            if($( document ).width() <= 768 && currentActiveSlideIdx == 0 && $mySlides.eq(currentActiveSlideIdx).find('.single-video-slide-caption').length > 0 ) {
                                $('.pswp__caption__center').html('');
                            }

                            if($(gallery.currItem.container).find('.video-js').length) {
                                playVideoJS( $(gallery.currItem.container).find('.video-js') );
                                trackEvent('Video', 'Play', 'Slide ' + (currentActiveSlideIdx+1));
                            }
                           
                        });

                        gallery.listen('pointerUp', () => {
                            // refresh to update captions
                            setTimeout(function() {
                                gallery.shout('afterChange')
                            }, 1000);
                        });

                        gallery.listen('resize', function() {
                            var windowHeight = $(window).height();
                            var slideHeight = 575 + 50;
                            if(windowHeight < slideHeight) {
                                var scale = windowHeight / slideHeight;
                                $('.mobile-styles').remove();
                                $("<div class='mobile-styles' />", {
                                    html: '&shy;<style> .pswp__zoom-wrap { transform-origin: center; ' + Modernizr.prefixed('transform') +  ': scale(' + scale + ') !important;}' + '</style>'
                                  }).appendTo("body");   
                            }
                        });

                        gallery.listen('close', function() {
                            EventTracker.trackPhotoswipe("Close");
                            //updating numbers on slide
                            $('.fso-slide-mobile-numbers').html($('.pswp__counter').text());

                            $slideshowMainElem.addClass('force-show-spinner');
                            $slideshowMainElem.find('.slide-stretcher-outer').removeClass('invisible');

                            /* see a much ligher-weight alternative right below
                            fsoSliderGotoSlide(gallery.getCurrentIndex(), false);
                            sliderPositionSlides(true);
                            */
                            currentActiveSlideIdx = gallery.getCurrentIndex();
                            $('slide.fso-slide-active').removeClass('fso-slide-active');
                            $mySlides.eq(currentActiveSlideIdx).addClass('fso-slide-active');

                            // FIXME apple dots

                            $mySlides.eq(currentActiveSlideIdx).find('img[data-src]:not([src])').each(function() {
                                var $this = $(this);
                                var imgSrc = $this.attr('data-src');

                                // do any dynamic size adjustments here
                                if ($this.attr('data-height') && window.determineImageSources) {
                                    imgSrc = determineImageSources(this)[0];
                                }

                                $this.attr('src', imgSrc);
                            });

                            setTimeout(function() {
                                $slideshowMainElem.removeClass('force-show-spinner');
                            }, 500);

                            // just for good measure - as photoswipe will do a history.back() on closing
                            // history.pushState({}, '', '#slide' + (currentActiveSlideIdx+1) );
                            // history.pushState({}, '', '#slide' + (currentActiveSlideIdx+1) );

                            hammertime.options.enable = true;

                        });

                        // just for good measure - as photoswipe will do a history.back() on closing
                        // history.pushState({}, '', '#slide' + (currentActiveSlideIdx+1) );

                        $slideshowMainElem.find('.slide-stretcher-outer').addClass('invisible');

                        // pause hammer's touch handler for the time of photoswipe (optimization)
                        hammertime.options.enable = false;
                        
                        // open photoswipe
                        gallery.init();

                        /* not needed

                        if (e.type == 'panleft' || e.type == 'swipeleft') {
                            setTimeout(function() {
                                gallery.prev();
                            }, 400);
                        }

                        if (e.type == 'panright' || e.type == 'swiperight') {
                            setTimeout(function() {
                                gallery.prev();
                            }, 400);
                        }

                        */
                    }

                });
                

            } else {

                $slideHolderDom.find('slide').each(function() {
                    if ($(this).find('.text-item').length) {
                        $(this).append('<div class="text-info-mobile glyphicon-info-sign"></div>');
                    }
                    if ($(this).hasClass('slide-template-new-c-with-band') && $(this).find('.floater-texter.editable').length) {
                        $(this).append('<div class="text-info-mobile glyphicon-info-sign"></div>');
                    }
                });

                slideshowMainElem.addEventListener('touchstart', function(e) {
                    onTouchStart(e);
                    fireEvent('userInteraction', 'touch-start');
                    return false;
                }, true);

                slideshowMainElem.addEventListener('touchmove', function(e) {
                    onTouchMove(e);
                    return false;
                }, true);

                slideshowMainElem.addEventListener('touchend', function(e) {
                    onTouchEnd(e);
                    return false;
                }, true);

                slideshowMainElem.addEventListener('touchcancel', function(e) {
                    onTouchEnd(e);
                    return false;
                }, true);

                // if close to slideshow, snap it
                document.addEventListener('touchend', function(e) {

                    if (Math.abs(window.scrollY - slideshowScrollTop) < 20) {
                        window.scrollTo(window.scrollX, slideshowScrollTop);
                    }

                    // just being safe here ...
                    if (!e || !e.target || !e.target.classList) return;

                    if (isIpad) {

                        if (inTouch && $(e.target).parents('slide').length) {
                            onTouchEnd(e);
                            return;
                        }

                        if (e.target.classList.contains('slide-arrow-holder') ||
                            $(e.target).parents('.slide-arrow-holder').length) {

                            var $me = $(e.target);
                            if ($me.hasClass('slide-left-arrow2') || $me.parents('.slide-left-arrow2').length) {
                                sliderMovePrev();
                            } else {
                                that.sliderMoveNext();
                            }

                            e.preventDefault();
                            e.stopPropagation();
                            e.stopImmediatePropagation();
                            return false;
                        }

                        if (e.target.classList.contains('menu-label') && !e.target.classList.contains('no-mobile-interaction')) {
                            $slideshowMainElem.addClass('always-show');
                            e.preventDefault();
                            e.stopPropagation();
                            e.stopImmediatePropagation();
                            return;
                        }

                    }

                    if (e.target.classList.contains('menu-label') && !e.target.classList.contains('no-mobile-interaction')) {
                        var $mySlideParent = $(e.target).parents('slide').addClass('show');
                        openLightbox($mySlideParent, '<div class="mobile-pac-menu"><div class="mobile-pac-menu--close"></div><ul></ul></div>');
                        $('.mobile-caption-lightbox-overlay').addClass('menu-lightbox');
                        $('.fso-slide-imagemap.show-overlay-mobile-menu .active-dot.active-dot-slider').each(function() {
                            $('.mobile-pac-menu ul').append('<li class="mobile-menu-link" data-class="' +
                                $(this).attr('data-class') + '">' + $(this).html() + '</li>');
                        });
                        $('.mobile-pac-menu ul').append('<li class="mobile-menu-link" data-class="menu-show">Menu</li>');

                        e.preventDefault();
                        e.stopPropagation();
                        e.stopImmediatePropagation();
                        return false;
                    }

                    if (e.target.classList.contains('mobile-menu-link')) {
                        closeLightbox($('slide.show').removeClass('show'));
                        switch ($(e.target).attr('data-class')) {
                            case 'menu-show':
                                if (currentActiveSlideIdx != 8) {
                                    inTouch = false;
                                    fsoSliderGotoSlide(7, false);
                                    sliderPositionSlides(true);
                                }
                                break;
                            case 'lad-show':
                                if (currentActiveSlideIdx != 10) {
                                    inTouch = false;
                                    fsoSliderGotoSlide(9, false);
                                    sliderPositionSlides(true);
                                }
                                break;
                            case 'hi-show':
                                if (currentActiveSlideIdx != 24) {
                                    inTouch = false;
                                    fsoSliderGotoSlide(23, false);
                                    sliderPositionSlides(true);
                                }
                                break;
                            case 'aola-show':
                                if (currentActiveSlideIdx != 53) {
                                    inTouch = false;
                                    fsoSliderGotoSlide(52, false);
                                    sliderPositionSlides(true);
                                }
                                break;
                            case 'asho-show':
                                if (currentActiveSlideIdx != 34) {
                                    inTouch = false;
                                    fsoSliderGotoSlide(33, false);
                                    sliderPositionSlides(true);
                                }
                                break;
                        }
                        /*
                        e.preventDefault();
                        e.stopPropagation();
                        e.stopImmediatePropagation();
                        return false;
                        */
                        return;
                    }

                    if (e.target.classList.contains('text-info-mobile')) {
                        var $mySlideParent = $(e.target).parents('slide').addClass('show');
                        if (true || $mySlideParent.find('div.text-item').text().length > 200) {
                            if ($mySlideParent.hasClass('slide-template-new-c-with-band') && $mySlideParent.find('.floater-texter.editable').length) {
                                openLightbox($mySlideParent, $mySlideParent.find('.floater-texter.editable').html());
                            } else {
                                openLightbox($mySlideParent, $mySlideParent.find('div.text-item').html());
                            }
                        } else {
                            $('body').addClass('mobile-text-info-showing');
                        }
                        e.preventDefault();
                        e.stopPropagation();
                        e.stopImmediatePropagation();
                        return false;
                    }

                    if (e.target.classList.contains('text-item') ||
                        e.target.classList.contains('mobile-caption-lightbox-overlay') ||
                        $(e.target).parents('.mobile-caption-lightbox-overlay').length) {
                        closeLightbox($('slide.show').removeClass('show'));
                        $('body').removeClass('mobile-text-info-showing');
                        e.preventDefault();
                        e.stopPropagation();
                        e.stopImmediatePropagation();
                        return false;
                    }

                }, true);

            }

        }

        // for mobile iOS, force to show the poster images instead of the <video> tags, so they
        // are draggable
        if (globalIsIOS) {
            $slideHolderDom.find('slide video').css('display', 'none');
            $slideHolderDom.find('slide .vjs-poster').css('display', 'block');
        }

        logger.debug('responsive-slider.js end of init()');

    }

    // figure out what's the first slide (this will count slides starting with '1', not '0' to
    // be consistent with the hashtags [#slide1, #slide2, ...])
    me.determineFirstSlide = function() {

        // if the firstSlide was already set on init, honor that
        if (this.startSlide) return this.startSlide;

        // if there's a video tag matching a video in a slide (?video=...), use that
        if ((globalGetParams.video || globalGetParams['video-play']) &&
            $slideshowMainElem.find('slide .video-js').length > 0) {

            var myVideoParam = globalGetParams.video || globalGetParams['video-play'];

            var slideMatching = _.reduce($slideshowMainElem.find('slide .video-js'), function(m, v) {
                if (m != null) return m;
                var mySlideId = $mySlides.index($(v).parents('slide'));

                var cloned = $(v).parents('slide') && $(v).parents('slide')[0].className && $(v).parents('slide')[0].className.indexOf("clone") != -1;

                if (getVideoIdForSlide(mySlideId) == myVideoParam && !cloned) return mySlideId;
            }, null);


            if (slideMatching !== void 0) {
                // autoplay if needed
                if (this.autoplayVideos) startVideoForSlide(slideMatching);
                return parseInt(slideMatching) + 1;
            }

            // if there was a slide=... query param use that
            if (globalGetParams.slide) {
                replaceVideoSource(globalGetParams.slide - 1, myVideoParam);
                if (this.autoplayVideos) startVideoForSlide(globalGetParams.slide - 1);
                return globalGetParams.slide;
            }

            // otherwise, let it play on first slide
            replaceVideoSource(0, myVideoParam);
            return 1;

        }

        if (location.hash) {
            var newSlideIdx = parseInt(location.hash.substring(1).replace(/slide/, '')) - 1;
            if (!isNaN(newSlideIdx) && newSlideIdx >= 0 && newSlideIdx <= totalSlides - 1)
                return newSlideIdx + 1;
        } else if(globalGetParams.slide) {
            var newSlideIdx = parseInt(globalGetParams.slide) - 1;
            if (!isNaN(newSlideIdx) && newSlideIdx >= 0 && newSlideIdx <= totalSlides - 1)
                return newSlideIdx + 1;
        }

        // otherwise, start at the beginning
        return 1;

    }

    ///////////////////////
    // Basic video handling

    function getVideoIdForSlide(slideId) {
        var $myElem = $mySlides.eq(slideId).find('.video-js');
        if (!$myElem) return null;
        var thisVideo = $myElem.attr('class') && $myElem.attr('class').match(/vjs-video-id-[^ ]*/);
        return thisVideo && thisVideo.length ? thisVideo[0].replace(/vjs-video-id-/, '') : null;
    }

    function startVideoForSlide(slideId) {

        // can't autoplay on iOS (without user interaction)
        if (globalIsIOS) return;

        logger.debug('startVideoForSlide, ' + slideId);

        var $myVideoJsElem = $mySlides.eq(slideId).find('.video-js');

        if ($myVideoJsElem.length == 0) return; // no video elem - sorry

        // only autoplay for first time, per video ID
        // var videosPlayed = (cookieMonster.get('gsc_headers_videos_autoplayed') || '');
        // var videoId = getVideoIdForSlide(slideId);
        // if (!globalGetParams['video-play'] && _.contains(videosPlayed.split(','), videoId)) return; // already played

        // if (!(_.contains(videosPlayed.split(','), videoId)))
        //     videosPlayed = videosPlayed + (videosPlayed == "" ? "" : ",") + videoId;
        
        // cookieMonster.set('gsc_headers_videos_autoplayed', videosPlayed, void 0, '/');

        // fire the event as well
        // console.log('videoAutoplay fired');
        fireEvent('videoAutoplay');
        playVideoJS($myVideoJsElem);

    }

    function stopVideoForSlide(slideId) {

        logger.debug('stopVideoForSlide, ' + slideId);

        var $myVideoJsElem = $mySlides.eq(slideId).find('.video-js');

        if ($myVideoJsElem.length == 0) return; // no video elem - sorry

        var videoInst;
        if ($myVideoJsElem.prop('tagName') !== 'VIDEO') {
            videoInst = videojs($myVideoJsElem.get(0));
        }

        if (videoInst) videoInst.pause();
    }

    // NOTE: this method is assisted by page.html outputting the video data into a global JS var
    function replaceVideoSource(slideId, videoId) {

        if (!window.globalVideoSrc) return;

        logger.debug('replaceVideoSource, ' + slideId + ', ' + videoId);

        var $myVideoJsElem = $mySlides.eq(slideId).find('.video-js');

        var videoInst;
        if ($myVideoJsElem.prop('tagName') !== 'VIDEO') {
            var videoInst = videojs($mySlides.eq(slideId).find('.video-js').get(0));
        }

        var oldVideoId = getVideoIdForSlide(slideId);
        $mySlides.eq(slideId).find('.video-js').removeClass('vjs-video-id-' + oldVideoId)
            .addClass('vjs-video-id-' + videoId);

        if (videoInst) {
            if (globalVideoSrc.match(/.*\.mp4.*/)) {
                videoInst.src({ type: 'video/mp4', src: globalVideoSrc });
            } else {
                videoInst.src(globalVideoSrc);
            }
        } else {
            if (globalVideoSrc.match(/.*\.mp4.*/)) {
                $myVideoJsElem.find('source').eq(0).attr('src', globalVideoSrc).attr('type', 'video/mp4');
                $myVideoJsElem.find('source:not([src="' + globalVideoSrc + '"])').remove();
            } else {
                $myVideoJsElem.find('source').eq(0).attr('src', globalVideoSrc);
            }
        }

        try {
            if (videoInst) {
                window.globalVideoThumb && videoInst.poster(globalVideoThumb);
            } else {
                window.globalVideoThumb && $myVideoJsElem.attr('poster', globalVideoThumb);
            }
        } catch (swallow) {}

        if (videoInst) {
            $mySlides.eq(slideId).find('.vjs-poster').css('display', 'block');
        }

        return;
    }

    ////////////////////////
    // Minimalistic lightbox

    function openLightbox($aDomParent, aInnards) {
        $aDomParent.addClass('show-lightbox');
        $('body').addClass('show-lightbox-caption').append('\
            <div class="mobile-caption-lightbox-overlay">\
                <table class="mobile-caption-lightbox-inner">\
                    <tr class="mobile-caption-lightbox-filler"></tr>\
                    <tr class="mobile-caption-lightbox"><td></td></tr>\
                    <tr class="mobile-caption-lightbox-filler"></tr>\
                </table>\
            </div>');
        $('.mobile-caption-lightbox td').html(aInnards);
    }

    function closeLightbox($aDomParent) {
        $aDomParent.removeClass('show-lightbox');
        $('body').removeClass('show-lightbox-caption');
        $('.mobile-caption-lightbox-overlay').remove();
    }

    /////////////////
    // Touch handlers
    // some ideas @from http://padilicious.com/code/touchevents/
    // and @from padilicious.com
    // and @from macosxautomation.com


    
    // touchCurrentLeft = 0,
    var initialX,
        // initialY,
        currentX,
        // currentY,
        startTime,
        // lockMode,
        myMinSlideLeft,
        borkedTouch = false,
        myTextReset = true,
        inTouch = false;

    // figure out whether or not touches should be handled for the current e.target
    function canTouchThis(e) {
        return e.target.tagName == 'SLIDE' || $(e.target).parents('slide').length;
    }

    // new lock handling
    var start_touchx = null,
        start_touchy = null,
        max_touchx = 0,
        max_touchy = 0,
        locked_x = false,
        locked_y = false;

    function onTouchStart(e) {

        if (borkedTouch || !canTouchThis(e)) return;
        if (e.touches.length > 1) {
            borkedTouch = true;
            return onTouchEnd(e);
        }

        // end off any ongoing touches cleanly
        if (inTouch) globalAnimationController.cancelAnimation($('.slide-holder'));

        // store initial x and y pos
        currentX = initialX = e.changedTouches[0].pageX;
        // currentY = initialY = e.changedTouches[0].pageY;
        startTime = (new Date()).getTime();
        // lockMode = false;
        borkedTouch = false;
        inTouch = true;

        // cancel all ongoing transitions

        // globalAnimationController.cancelAnimation($('.slide-holder'));
        // if (mySlideholderElem.style[myTransform] != 'none') mySlideholderElem.style[myTransform] = 'none';
        // sliderEndAnimation();
        sliderPositionSlides(true);

        //myTextReset = false;

        // touchCurrentLeft = 0;

        // new lock handling
        start_touchx = e.touches[0].clientX;
        start_touchy = e.touches[0].clientY;
        max_touchx = 0;
        max_touchy = 0;
        locked_x = false;
        locked_y = false;

    }

    function onTouchMove(e) {

        // console.log('touchMove ' + e.changedTouches[0].pageX);
        
        // Cancel touch move if target has parent .cd-image-container
        if ($(e.target).closest('.cd-image-container').length > 0) {
            return;
        }

        if (!inTouch || borkedTouch) return;
        // if (!canTouchThis(e)) return;
        if (e.touches.length > 1) return onTouchEnd(e);


        // new lock handling
        if (locked_y) return true;

        max_touchx = Math.max(max_touchx, Math.abs(e.changedTouches[0].clientX - start_touchx));
        max_touchy = Math.max(max_touchy, Math.abs(e.changedTouches[0].clientY - start_touchy));

        if (!locked_x && !locked_y && max_touchx > 12) {
        // if (!locked_x && ((max_touchx > 12 && max_touchy < 7) || (max_touchx > 20 && max_touchy < 10) || (max_touchx > 70 && max_touchy < 30))) {
            locked_x = true;
        }

        if (!locked_x && !locked_y && max_touchy > 12) {
        // if (!locked_y && ((max_touchx < 7 && max_touchy > 12) || (max_touchx < 10 && max_touchy > 20) || (max_touchx < 30 && max_touchy > 70))) {
            locked_y = true;

            // transfer the elem back to it's original position
            mySlideholderElem.style[myTransform] = 'translate3d(' +
            ((isRTL ? 1 : -1) * (parseInt(-slideholderDelta / 2) + currentActiveSlideIdx * fsoSlideWidth2 +
                (isCloned ? totalSlides * fsoSlideWidth2 : 0))) +
            'px,0px,0px)';

            return;
        }

        var myX = e.changedTouches[0].pageX;
        // var myXMoved = myX - currentX;

        /*
        if (myXMoved == 0) {
            console.log('zero');
            if (locked_x) e.preventDefault();
            return; // did not really move
        }
        */

        // var myXTotalMoved = myX - initialX;

        currentX = myX;

        // var myY = e.changedTouches[0].pageY;
        // var myYMoved = myY - currentY;
        // var myYTotalMoved = myY - initialY;

        // currentY = myY;

        // var myLeft = touchCurrentLeft;
        // myLeft += myXMoved;
        
        var myLeft = myX - initialX;

        // make sure left isn't out of bounds
        if (currentActiveSlideIdx == 0 && ((isRTL && myLeft < 10) || (!isRTL && myLeft > 10))) {
            myLeft -= myLeft * 0.7;
        }

        if (currentActiveSlideIdx == totalSlides - 1 && ((isRTL && myLeft > 10) || (!isRTL && myLeft < 10))) {
            myLeft -= myLeft * 0.7;
        }

        /*
        if ((myYTotalMoved > 20 || myXTotalMoved) && !myTextReset) {
            // FIXME
            $('.mobile-landing-arc .slide .slide-text').css('opacity', 0).css('display', 'none');
            //$('.mobile-landing-arc .slide .slide-text').css('opacity', 0);
            myTextReset = true;
            / *
            myTextHideTimeoutHandle = setTimeout(function() { $('.mobile-landing-arc .slide .slide-text').css('display', 'none'); }, 500);
            * /
        }
        */

        mySlideholderElem.style[myTransform] = 'translate3d(' +
            (myLeft + (isRTL ? 1 : -1) * (parseInt(-slideholderDelta / 2) + currentActiveSlideIdx * fsoSlideWidth2 +
                (isCloned ? totalSlides * fsoSlideWidth2 : 0))) +
            'px,0px,0px)';

        // touchCurrentLeft = myLeft;

        /* taken out - more full-featured touch locking was added

        // if they move horizontally over a certain amount, then we go into
        // 'lock mode', which prevents the page from vertically sliding
        if (!lockMode && Math.abs(myXTotalMoved) > 15) {
            lockMode = true;
        }
        if (lockMode) e.preventDefault();

        */

        if (locked_x) e.preventDefault();

    }

    function onTouchEnd(e) {

        if ($(e.target).closest('.cd-image-container').length > 0) {
            return;
        }

        if (!inTouch) return;
        // if (!canTouchThis(e)) return;
        if (e.touches.length == 0) borkedTouch = false;

        if (e && e.target && e.target.classList && e.target.classList.contains &&
            e.target.classList.contains('skip-touch-handling')) {
            return false;
        }

        var myEndTime = (new Date()).getTime();
        var myTotalTime = myEndTime - startTime;

        // var myLeft = touchCurrentLeft;

        // if the slide number is the same as it used to be, then have a look
        // at the motion and see if that indicates that we should change the
        // slide, even if it's not more than 50%
        var myXPitch = currentX - initialX;
        // var myYPitch = currentY - initialY;

        var mySlideNum = currentActiveSlideIdx;

        if (myXPitch > fsoSlideWidth2 / 2) {
            mySlideNum += (isRTL ? 1 : -1);
        } else if (myXPitch < -fsoSlideWidth2 / 2) {
            mySlideNum += (isRTL ? -1 : 1);
        }

        /*
        if (mySlideNum == currentActiveSlideIdx) {
            if (myXPitch > 75 || (myXPitch > 30 && myTotalTime < 250)) {
                mySlideNum -= 1;
            }
            else if (myXPitch < -75 || (myXPitch < -30 && myTotalTime < 250)) {
                mySlideNum += 1;
            }
        }
        */

        /*
        // for non-IOS (Android) see if this is actually just a "click"
        if (mySlideNum == currentActiveSlideIdx && myXPitch < 10 && myYPitch < 10 && myTotalTime < 250) {

            // FIXME on this whole thing

            // toggle off and on
            if (!myTextReset) {

                $('.mobile-landing-arc .slide .slide-text').css('opacity', 0).css('display', 'none');
                myTextReset = true;

            } else {

                / *
                if (myTextHideTimeoutHandle) {
                    clearTimeout(myTextHideTimeoutHandle);
                    myTextHideTimeoutHandle = null;
                }
                * /
                myTextReset = false;

                $('.mobile-landing-arc .slide:eq('+mySlideNum+') .slide-text').css('opacity', 0).css('display', 'block');
                setTimeout(function() {
                    $('.mobile-landing-arc .slide:eq('+mySlideNum+') .slide-text').css('opacity', 0.75);
                }, 5);

            }

            / *
            //showVideoForSlide(mySlideNum);
            var myVideoUrl = $('.mobile-landing-arc .slide:eq('+mySlideNum+')').attr('data-video-url');
            // FIXME: should change to rtsp url
            document.location = myVideoUrl;
            //alert(myVideoUrl);
            * /
            return;

        }
        */

        // detect swipes
        var isSwipe = false;
        if (myTotalTime < 400 && Math.abs(myXPitch) > 20) {
            isSwipe = true;
            if (myXPitch > 20) {
                mySlideNum = currentActiveSlideIdx + (isRTL ? 1 : -1);
            } else {
                mySlideNum = currentActiveSlideIdx + (isRTL ? -1 : 1);
            }
        }

        // correct mySlideNum if it's out of bounds
        if (mySlideNum < 0) {
            mySlideNum = 0;
        } else if (mySlideNum >= totalSlides) {
            mySlideNum = totalSlides - 1;
        }

        /*
        var myNewLeft = 0;
        if (mySlideNum == currentActiveSlideIdx + 1) {
            var myNewLeft = -fsoSlideWidth2;
        }
        if (mySlideNum == currentActiveSlideIdx - 1) {
            var myNewLeft = fsoSlideWidth2;
        }
        */

        myNewLeft = (isRTL ? 1 : -1) * (parseInt(-slideholderDelta / 2) + mySlideNum * fsoSlideWidth2);
        if (isCloned) myNewLeft += (isRTL ? 1 : -1) * totalSlides * fsoSlideWidth2;

        // removed .addClass('sliding') - not really needed here, saves a style recalculation
        if (false && isSwipe) {
            if (currentActiveSlideIdx != mySlideNum) {
                // if (mySlideholderElem.style[myTransform] != 'none') mySlideholderElem.style[myTransform] = 'none';
                fsoSliderGotoSlide(mySlideNum, false);
            }
            sliderPositionSlides(true);
        } else {
            globalAnimationController.animate2d($('.slide-holder'), {
                x: myNewLeft,
                y: 0
            }, (isSwipe ? '.4s cubic-bezier(0.23, 1, 0.32, 1)' : '.5s cubic-bezier(0.23, 1, 0.32, 1)'), function() {
                if (currentActiveSlideIdx != mySlideNum) {
                    // if (mySlideholderElem.style[myTransform] != 'none') mySlideholderElem.style[myTransform] = 'none';
                    fsoSliderGotoSlide(mySlideNum, false);

                   $('.fso-slide-active').removeClass('fso-slide-active');
                   $mySlides.eq(mySlideNum).addClass('fso-slide-active');
                }
                sliderPositionSlides(true);
                inTouch = false;
            });
        }

    }

    // callback when active slide images are loaded
    me.waitForActiveSlide = function(callback, deep) {
        var self = this;
        var maxDeep = 10;

        setTimeout(function(){
            if(self.activeSlideLoaded()) {
                callback();
                return
            }

            if(deep > maxDeep) {
                callback();
            } else {
                self.waitForActiveSlide(callback, deep + 1);
            }
        }, 500);
    }


    me.activeSlideLoaded = function() {
        var $myActiveSlide = $mySlides.eq(currentActiveSlideIdx);
        var loaded = true;
        $myActiveSlide.find('img').each(function() {
            loaded = loaded && this.complete;
        });
        return loaded;
    }

    //////////////////
    // Responsiveness

    // resize everyone
    me.resize = function(stackCounter) {
        var isFirefox = navigator.userAgent.toLowerCase().indexOf('firefox') > -1;

        if (!this.hasLeftSidebar) {

            fsoSlideWidth = this.slidesMax860 ? Math.min(860, $slideshowMainElem.width()) : $slideshowMainElem.width();
            xRatio = fsoSlideWidth / 860;
            var fsoSlideWrapperWidth = $slideshowMainElem.width();

            // if it's taller than viewport, adjust
            var windowHeight = $(window).height();
            if (windowHeight < parseInt(this.fsoSliderZoomHeight * xRatio)) {
                xRatio = windowHeight / this.fsoSliderZoomHeight;
                fsoSlideWidth = parseInt(xRatio * 860);
                fsoSlideWrapperWidth = $(window).width();
            }

            fsoSlideWidth2 = $mySlides.eq(0).outerWidth(true);
            
            slideholderDelta = fsoSlideWrapperWidth - fsoSlideWidth;
            // handle the funky 20px weird "play" on iPad
            if (isIpad) slideholderDelta = 0;

        } else {

            // TODO add in dynamic left bar size
            var currentWidth = $('#banner').width();
            fsoSlideWidth = fsoSlideWidth2 = $mySlides.eq(0).outerWidth(true); // (currentWidth < 860 ? currentWidth : currentWidth - 220);
            xRatio = fsoSlideWidth / 860;
            slideholderDelta = 0;

        }

        slideshowScrollTop = slideshowMainElem.offsetTop;

        // no resizing for IE8-
        if (globalIsIE) return;

        // HACK change the CSS rules as needed

        // FIXME eliminate this
        if (!window.getCSSRule || /Trident/.test(navigator.userAgent)) {

            // window.console && console.error && console.error('getCSSRule function not available!');

            var style = document.createElement('style');
            style.appendChild(document.createTextNode(''));
            document.head.appendChild(style);
            var sheet = style.sheet;
            
            sheet.insertRule('.slide-wrapper slide.slide-templated-new .text-item.animation-left-hold { ' +
                'opacity: 0 !important; ' +
                'transform: translate3d(' + ((isRTL ? 1 : -1) * fsoSlideWidth2) + 'px, 30px, 0px) !important; ' +
                '}', 0);

            if (!window.cancelVerticalCaptionCentering && document.body.className.match(/templated-slider-build-2-1/)) {
                sheet.insertRule('.slide-wrapper slide.slide-templated-new .text-item.animation-left-hold.js-vertical-middle { ' +
                    'opacity: 0 !important; ' +
                    'transform: translate3d(' + ((isRTL ? 1 : -1) * fsoSlideWidth2) + 'px, -25%, 0px) !important; ' +
                    '}', 1);
            }

            sheet.insertRule('.slide-wrapper slide.slide-templated-new .text-item.animation-right-hold { ' +
                'opacity: 0 !important; ' +
                'transform: translate3d(' + ((isRTL ? -1 : 1) * fsoSlideWidth2) + 'px, 30px, 0px) !important; ' +
            '}', 2);
            if (!window.cancelVerticalCaptionCentering && document.body.className.match(/templated-slider-build-2-1/)) {
                sheet.insertRule('.slide-wrapper slide.slide-templated-new .text-item.animation-right-hold.js-vertical-middle { ' +
                    'opacity: 0 !important; ' +
                    'transform: translate3d(' + ((isRTL ? -1 : 1) * fsoSlideWidth2) + 'px, -25%, 0px) !important; ' +
                '}', 3);
            }

            sheet.insertRule('.slide-wrapper slide.slide-templated-new .text-item.animation-left-hold2 { ' +
                'opacity: 1 !important; ' +
                'transform: translate3d(' + ((isRTL ? 1 : -1) * fsoSlideWidth2) + 'px, 0px, 0px) !important; ' +
            '}', 4);
            if (!window.cancelVerticalCaptionCentering && document.body.className.match(/templated-slider-build-2-1/)) {
                sheet.insertRule('.slide-wrapper slide.slide-templated-new .text-item.animation-left-hold2.js-vertical-middle { ' +
                    'opacity: 1 !important; ' +
                    'transform: translate3d(' + ((isRTL ? 1 : -1) * fsoSlideWidth2) + 'px, -50%, 0px) !important; ' +
                '}', 5);
            }

            sheet.insertRule('.slide-wrapper slide.slide-templated-new .text-item.animation-right-hold2 { ' +
                'opacity: 1 !important; ' +
                'transform: translate3d(' + ((isRTL ? -1 : 1) * fsoSlideWidth2) + 'px, 0px, 0px) !important; ' +
            '}', 6);
            if (!window.cancelVerticalCaptionCentering && document.body.className.match(/templated-slider-build-2-1/)) {
                sheet.insertRule('.slide-wrapper slide.slide-templated-new .text-item.animation-right-hold2.js-vertical-middle { ' +
                    'opacity: 1 !important; ' +
                    'transform: translate3d(' + ((isRTL ? -1 : 1) * fsoSlideWidth2) + 'px, -50%, 0px) !important; ' +
                '}', 7);
            }

        } else {
            if (!this.useSimpleSliding && !globalIsMobile && globalHas3d && Modernizr.csstransitions) {
            
                var prefixedTransform = globalTransitionTransformProps[Modernizr.prefixed('transform')];
        
            try {
                // filter stylesheets, shaves off 1 second of load time!
                var filter = new RegExp('(/scss/slideshow/standard-slideshows.css|/_combined/slideshows.scss)');

                // rotate(0deg) is needed to prevent weird font smoothing rendering in zoom mode (see https://gogs.standardadmin.org/sites/www.scientology.org-webstack/issues/106)

                getCSSRule('.slide-wrapper slide .item.text-item.animation-left-hold', '', filter).style.cssText = 'opacity: 0 !important; ' + prefixedTransform + ': translate3d(' + ((isRTL ? 1 : -1) * fsoSlideWidth2) + 'px, 30px, 0px)  rotate(0deg) !important;';
                if (!window.cancelVerticalCaptionCentering && document.body.className.match(/templated-slider-build-2-1/) && getCSSRule('.slide-wrapper slide .item.text-item.animation-left-hold.js-vertical-middle','', filter)) getCSSRule('.slide-wrapper slide .item.text-item.animation-left-hold.js-vertical-middle', '', filter).style.cssText = 'opacity: 0 !important; ' + prefixedTransform + ': translate3d(' + ((isRTL ? 1 : -1) * fsoSlideWidth2) + 'px, -25%, 0px)  !important;';

                getCSSRule('.slide-wrapper slide .item.text-item.animation-right-hold', '', filter).style.cssText = 'opacity: 0 !important; ' + prefixedTransform + ': translate3d(' + ((isRTL ? -1 : 1) * fsoSlideWidth2) + 'px, 30px, 0px)  rotate(0deg) !important;';
                if (!window.cancelVerticalCaptionCentering && document.body.className.match(/templated-slider-build-2-1/) && getCSSRule('.slide-wrapper slide .item.text-item.animation-right-hold.js-vertical-middle','', filter)) getCSSRule('.slide-wrapper slide .item.text-item.animation-right-hold.js-vertical-middle', '', filter).style.cssText = 'opacity: 0 !important; ' + prefixedTransform + ': translate3d(' + ((isRTL ? -1 : 1) * fsoSlideWidth2) + 'px, -25%, 0px)  !important;';

                getCSSRule('.slide-wrapper slide .item.text-item.animation-left-hold2', '', filter).style.cssText = 'opacity: 1 !important; ' + prefixedTransform + ': translate3d(' + ((isRTL ? 1 : -1) * fsoSlideWidth2) + 'px, 0px, 0px)  rotate(0deg) !important;';
                if (!window.cancelVerticalCaptionCentering && document.body.className.match(/templated-slider-build-2-1/) && getCSSRule('.slide-wrapper slide .item.text-item.animation-left-hold2.js-vertical-middle','', filter)) getCSSRule('.slide-wrapper slide .item.text-item.animation-left-hold2.js-vertical-middle', '', filter).style.cssText = 'opacity: 1 !important; ' + prefixedTransform + ': translate3d(' + ((isRTL ? 1 : -1) * fsoSlideWidth2) + 'px, -50%, 0px)  !important;';

                getCSSRule('.slide-wrapper slide .item.text-item.animation-right-hold2', '', filter).style.cssText = 'opacity: 1 !important; ' + prefixedTransform + ': translate3d(' + ((isRTL ? -1 : 1) * fsoSlideWidth2) + 'px, 0px, 0px)  rotate(0deg) !important;';
                if (!window.cancelVerticalCaptionCentering && document.body.className.match(/templated-slider-build-2-1/) && getCSSRule('.slide-wrapper slide .item.text-item.animation-right-hold2.js-vertical-middle','', filter)) getCSSRule('.slide-wrapper slide .item.text-item.animation-right-hold2.js-vertical-middle', '', filter).style.cssText = 'opacity: 1 !important; ' + prefixedTransform + ': translate3d(' + ((isRTL ? -1 : 1) * fsoSlideWidth2) + 'px, -50%, 0px)  !important;';
            } catch(error) {
                console.error(error);
                if(isFirefox &&
                    (!stackCounter || stackCounter < 3)) {
                        if(!stackCounter) {
                            stackCounter = 1;
                        }
                        setTimeout(function(){
                            this.resize(stackCounter + 1);
                        }, 1000);
                }
            }

            }
        }

        // fix up the apple dots again
        fsoSliderRecalculateAppleDots();
        fsoSliderFixAppleDots(currentActiveSlideIdx);

        // div can just resize immediately
        $allNonImageElems.each(function() {
            resizeElem($(this));
        });

        // for images, wait until they are loaded
        $allImageElems.each(function() {
            var $this = $(this);
            if ($this.hasClass('loaded')) {
                // already loaded
                resizeElem($this);
            } else {
                // wait until loaded
                // note: image loading is unreliable in IE
                if (!/Trident/.test(navigator.userAgent)) {
                     $this.on('load', function() {
                        resizeElem($this);
                    });
                } else {
                    setTimeout(function() {
                        resizeElem($this);
                    }, 1000);
                    setTimeout(function() {
                        resizeElem($this);
                    }, 2000);
                    setTimeout(function() {
                        resizeElem($this);
                    }, 5000);
                }
            }
        });

        // overall resizing
        $('.slide-arrow-holder .arrow-bg').width(parseInt(slideholderDelta / 2) + 50);
        if (slideholderDelta > 0) {
            $('.slide-arrow-holder .arrow-bg').addClass('gradiented');
            /*
            $('.slide-arrow-holder.slide-left-arrow2 arrow').css('left', (parseInt((parseInt(slideholderDelta/2) + 50)/2) - 26) + 'px');
            $('.slide-arrow-holder.slide-right-arrow2 arrow').css('right', (parseInt((parseInt(slideholderDelta/2) + 50)/2) - 26) + 'px');
            */
        } else {
            $('.slide-arrow-holder .arrow-bg').removeClass('gradiented');
            /*
            $('.slide-arrow-holder.slide-left-arrow2 arrow').css('left', 0);
            $('.slide-arrow-holder.slide-right-arrow2 arrow').css('right', 0);
            */
        }

        // resposition the slides to reflect any changes
        sliderPositionSlides();

        // if zoomed in resize slides
        if (fsoSliderZoomedInScaled) {
            var self = this;
            self.cancelZooming = true;
            setTimeout(function(){
                self.cancelZooming = true;
                self.prepareScaleImages();
            }, 2000);
        }
    }

    // resize an element
    function resizeElem($elem) {

        if ($elem.hasClass('js-dynamic-size-set')) return;

        for (var a in attrs) {
            var myAttrsName = attrs[a];
            var myVal = $elem.attr('data-' + myAttrsName);
            if (myVal == null || myVal == 'NaN') continue;
            if ($elem.hasClass('dynamically-sized')) {
                myVal = Math.floor(myVal / xRatio);
                $elem.attr('data-' + myAttrsName, myVal);
                setTimeout(function() {
                    $elem.removeClass('dynamically-sized');
                }, 1000);
            }
            $elem.css(myAttrsName, Math.floor(myVal * xRatio));
        }
    }

    ////////////////
    // (Pre-)loading

    // load the previous 2, current and new 2 slides (or the next 4 if it's the first slide, last 4
    // if it's the last slide, etc.)
    function loadSurroundingSlides(aSlideNum) {

        // load slides, otherwise there is a bug when on screens < 1024px 
        // the slides are not loaded
        // if (window.deviceCustomType != 'desktop') return;

        logger.debug('loading surround: ' + aSlideNum);

        var startNum = Math.min(Math.max(aSlideNum - 2, 0), totalSlides - 5);
        sliderReloadCounter = 0;
        $slideshowMainElem.removeClass('all-loaded');
        for (var i = startNum; i < startNum + 5; i++) {
            var $thisSlide = $mySlides.eq(i);
            $thisSlide.find('.image-item[data-src]:not(.loaded),.image-holder img[data-src]:not(.loaded)').each(function() {
                sliderReloadCounter++;
                var $myThisSlide = $thisSlide;
                var $this = $(this);
                $this.css('background', 'none').css('visibility', 'hidden');

                if (!/Trident/.test(navigator.userAgent)) {
                    var start = performance.now();
                    $this.on('load', function() {
                        // $this[0].offsetTop;
                        $this.css('visibility', 'visible');
                        var $myMyThisSlide = $myThisSlide;
                        // if (window._fsoSlidesSlideLoadedCallback) _fsoSlidesSlideLoadedCallback($myMyThisSlide);
                        sliderLoaded();
                    });

                }

                /*
                // HACK this is a bit too simplistic - should probably be extracted somewhere
                $this.attr('src', $this.attr('data-src').replace(/\/data\/www.scientology.org\//, (globalIsIOS ? '/imagecache/gcui_640w/data/www.scientology.org/' : '/data/www.scientology.org/'))).addClass('loaded');
                */
                 $this.on('load', function() {
                    $(this).removeClass('loading-image-hide');
                    $(this).parents('.image-holder').removeClass('js-preview');    
                });

                var imgSrc = $this.attr('data-src');
                if(imgSrc.indexOf("FURL/") == 0) {
                    imgSrc = "/" + imgSrc;
                }

                // do any dynamic size adjustments here
                if ($this.attr('data-height') && window.determineImageSources) {
                    var imageSources = determineImageSources(this);
                    if(imageSources) {
                        imgSrc = imageSources[0];
                    }
                }

                if(fsoSliderZoomedIn) {
                    return;
                }

                logger.debug('preloading surround: ' + imgSrc);
                $this.addClass('loading-image-hide').attr('src', imgSrc).addClass('loaded');

                if (/Trident/.test(navigator.userAgent)) {
                    setTimeout(function() {
                        // $this[0].offsetTop;
                        $this.css('visibility', 'visible');
                        var $myMyThisSlide = $myThisSlide;
                        // if (window._fsoSlidesSlideLoadedCallback) _fsoSlidesSlideLoadedCallback($myMyThisSlide);
                        sliderLoaded();
                    }, 3000);
                }

                // if there's a double-size as well, start slowly loading that
                if ($this.parents('.image-holder').length) {

                    var $double = $this.parents('.image-holder').find('.zoomer-image');

                    (function() {
                        setTimeout(function() {
                            loadImage($double);
                        }, (fsoSliderZoomedIn ? 0 : 500) + i * (fsoSliderZoomedIn ? 20 : 100));
                    })();

                }


            });
        }
        if (sliderReloadCounter == 0) $slideshowMainElem.addClass('all-loaded');

    }

    function sliderLoaded() {
        if (--sliderReloadCounter == 0) $slideshowMainElem.addClass('all-loaded');
    }
    /////////////////
    // Sliding motion

    function sliderMovePrev() {

        if (currentActiveSlideIdx == 0 && !isCloned) return;

        if (currentActiveSlideIdx > 0) {
            // return location.hash = 'slide' + currentActiveSlideIdx;
            EventTracker.trackArrowClick(currentActiveSlideIdx, "Prev");

            return replaceHash('slide' + currentActiveSlideIdx);
        }

        // cloned, need to do a big yank before sliding
        globalAnimationController.cancelAnimation($slideHolderDom);

        var deltaX = (isRTL ? -2 : 2) * totalSlides * 100;
        slideHolderDom.style[Modernizr.prefixed('transition')] = 'none';
        slideHolderDom.offsetHeight;
        slideHolderDom.style[Modernizr.prefixed('transform')] = 'translate3d(-' + deltaX + '%, 0, 0)';
        slideHolderDom.offsetHeight;
        // location.hash = 'slide' + totalSlides;
        replaceHash('slide' + totalSlides);

    }

    me.sliderMovePrev = sliderMovePrev;

    me.sliderMoveNext = function() {
        
        if (currentActiveSlideIdx == totalSlides - 1 && !isCloned) return;

        if (currentActiveSlideIdx <  totalSlides - 1) {
            // return location.hash = 'slide' + (currentActiveSlideIdx + 2);

            EventTracker.trackArrowClick(currentActiveSlideIdx+2, "Next");

            return replaceHash('slide' + (currentActiveSlideIdx + 2));
        }

        // cloned, need to do a big yank before sliding
        globalAnimationController.cancelAnimation($slideHolderDom);

        var deltaX = (isRTL ? -1 : 1) * (totalSlides-1) * 100;
        slideHolderDom.style[Modernizr.prefixed('transition')] = 'none';
        slideHolderDom.offsetHeight;
        slideHolderDom.style[Modernizr.prefixed('transform')] = 'translate3d(-' + deltaX + '%, 0, 0)';
        slideHolderDom.offsetHeight;
        // location.hash = 'slide1';
        replaceHash('slide1');

    }

    me.sliderGotoFirst = function() {
        this.gotoSlide(0);
    }

    me.sliderGotoLast = function() {
        this.gotoSlide(totalSlides-1);
    }

    /*
    function fsoSliderAddSelfCancellingAnimation(aFunction, aDelay) {
        var animNumber = setTimeout(aFunction, aDelay);
        subanimations[animNumber] = 1;
    }
    */

    // finish an animation
    function sliderEndAnimation(aForce) {

        if (ipAnimation == 0 && !aForce) return;
        if (ipAnimation != 0) clearTimeout(ipAnimation);
        if (fsoSliderZoomTimeout > 0) clearTimeout(fsoSliderZoomTimeout);

        $('.sliding .item').removeClass('move-left-fade-out move-right-fade-out move-left-fade-in move-right-fade-in move-left move-right text-left-effect text-right-effect');

        if (globalHas3d && Modernizr.csstransitions)
            $('.sliding .item').css(Modernizr.prefixed('transform'), '')
                .css(Modernizr.prefixed('transition'), 'none');

        if (globalHas3d)
            $('.sliding').css(Modernizr.prefixed('transform'), '');

        $('.sliding').removeClass('sliding');

        sliderPositionSlides();

        ipAnimation = 0;

    }

    function sliderPositionSlides(mobileOptimize) {

        // $('.slide-holder').css((isRTL ? 'right' : 'left'), (-1 * (parseInt(-slideholderDelta/2) + fsoSlideWidth2 * currentActiveSlideIdx)) + 'px').removeClass('moving');

        // $('.slide-holder').css(Modernizr.prefixed('transition'), 'none');
        if (Modernizr.csstransitions && mySlideholderElem.style[Modernizr.prefixed('transition')] != 'none')
            mySlideholderElem.style[Modernizr.prefixed('transition')] = 'none';

        // var deltaX = (isRTL ? 1 : -1) * (parseInt(-slideholderDelta/2) + fsoSlideWidth2 * currentActiveSlideIdx);

        var deltaX = (isRTL ? 1 : -1) * fsoSlideWidth2 * currentActiveSlideIdx;
        // var deltaX = (currentActiveSlideIdx * (100/totalSlides));
        // var deltaX = currentActiveSlideIdx * 100;
        // var deltaX = currentActiveSlideIdx;

        if (isCloned) {
            deltaX += (isRTL ? 1 : -1) * totalSlides * fsoSlideWidth2;
        }

        // $('.slide-holder').css(Modernizr.prefixed('transform')
        // );

        if (globalHas3d && Modernizr.csstransitions) {
            mySlideholderElem.style[Modernizr.prefixed('transform')] =
                'translate3d(' + deltaX + 'px,0,0)';
        } else {
            if (window.globalGetParams && globalGetParams.headless) {
                mySlideholderElem.style[Modernizr.prefixed('transform')] =
                'translate3d(' + deltaX + 'px,0,0)';
            } else {
                // FIXME this (alt) is broken
                mySlideholderElem.style.left = deltaX + 'px';
            }
        }

        if (!mobileOptimize) {

            $('.slide-holder').removeClass('moving');
            $slideshowMainElem.removeClass('moving');
            $('.slide-holder').attr('class', $('.slide-holder').attr('class').replace(/[ ]*moving-off-of-[0-9]+/, ''));
            $slideshowMainElem.attr('class', $slideshowMainElem.attr('class').replace(/[ ]*moving-off-of-[0-9]+/, ''));
            $slideshowMainElem.attr('class', $slideshowMainElem.attr('class').replace(/[ ]*moving-onto-[0-9]+/, ''));
            $slideshowMainElem.attr('class', $slideshowMainElem.attr('class').replace(/[ ]*moving-to-dir-[^ ]+/, ''));
            
            $('.fso-slide-active').removeClass('fso-slide-active');
            if ($mySlide) {
                $mySlide.addClass('fso-slide-active');
            } else {
                $mySlides.eq(currentActiveSlideIdx).addClass('fso-slide-active');
            }

        }

        if (isIpad) $slideshowMainElem.removeClass('always-show');

    }

    animationDebugMode = false;

    function fsoSliderAnimateIn($mySlide, aExtraMotion, aDelay, aMoveinText) {

        // for IE, don't do the little item animations
        if (globalIsIE) return aDelay;

        if (aExtraMotion != 0) {

            if (globalHas3d && Modernizr.csstransitions) {
                $mySlide.css(Modernizr.prefixed('transform'), 'translate3d(' + aExtraMotion + 'px, 0px, 0px)');
            } else {
                $mySlide.css('left', -aExtraMotion + 'px');
            }
        }

        $mySlide.find('.item').each(function() {

            var $myItem = $(this);
            var noAnimateDelay = $myItem.hasClass('no-animation-delay');
            if ($myItem.hasClass('text-item')) {
                if (aMoveinText) {

                    var customDirection = myDirection;
                    // if (isRTL && customDirection == 'left') {
                    //     customDirection = 'right';
                    // } else if (isRTL && customDirection == 'right') {
                    //     customDirection = 'left';
                    // }

                    // 


                    $myItem.css('opacity', 1).addClass('animation-' + customDirection + '-hold');
                    (function() {
                        var theDirection = customDirection;
                        textAnimationQueue.push(setTimeout(function() {
                            $myItem.removeClass('animation-' + theDirection + '-hold').addClass('animation-' + theDirection + '-hold2');
                        }, 500 + aDelay));
                    })();

                    /*
                    $myItem.addClass('text-' + customDirection + '-effect');
                    fsoSliderAddSelfCancellingAnimation(function() {
                        $myItem.addClass('animate');
                    }, 700);
                    */

                }
            } else {
                if (aMoveinText || noAnimateDelay) {
                    var animateProps = {
                        opacity: 1
                    };
                    if (globalHas3d && Modernizr.csstransitions) {
                        animateProps[Modernizr.prefixed('transform')] = 'translate3d(' +
                            ((myDirection == 'left' ? minusOne : plusOne) * fsoSlideWidth2) +
                            'px, 0px, 0px)';
                        globalAnimationController.animate(
                            $myItem,
                            animateProps,
                            (
                                noAnimateDelay ?
                                (animationDebugMode ? '10s' : '1s') + ' cubic-bezier(0.23, 1, 0.32, 1)' :
                                (animationDebugMode ? '8s' : '.8s') + ' cubic-bezier(0.165, 0.840, 0.440, 1.000) ' + aDelay + 'ms'
                            )
                        );
                    } else {
                        $myItem.css('left', (myDirection == 'left' ? -1 : 1) * fsoSlideWidth2 + 'px');
                    }
                } else {
                    $myItem.addClass('move-' + myDirection);
                }

                /*
                fsoSliderAddSelfCancellingAnimation(function() {
                    if (aMoveinText) {
                        $myItem.addClass('move-' + myDirection + '-fade-in');
                    } else {
                        $myItem.addClass('move-' + myDirection);
                    }
                }, aDelay);
                */

            }
            aDelay += (animationDebugMode ? 500 : 50);

        });

        return aDelay;

    }

    // slide the apple dots around - if there are too many of them
    function fsoSliderFixAppleDots(newSlideIdx) {

        if (!tooManyAppleDots) return;

        var animateProps = {};

        var halfWaySlides = totalSlides / 2;

        // some funk after zooming
        // halfWaySlides = Math.floor(dotHolderWidth / $('.slide-link').width()) - 3;

        halfWaySlides = 16;

        // also slide the whole thing to the left if over the half mark
        if (newSlideIdx >= halfWaySlides) {

            // animateProps[isRTL ? 'right' : 'left'] = dotHolderWidth + (
            //     fsoSliderZoomedIn ?
            //     ($('.slide-dot-over.slide-dot-over-left').eq(1).width() - lastSlideOffset) :
            //     ($('.slide-dot-over.slide-dot-over-left').eq(1).width() - lastSlideOffset)
            // );

            // var slidesOffset = newSlideIdx - (newSlideIdx % 6) - halfWaySlides;
            var slidesOffset = newSlideIdx - halfWaySlides + 1;
            // if(slidesOffset == 0) {
            //     slidesOffset = 1;
            // }

            if(slidesOffset < 0) {
                slidesOffset *= -1;
            }

            animateProps[isRTL ? 'right' : 'left'] =
            Math.max( slidesOffset * -24.15625,
                dotHolderWidth + (
                    fsoSliderZoomedIn ?
                    (0 - lastSlideOffset) :
                    (0 - lastSlideOffset)
                )
            );


            if(leftHolderOffset != animateProps[isRTL ? 'right' : 'left']) {
                leftHolderOffset = animateProps[isRTL ? 'right' : 'left'];

                fsoSliderRecalculateMiddlayDots(leftHolderOffset);
                // fsoSliderRecalculateMiddlayDots(leftHolderOffset);
                // var inner = $('.slide-dots-holder-inner').html()
                // TweenMax.set($('.slide-link'), {clearProps: "all"});
                // $(window).width()
// console.log(inner);
                // $('.slide-dots-holder-inner').html(inner);
                // $(window).width()

                // TweenMax.set($('.slide-link'), {clearProps: "all"});
                TweenMax.to($('.slide-link'), 0.25, {scale: 1, x: 0, ease: Power3.easeInOut});

                // midwaySlideNumLow = newSlideIdx;
                // midwaySlideNum = newSlideIdx - halfWaySlides + 1;

                if(midwaySlideNumLow + 1 < totalSlides) {
                    TweenMax.to($('.slide-link[href="#slide' + (midwaySlideNumLow + 3) + '"]'), 0.25, {scale: 0.5, x: 0});
                    TweenMax.to($('.slide-link[href="#slide' + (midwaySlideNumLow + 2) + '"]'), 0.25, {scale: 0.5, x: 0, ease: Power3.easeInOut});
                    TweenMax.to($('.slide-link[href="#slide' + (midwaySlideNumLow + 1) + '"]'), 0.25, {scale: 0.7, x: 0, ease: Power3.easeInOut});
                    TweenMax.to($('.slide-link[href="#slide' + (midwaySlideNumLow) + '"]'), 0.25, {scale: 0.8, x: 0, ease: Power3.easeInOut});

                    TweenMax.to($('.slide-link[href="#slide' + midwaySlideNum + '"]'), 0.25, {scale: 0.7, x: 0, ease: Power3.easeInOut});
                    TweenMax.to($('.slide-link[href="#slide' + (midwaySlideNum + 1) + '"]'), 0.25, {scale: 0.8, x: 0, ease: Power3.easeInOut});
                    // TweenMax.to($('.slide-link[href="#slide' + (midwaySlideNum + 2) + '"]'), 0.25, {scale: 0.8, x: 0, ease: Power3.easeInOut});
                } else {
                    TweenMax.to($('.slide-link[href="#slide' + midwaySlideNum + '"]'), 0.25, {scale: 0.7, x: 0, ease: Power3.easeInOut});
                    TweenMax.to($('.slide-link[href="#slide' + (midwaySlideNum + 1) + '"]'), 0.25, {scale: 0.8, x: 0, ease: Power3.easeInOut});
                }
            } else {
                // console.log('fsoSliderRecalculateMiddlayDots with 0');
                fsoSliderRecalculateMiddlayDots(leftHolderOffset);

                TweenMax.to($('.slide-link'), 0.25, {scale: 1, x: 0, ease: Power3.easeInOut});

                TweenMax.to($('.slide-link[href="#slide' + midwaySlideNum + '"]'), 0.25, {scale: 0.7, x: 0, ease: Power3.easeInOut});
                TweenMax.to($('.slide-link[href="#slide' + (midwaySlideNum + 1) + '"]'), 0.25, {scale: 0.8, x: 0, ease: Power3.easeInOut});
            }
            
            $('.slide-dots-holder-inner').stop(true, true).animate(animateProps, 300, function() {
                // $('.slide-dots-holder-inner').css('opacity', 1);
            });

        } else {

            // animateProps[isRTL ? 'right' : 'left'] = $('.slide-dot-over.slide-dot-over-left').eq(1).width() + 2;
            animateProps[isRTL ? 'right' : 'left'] = 0;

            fsoSliderRecalculateMiddlayDots(0);

            if(leftHolderOffset != animateProps[isRTL ? 'right' : 'left']) {
                TweenMax.set($('.slide-link'), {clearProps: "all"});
                leftHolderOffset = animateProps[isRTL ? 'right' : 'left'];
            }

            for(var i = 0; i < 5; i++) {
                TweenMax.to($('.slide-link[href="#slide' + i + '"]'), 0.25, {scale: 1, x: 0, ease: Power3.easeInOut});
            }
            if(midwaySlideNumLow > 0) {
                // TweenMax.to($('.slide-link[href="#slide' + (midwaySlideNumLow + 3) + '"]'), 0.25, {scale: 0.5, x: 0});
                // TweenMax.to($('.slide-link[href="#slide' + (midwaySlideNumLow + 2) + '"]'), 0.25, {scale: 0.5, x: 0});
                TweenMax.to($('.slide-link[href="#slide' + (midwaySlideNumLow + 1) + '"]'), 0.25, {scale: 0.7, x: 0});
                TweenMax.to($('.slide-link[href="#slide' + (midwaySlideNumLow) + '"]'), 0.25, {scale: 0.8, x: 0});
            }

            $('.slide-dots-holder-inner').stop(true, true).animate(animateProps, 300, function() {
                // $('.slide-dots-holder-inner').css('opacity', 1);
            });

        }

    }

    // recalculate the apple dot positions - call on zoom in/out and resize
    function fsoSliderRecalculateAppleDots() {

        if (!tooManyAppleDots) return;

        // find the mid-way slides
        if (!fsoSliderZoomedIn && $('.slide-dots-holder')[1] || (fsoSliderZoomedIn && fsoSliderZoomedInScaled) ) {
            $('.slide-dots-holder')[1].offsetTop;
            dotHolderWidth = $('.slide-dots-holder').eq(1).width() - $('.slide-dot-over.slide-dot-over-left').eq(1).width() - $('.slide-dot-over.slide-dot-over-right').eq(1).width() + 30;
        } else {
            $('.slide-dots-holder')[0].offsetTop;
            dotHolderWidth = $('.slide-dots-holder').eq(0).width() - $('.slide-dot-over.slide-dot-over-left').eq(0).width() - $('.slide-dot-over.slide-dot-over-right').eq(0).width() + 30;
        }

        if (dotHolderWidth >= lastSlideOffset) {
            $('body').addClass('fso-slides-wide-enough-for-apple-dots-no-slide');
        } else {
            $('body').removeClass('fso-slides-wide-enough-for-apple-dots-no-slide');
        }

        fsoSliderRecalculateMiddlayDots();
    }

    function fsoSliderRecalculateMiddlayDots(left) {
        var currentDots = allNormalAppleDots;

        midwaySlideNum = 0;
        midwaySlideNumLow = 0;

        var num = 1;
        if($('.slide-dots-holder-inner').length == 1) {
            num = 0;
        }

        var innerLeft = left || $('.scrolling-dots').eq(num).position().left;

        if (!isRTL) {
            for (var i = totalSlides; i >= 1; i--) {
                if (midwaySlideNum == 0 && currentDots.eq(i - 1).position().left + innerLeft < 0) {
                    midwaySlideNum = i;
                }
                // if (lastSlideOffset - currentDots.eq(i - 1).position().left < dotHolderWidth) {
                if (currentDots.eq(i - 1).position().left + innerLeft > dotHolderWidth) {
                    midwaySlideNumLow = Math.max(0, i-1);
                }
            };
        } else {
            // disable for RTL
            return;

            var overallWidth = $('.scrolling-dots').eq(1).width();
            for (var i = totalSlides; i >= 1; i--) {
                if (midwaySlideNum == 0 && overallWidth - currentDots.eq(i - 1).position().left < dotHolderWidth) {
                    midwaySlideNum = i;
                }

                if (lastSlideOffset - (overallWidth - currentDots.eq(i - 1).position().left) < dotHolderWidth) {
                    midwaySlideNumLow = Math.max(0, i - 3);
                }
            };
        }

        // hide/show dots

        // hide all invisible dots to the left
        for(var i = 0 ; i < midwaySlideNum; i ++) {
            TweenMax.to(currentDots.eq(i), 0.25, {autoAlpha: 0, ease: Power3.easeInOut});
        }

        // slider is at the far right -> show all dots to the right
        if(midwaySlideNumLow == 0) {
            for(var i = midwaySlideNum ; i < currentDots.length; i ++) {
                TweenMax.to(currentDots.eq(i), 0.25, {autoAlpha: 1, ease: Power3.easeInOut});
            }
        } else {
            for(var i = midwaySlideNum ; i < midwaySlideNumLow; i ++) {
                TweenMax.to(currentDots.eq(i), 0.25, {autoAlpha: 1, ease: Power3.easeInOut});
            }
        }

        // hide all visible dots to the right
        if(midwaySlideNumLow > 0) {
            for(var i = midwaySlideNumLow ; i < currentDots.length; i ++) {
                TweenMax.to(currentDots.eq(i), 0.25, {autoAlpha: 0, ease: Power3.easeInOut});
            }
        }

        
        // TweenMax.set($('.slide-link'), {opacity: 1, scale: 1, x: 0});
    }

    function fsoSliderHashChange() {

        var newSlideIdx = parseInt(location.hash.substring(1).replace(/slide/, '')) - 1;
        if (isNaN(newSlideIdx) || newSlideIdx < 0 || newSlideIdx > totalSlides - 1) return;

        if (currentActiveSlideIdx == newSlideIdx) return;

        if (!isIpad) {
            fsoSliderGotoSlide(newSlideIdx, true);
        } else {
            fsoSliderGotoSlide(newSlideIdx, false);
            sliderPositionSlides(true);
        }

    }

    function fsoSliderGotoSlide(newSlideIdx, animate) {

        if (!window.slide8Ignore) {

            if (newSlideIdx > 6) {
                $('.menu-holder-after-8').fadeIn(300);
            } else {
                $('.menu-holder-after-8').hide();
            }

            if (newSlideIdx == 7) {
                $('.fso-custom-menu').addClass('always-show');
                $('body').addClass('hide-zoomer');
            } else {
                $('.fso-custom-menu').removeClass('always-show');
                $('body').removeClass('hide-zoomer');
            }

        }

        // slide link selections
        $('.slide-link').removeClass('selected');
        $('.slide-link[href="#slide' + (newSlideIdx + 1) + '"]').addClass('selected');

        // HACK if we are not animating, this means that mobile is on for now, so we
        // don't worry about the apple dots for now (as an optimization)
        if (animate) fsoSliderFixAppleDots(newSlideIdx);

        setTimeout(function() {
            loadSurroundingSlides(newSlideIdx);
        }, 100);

        /*
        // if there's animation in progress, cancel it
        if (ipAnimation > 0) {
            for (s in subanimations) clearTimeout(subanimations[s]);
            clearTimeout(ipAnimation);
            sliderEndAnimation();
        }
        subanimations = {};
        */

        if (animate) {

            if (!simpleAnimation) {

                sliderEndAnimation();

                // end any text animation as well
                for (var i = 0; i < textAnimationQueue.length; i++) {
                    clearTimeout(textAnimationQueue[i]);
                }
                $('.text-item').removeClass('animation-left-hold animation-left-hold2 animation-right-hold animation-right-hold2');

            }

            // get some basic data
            myDirection = (currentActiveSlideIdx < newSlideIdx) ? 'left' : 'right';
            var myDelay = 0;
            var $myActiveSlide = $mySlides.eq(currentActiveSlideIdx).addClass('sliding');
            $mySlide = $mySlides.eq(newSlideIdx).addClass('sliding');

            // figure out the prev/next slides
            var $myNextSlide = null;
            var $myPrevSlide = null;
            if (myDirection === 'left') {
                if (newSlideIdx < totalSlides - 1)
                    $myNextSlide = $mySlides.eq(newSlideIdx + 1).addClass('sliding');
                if (currentActiveSlideIdx > 0)
                    $myPrevSlide = $mySlides.eq(currentActiveSlideIdx - 1).addClass('sliding');
            } else {
                if (newSlideIdx > 0)
                    $myNextSlide = $mySlides.eq(newSlideIdx - 1).addClass('sliding');
                if (currentActiveSlideIdx < totalSlides - 1)
                    $myPrevSlide = $mySlides.eq(currentActiveSlideIdx + 1).addClass('sliding');
            }

            // if (isRTL) myDirection = (currentActiveSlideIdx < newSlideIdx) ? 'right' : 'left';

            $('.slide-holder').addClass('moving');
            $slideshowMainElem.addClass('moving');
            $('.slide-holder').addClass('moving-off-of-' + currentActiveSlideIdx);
            $slideshowMainElem.addClass('moving-off-of-' + currentActiveSlideIdx);
            $slideshowMainElem.addClass('moving-onto-' + (newSlideIdx + 1));
            $slideshowMainElem.addClass('moving-to-dir-' + myDirection);

            if (!simpleAnimation) {

                // do any extra motion here
                var extraMotion = 0;
                var nextExtraMotion = 0;
                if (Math.abs(currentActiveSlideIdx - newSlideIdx) > 1) {
                    extraMotion = (currentActiveSlideIdx - newSlideIdx) * (fsoSlideWidth2);
                    extraMotion += (fsoSlideWidth2) * ((currentActiveSlideIdx < newSlideIdx) ? +1 : -1);
                    nextExtraMotion = extraMotion + (fsoSlideWidth2) * ((currentActiveSlideIdx < newSlideIdx) ? +1 : -1);
                }

                if ($myPrevSlide) {
                    $myPrevSlide.find('.item').each(function() {

                        var noAnimateDelay = $(this).hasClass('no-animation-delay');

                        if (globalHas3d && Modernizr.csstransitions) {
                            var animateProps = {
                                opacity: window.globalSlideshowFadeout !== void 0 ? globalSlideshowFadeout : 0.2,
                            };
                            if ($(this).hasClass('text-item')) animateProps.opacity = 0;
                            animateProps[Modernizr.prefixed('transform')] = 'translate3d(' +
                                ((myDirection == 'left' ? minusOne : plusOne) * fsoSlideWidth2) +
                                'px, 0px, 0px)';
                            globalAnimationController.animate(
                                $(this),
                                animateProps,
                                (
                                    noAnimateDelay ?
                                    (animationDebugMode ? '10s' : '1s') + ' cubic-bezier(0.23, 1, 0.32, 1)' :
                                    (animationDebugMode ? '6s' : '.6s') + ' cubic-bezier(0.165, 0.840, 0.440, 1.000)'
                                )
                            );
                        } else {
                            $(this).css('left', (myDirection == 'left' ? -1 : 1) * fsoSlideWidth2 + 'px');
                        }

                        // $(this).addClass('move-' + myDirection + '-fade-out');

                    });
                }

                $myActiveSlide.find('.item').each(function() {
                    var $myItem = $(this);
                    var noAnimateDelay = $myItem.hasClass('no-animation-delay');

                    if (globalHas3d && Modernizr.csstransitions) {
                        var animateProps = {
                            opacity: window.globalSlideshowFadeout !== void 0 ? globalSlideshowFadeout : 0.2,
                        };
                        if ($(this).hasClass('text-item')) animateProps.opacity = 0;
                        animateProps[Modernizr.prefixed('transform')] = 'translate3d(' +
                            ((myDirection == 'left' ? minusOne : plusOne) * fsoSlideWidth2) +
                            'px, 0px, 0px)';
                        globalAnimationController.animate(
                            $(this),
                            animateProps,
                            (
                                noAnimateDelay ?
                                (animationDebugMode ? '10s' : '1s') + ' cubic-bezier(0.23, 1, 0.32, 1)' :
                                (animationDebugMode ? '6s' : '.6s') + ' cubic-bezier(0.165, 0.840, 0.440, 1.000) ' + myDelay + 'ms'
                            )
                        );
                    } else {
                        $(this).css('left', (myDirection == 'left' ? -1 : 1) * fsoSlideWidth2 + 'px');
                    }

                    /*
                    fsoSliderAddSelfCancellingAnimation(function() {
                        $myItem.addClass('move-' + myDirection + '-fade-out');
                    }, myDelay);
                */

                    myDelay += (animationDebugMode ? 500 : 50);
                });

                myDelay = Math.max(0, myDelay - (animationDebugMode ? 500 : 50));

                if (isCloned) {
                    nextExtraMotion += (isRTL ? 1 : -1) * totalSlides * fsoSlideWidth2;
                    extraMotion += (isRTL ? 1 : -1) * totalSlides * fsoSlideWidth2;
                }

            }

            if (!simpleAnimation) {
                if ($myNextSlide) fsoSliderAnimateIn($myNextSlide, plusOne * nextExtraMotion, 0, false);
                myDelay = fsoSliderAnimateIn($mySlide, plusOne * (isRTL ? -1 : 1) * extraMotion, myDelay, true);

                ipAnimation = setTimeout(function() {
                    sliderEndAnimation();
                }, myDelay + animationGracePeriod);

                /*
                ipAnimation = setTimeout(function() {
                    sliderEndAnimation();
                }, 100);
                */

            } else {

                // var deltaX = (isRTL ? 1 : -1) * (parseInt(-slideholderDelta/2) + fsoSlideWidth2 * newSlideIdx);
                // var deltaX = (newSlideIdx * (100/totalSlides));
                var deltaX = (isRTL ? -1 : 1) * newSlideIdx * 100;

                if (isCloned) {
                    deltaX += (isRTL ? -1 : 1) * totalSlides * 100;
                }

                var animateProps = {};
                animateProps[Modernizr.prefixed('transform')] = 'translate3d(' + (-deltaX) + '%, 0, 0)';

                globalAnimationController.animate(
                    $slideHolderDom,
                    animateProps,
                    (animationDebugMode ? '8s' : '.8s') + ' cubic-bezier(0.165, 0.840, 0.440, 1.000)',
                    function() {
                        sliderEndAnimation(true);
                    }
                );

                // HACK change the active slide class at the beginning - this is different from the
                // other animation, but is needed to allow for the existing slide animations to play off nicely
                $('.fso-slide-active').removeClass('fso-slide-active');
                $mySlides.eq(newSlideIdx).addClass('fso-slide-active');

            }

        } else {
            $mySlide = $mySlides.eq(newSlideIdx); // .addClass('sliding');
        }

        // pre-change callbacks
        me.slideWillChange();

        // update the index here
        currentActiveSlideIdx = newSlideIdx;
        $slideshowMainElem.attr('data-slide-active', newSlideIdx);
        $('.fso-slide-mobile-numbers .slide-num').text(currentActiveSlideIdx + 1);

        if ((newSlideIdx == totalSlides - 1)) {
            $slideshowMainElem.addClass('fso-slide-last');
            $('.slideshow-holder').addClass('fso-slider-last');
        } else {
            $slideshowMainElem.removeClass('fso-slide-last');
            $('.slideshow-holder').removeClass('fso-slider-last');
        }

        if (newSlideIdx == 0) {
            $('.header-container').addClass('on-first-slide');
            $('.slideshow-holder').addClass('slider-first-slide');
        } else {
            $('.header-container').removeClass('on-first-slide');
            $('.slideshow-holder').removeClass('slider-first-slide');
        }

        // post-change callbacks
        me.slideHasChanged();

    };

    me.slideWillChange = function() {
        if (!globalIsIOS) {
            if ($mySlides.eq(currentActiveSlideIdx).find('.video-js').length) stopVideoForSlide(currentActiveSlideIdx);
        }
        $slideshowMainElem.trigger('slide-will-change', currentActiveSlideIdx);
    }

    me.slideHasChanged = function() {

        $('.slide-dots-holder-counter-current').text(currentActiveSlideIdx+1);
        $('.slide-dots-holder-counter-total').text(this.totalSlides());

        var slideIndex = currentActiveSlideIdx+1;
        EventTracker.trackSlideView(slideIndex);
        

        // if (!globalIsIOS) {
            var $customSlide = $('.custom-slide-leftnav[data-slide-id="' + $mySlides.eq(currentActiveSlideIdx).attr('data-slide-id') + '"]');
            $('.custom-slide-leftnav.show').removeClass('show');

            if ($customSlide.length) {
                $('.slideshow-left-nav').addClass('custom-slide-showing');
                $customSlide.addClass('show');
            } else {
                $('.slideshow-left-nav').removeClass('custom-slide-showing');
            }
        // }

        var slideArrowRight = $slideshowMainElem.find('.slide-right-arrow2')[0];

        if(!this.isCircularClone() && slideArrowLeft != undefined && slideArrowRight != undefined) {
            if(currentActiveSlideIdx + 1 == this.totalSlides()) {
                $(slideArrowRight).hide();
            } else {
                $(slideArrowRight).show();
            }

            if(currentActiveSlideIdx == 0) {
                $(slideArrowLeft).hide();
            } else {
                $(slideArrowLeft).show();
            }
        }

        if (fsoSliderZoomedIn) {
            this.scaleAdjacentImages();
        }

        $slideshowMainElem.trigger('slide-has-changed', currentActiveSlideIdx);

        var $navmenu = $('.slideshow-nav-menu[data-start-slide-id]');
        if($navmenu.length) {
            var startSlideId = $navmenu.attr('data-start-slide-id');
            if(slideIndex > startSlideId ) {
                $navmenu.show();
            } else {
                $navmenu.hide();
            }
        }

        initComparison();

        if($mySlides.eq(currentActiveSlideIdx).find('.cd-image-container').length) {
            setTimeout(() => {
                $mySlides.eq(currentActiveSlideIdx).find('.cd-image-container').click();
            }, 800);
        }

        if($mySlides.eq(currentActiveSlideIdx).find('.video-js').length) startVideoForSlide(currentActiveSlideIdx);
        
    }

    me.preloadSlides = function(self) {
        if(!self) {
            self = this;
        }
        var tempFirstSlide = self.determineFirstSlide();
        if (window.deviceCustomType == 'desktop' || self.touchMode != 'photoswipe') loadSurroundingSlides(Math.max(0, tempFirstSlide-1));

        // and slowly load in all the slides
        if (!globalIsIOS && !globalIsSafari) {
            for (var i = 0; i < totalSlides; i++) {
                (function() {

                    if (window.deviceCustomType != 'desktop' && self.touchMode == 'photoswipe') return;

                    var $thisSlide = $mySlides.eq(i);
                    setTimeout(function() {
                        $thisSlide.find('.image-item[data-src]:not(.loaded),.image-holder img[data-src]:not(.loaded)').each(function() {

                            if($slideshowMainElem.hasClass('slideshow-zoomed')) {
                                return;
                            }
                            
                            var $myThisSlide = $thisSlide;
                            var $this = $(this);
                            var imgSrc = $this.attr('data-src');
                            if(imgSrc.indexOf("FURL/") == 0) {
                                imgSrc = "/" + imgSrc;
                            }

                            // do any dynamic size adjustments here
                            if ($this.attr('data-height')) imgSrc = determineImageSources(this)[0];

                            logger.debug('preloading #1: ' + imgSrc);

                            if ($this.attr('src') != imgSrc) {
                                $this.on('load', function() {
                                    if(fsoSliderZoomedInScaled) {
                                        return;
                                    }
                                    $this.parents('.image-holder').removeClass('js-preview');    
                                });
                                $this.css('background', 'none').addClass('loading-image-hide')
                                    .attr('src', imgSrc).addClass('loaded');
                            } else {
                                // don't add "loading-image-hide" if the src is not being modified,
                                // since the "load" event will not fire for some browsers
                                $this.css('background', 'none')
                                    .addClass('loaded');
                                $this.parents('.image-holder').removeClass('js-preview');
                            }

                            $this.on('load', function() {
                                if(fsoSliderZoomedInScaled) {
                                    return;
                                }
                                $this.removeClass('loading-image-hide');
                            });
                        });
                    }, 500 * i);
                })();
            }
        }
    }

    function fsoSliderCanZoomIn() {
        var canZoom = true;
        for(var i = 0; i < $mySlides.length; i++) { 
            var $slide = $mySlides.eq(i);
            $slide.find('img:not(.loaded__zoomed):not(.loading__zoomed)').each(function(index, el) {
                if(!$(el).attr('data-width') && $(el).find('.jpg') > -1) {
                    canZoom = false;
                    console.error("can't zoom missing [data-width]", $(el));
                }
            });
        }

        // safari has blurry text zooming bug
        return canZoom && gscSlideshowCanZoomIn();
    }

    me.fsoSliderZoomIn = function(keepScrollPosition) {

        if(!fsoSliderCanZoomIn()) {
            return;
        }

        EventTracker.trackZoom("In");

        scaledImages = {};

        // no zooming for IE8-
        if (globalIsIE) return;

        // no zooming for small (mobile) screens
        if (screen && screen.width && screen.width <= 800) return;

        if (fsoSliderZoomedIn) return;
        sliderEndAnimation();
        // scroll to top immediately
        if(!keepScrollPosition) {
            $('body')[0].scrollTop = 0;
        }

        $('.fso-slide-lower-bg .slide-selectors').css('left', $(window).width() / 2 - fsoSlideWidth / 2);

        if (fsoSliderZoomTimeout > 0) clearTimeout(fsoSliderZoomTimeout);

        $('.fso-zoomer').addClass('fadeOut').removeClass('fadeIn');

        // $('#header_and_content_container').css('overflow', 'visible');
        
        $('.fso-custom-slider-fader').css('display', 'block');

        /*
        $('.fso-custom-slider-fader').css('opacity', 0).css('display', 'block');
        setTimeout(function() {
            $('.fso-custom-slider-fader').css('opacity', 1);
        }, 100);
        */

        var zoomRatio = this.fsoSliderCalculateZoomRatio();

        $slideshowMainElem.find('.slide-stretcher-outer')
            .css('-moz-transform', '-moz-translate3d(0px, ' + -zoomRatio.verticalDelta + 'px, 0px) scale3d(' + zoomRatio.scaleRatio + ',' + zoomRatio.scaleRatio + ',1.0)')
            .css('-ms-transform', '-ms-translate3d(0px, ' + -zoomRatio.verticalDelta + 'px, 0px) scale3d(' + zoomRatio.scaleRatio + ',' + zoomRatio.scaleRatio + ',1.0)')
            .css('-o-transform', '-o-translate(0px, ' + -zoomRatio.verticalDelta + 'px) scale3d(' + zoomRatio.scaleRatio + ',' + zoomRatio.scaleRatio + ',1.0)')
            .css('transform', 'translate3d(0px, ' + -zoomRatio.verticalDelta + 'px, 0px) scale3d(' + zoomRatio.scaleRatio + ',' + zoomRatio.scaleRatio + ',1.0)')
            .css('-webkit-transform', 'translate3d(0px, ' + -zoomRatio.verticalDelta + 'px, 0px) scale3d(' + zoomRatio.scaleRatio + ',' + zoomRatio.scaleRatio + ',1.0)');
        $('.additional-zoomer-elem')
            .css('-moz-transform', '-moz-translate3d(0px, ' + -zoomRatio.verticalDelta + 'px, 0px) scale3d(' + zoomRatio.scaleRatio + ',' + zoomRatio.scaleRatio + ',1.0)')
            .css('-ms-transform', '-ms-translate3d(0px, ' + -zoomRatio.verticalDelta + 'px, 0px) scale3d(' + zoomRatio.scaleRatio + ',' + zoomRatio.scaleRatio + ',1.0)')
            .css('-o-transform', '-o-translate(0px, ' + -zoomRatio.verticalDelta + 'px) scale3d(' + zoomRatio.scaleRatio + ',' + zoomRatio.scaleRatio + ',1.0)')
            .css('transform', 'translate3d(0px, ' + -zoomRatio.verticalDelta + 'px, 0px) scale3d(' + zoomRatio.scaleRatio + ',' + zoomRatio.scaleRatio + ',1.0)')
            .css('-webkit-transform', 'translate3d(0px, ' + -zoomRatio.verticalDelta + 'px, 0px) scale3d(' + zoomRatio.scaleRatio + ',' + zoomRatio.scaleRatio + ',1.0)');

        // zoom back videos
        $slideshowMainElem.find('.video-slide')
            .css('-moz-transform', '-moz-translate3d(0px, ' + (1/-zoomRatio.verticalDelta) + 'px, 0px) scale3d(' + (1/zoomRatio.scaleRatio) + ',' + (1/zoomRatio.scaleRatio) + ',1.0)')
            .css('-ms-transform', '-ms-translate3d(0px, ' + (1/-zoomRatio.verticalDelta) + 'px, 0px) scale3d(' + (1/zoomRatio.scaleRatio) + ',' + (1/zoomRatio.scaleRatio) + ',1.0)')
            .css('-o-transform', '-o-translate(0px, ' + (1/-zoomRatio.verticalDelta) + 'px) scale3d(' + (1/zoomRatio.scaleRatio) + ',' + (1/zoomRatio.scaleRatio) + ',1.0)')
            .css('transform', 'translate3d(0px, ' + (1/-zoomRatio.verticalDelta) + 'px, 0px) scale3d(' + (1/zoomRatio.scaleRatio) + ',' + (1/zoomRatio.scaleRatio) + ',1.0)')
            .css('-webkit-transform', 'translate3d(0px, ' + (1/-zoomRatio.verticalDelta) + 'px, 0px) scale3d(' + (1/zoomRatio.scaleRatio) + ',' + (1/zoomRatio.scaleRatio) + ',1.0)');

        // slide controls animation
        // get original position
        $slideshowMainElem.find('.slide-controls').css('position', 'absolute');
        var originalOffset = $slideshowMainElem.find('.slide-arrow-holder').offset();

        var dotsOriginalOFfset = $slideshowMainElem.find('.scrolling-dots').offset();

        // zoom in
        $slideshowMainElem.addClass('zoomedIn');
        $('body').addClass('slideshow-zoomed-in');
        // end of zoom in

        // end position
        $slideshowMainElem.find('.slide-arrow-holder').addClass('no-transition');
        $slideshowMainElem.find('.slide-controls').css('position', '');
        var fixedFixedOffset = $slideshowMainElem.find('.slide-arrow-holder').offset();;

        timeline && timeline.stop();
        timeline = new TimelineMax();
        TweenMax.set($slideshowMainElem.find('.slide-controls, .scrolling-dots'), {clearProps: 'all'});

        // transform
        timeline.from($slideshowMainElem.find('.slide-controls'), 0.5, {
            x:  ( originalOffset.left - fixedFixedOffset.left ),
            width: $(window).width() - 2*(originalOffset.left - fixedFixedOffset.left),
            y: originalOffset.top - fixedFixedOffset.top,
            clearProps: 'all',
            onComplete: function(){
                var target = this.target;
                target.find('.slide-arrow-holder').removeClass('no-transition');
            },
            ease: Power4.easeInOut
        });

        
        var fixedDotsOffset = $slideshowMainElem.find('.scrolling-dots').offset();;
        timeline.from($slideshowMainElem.find('.scrolling-dots'), 0.5, {
            y: dotsOriginalOFfset.top - fixedDotsOffset.top,
            ease: Power4.easeInOut
        }, 0.1);
        // end of slide controls animation

        // a tiny delay was added here, so the scroll event doesn't immediately close the slideshow
        // if the page scrolls
        setTimeout(function() {
            fsoSliderZoomedIn = true;
            fsoSliderZoomedInScaled = true;
        }, 50);
        
        /*
        // $('.slide-zoomer').css('opacity', 0);
        setTimeout(function() {
            $('.slide-zoomer').find('span').text(jsStrings['scn-fso-exit']);
        }, 100);
        */

        // fix up the apple dots again
        // $('.slide-dots-holder-inner').css('opacity', 0);
        setTimeout(function() {
            fsoSliderRecalculateAppleDots();
            fsoSliderFixAppleDots(currentActiveSlideIdx);
        }, 1000);
    /*
        // if there's a double-size image for current slide, load that in here
        $mySlides.eq(currentActiveSlideIdx).find('.image-holder .zoomer-image:not([src]):not(.loaded)').each(function() {
            loadImage($(this));
        });

        // slowly load in the other double-sized images as well
        var i = 0;
        $mySlides.find('.image-holder .zoomer-image:not([src]):not(.loaded)').each(function() {
            var $this = $(this);
            (function() {
                setTimeout(function() {
                    loadImage($this);
                }, 1000 * i++);
            })();
        });
    */
        var self = this;
        self.prepareScaleImages()
        setTimeout(function(){
            self.prepareScaleImages()
        }, 1000);


    }

    me.prepareScaleImages = function() {
        var self = this;
        var zoomRatio = self.fsoSliderCalculateZoomRatio();
        var scale = zoomRatio.scaleRatio;
        self.cancelZooming = false;

        scaledImages = {};
        $mySlides.eq(currentActiveSlideIdx).find('img').each(function(index, el) {
            self.scaleImage(el, scale, currentActiveSlideIdx+"_"+index, true);
        });


        // slowly load +2 and -2 images
        setTimeout(function(){
            if(!$slideshowMainElem.hasClass('zoomedIn')) {
                return;
            }

            $mySlides.find('.loaded__zoomed, .loading__zoomed').removeClass('loaded__zoomed loading__zoomed');
            scaledImages = {};

            var $images = $mySlides.find('img');
            $mySlides.each(function(index, el) {
                if(index != currentActiveSlideIdx) {
                    var $el = $(el);
                    $el.find('.image-item').addClass('js-preview');
                    _.each($el.find('img'), function(value, key, list){
                        var $img = $(value);
                        if(!$img.attr('src') || $img.attr('src').indexOf('.svg') == -1) {

                            if(!$img.attr('data-src') && $img.attr('src')) {
                                $img.attr('data-src', $img.attr('src'))
                            }

                            $img.attr('src', '');
                        }
                    });
                }
            });

            self.scaleAdjacentImages();
        }, 500);
    }

    // slowly load +n and -n images
    me.scaleAdjacentImages = function(n) {
        if(!n) {
            n = 2;
        }
        var self = this;
        var zoomRatio = self.fsoSliderCalculateZoomRatio();
        var scale = zoomRatio.scaleRatio;

        var i = 0;

        // Create a new empty promise
        var sequence = Promise.resolve();
        var promises = [];

        var startIndex = currentActiveSlideIdx;

        for(var j = startIndex; j < n * $mySlides.length; j++) {
            if(j < $mySlides.length && Math.abs(currentActiveSlideIdx - j) <= n) { 
                var slideIdx = j;
                var $slide = $mySlides.eq(slideIdx);
                $slide.find('img:not(.loaded__zoomed):not(.loading__zoomed)').each(function(index, el) {
                    sequence = sequence.then(function() {
                        return self.scaleImage(el, scale, slideIdx+"_"+index);
                    });
                    i++;
                });
            }

            var prevSlideIdx = n*currentActiveSlideIdx - j + 1;
            if(prevSlideIdx >= 0 && Math.abs(currentActiveSlideIdx - prevSlideIdx) <= n) {
                var slideIdx = prevSlideIdx;
                var $slide = $mySlides.eq(slideIdx);
                $slide.find('img:not(.loaded__zoomed):not(.loading__zoomed)').each(function(index, el) {
                    sequence = sequence.then(function() {
                        return self.scaleImage(el, scale, slideIdx+"_"+index);
                    });
                    i++;
                });
            }
        }

        sequence = sequence.then(function() {
            if(n < 5) {
                self.scaleAdjacentImages(5);
            }
        });
    }

    me.scaleImage = function(el, scale, imgIdx, addZoomClass) {
        var self = this;
        return new Promise(function(resolve, reject) {
            if(!$slideshowMainElem.hasClass('zoomedIn') || self.cancelZooming) {
                console.log('cancel zooming');
                reject();
                return;
            }


            var cropScale = 1.75;
            if(window.devicePixelRatio > 1) {
                cropScale *= 2;
            }

            var MAX_IMAGE_WIDTH = 1400*window.devicePixelRatio;

            var $el = $(el);

            var cropfitWidth = Math.round($el.attr('data-width') * cropScale);
            cropfitWidth = Math.min(MAX_IMAGE_WIDTH, cropfitWidth);
            var width = Math.round($el.attr('data-width') * scale);
            var height = Math.round($el.attr('data-height') * scale);

            var imageWidth = parseInt($el.attr('data-width'));

            if(!cropfitWidth) {
                resolve();
                console.error('missing data-width on ', $el);
                var url = $el.attr('data-src');
                if(url.substr(0,1) != "/" && url.substr(0, 4) != "http") {
                    url = "/" + url;
                }
                $el.attr('src', url);
                return;
            }
            
            // try image dimentions if loaded
            var w = $el.width();
            var h = $el.height();

            // if(w > 0 && h > 0) {
            //     imageWidth = w;
            //     width = Math.round(w * scale);
            //     height = Math.round(h * scale);
            // }

            var imgSrc = el.getAttribute('data-src');
            var slide = getSlideInfo(imgSrc);
            var imgURL = slide.SrcScale1x;
            if(window.devicePixelRatio > 1) {
                imgURL = slide.SrcScale2x;
            }


            if ( imageWidth > 400 && imageWidth * scale != Math.round(imageWidth * scale) ) {
                var newImagwWidth = imageWidth;
                for (var index = 0; index < 20; index++) {
                    newImagwWidth ++;
                    if( newImagwWidth * scale == Math.round(newImagwWidth * scale) ) {
                        imageWidth = newImagwWidth;
                        width = Math.round(imageWidth * scale);

                        var styleAttr = $(el).closest('.image-item').attr('style');
                        var cssWidth = '';

                        if (styleAttr) {
                            var styleProps = styleAttr.split(';');
                            for (var i = 0; i < styleProps.length; i++) {
                                var prop = styleProps[i].trim();
                                if (prop.startsWith('width:')) {
                                    cssWidth = prop.substring(6).trim();
                                    break;
                                }
                            }
                        }

                        $(el).closest('.image-item').attr('data-original-width',  cssWidth);
                        $(el).closest('.image-item').css('width', (imageWidth / 860 * 100) + '%');
                        $(el).closest('.image-item').addClass('image-item__resized');
                        break;
                    }
                }
            }

            // parse out path
            var l = document.createElement("a");
            l.href = imgURL;
            imgURL = l.pathname;
            if(imgURL.indexOf('/FURL') == -1) {
                imgURL = "/FURL" + imgURL;
            }

            if(l.search) {
                imgURL = imgURL + l.search;
            }

            // imgURL += "?_=" + cacheId;

            if(scaledImages[imgURL + imgIdx + "_" + scale*window.devicePixelRatio]) {
                resolve();
                return;
            }
            scaledImages[imgURL + imgIdx + "_" + scale*window.devicePixelRatio] = true;

            el.classList.add('loading__zoomed');

            if(window.Cache) {
                try {
                    caches.open('blob-cache-3').then(function(cache) {
                      var request = new Request(imgURL + "_" + imageWidth + "_" + (scale * window.devicePixelRatio));
                      cache.match(request).then(function(response){
                            if(response) {
                                response.blob().then(function(blob){
                                    var objectURL = URL.createObjectURL(blob);
    
                                    if(addZoomClass) {
                                        $slideshowMainElem.addClass('slideshow-zoomed');
                                    }
    
                                    el.classList.add('loaded', 'loaded__zoomed');
                                    el.classList.remove('loading__zoomed');
                                    el.src = objectURL;
                                    resolve();
                                }, function(){
                                    zoomImage(el, imgURL, width, addZoomClass, scale, cache).then(resolve, reject);
                                });
                            } else {
                                zoomImage(el, imgURL, width, addZoomClass, scale, cache).then(resolve, reject);
                            }
                        }, function(){
                            zoomImage(el, imgURL, width, addZoomClass, scale, cache).then(resolve, reject);
                        });
                    }, function(){
                        zoomImage(el, imgURL, width, addZoomClass, scale).then(resolve, reject);
                    });
                } catch (error) {
                    console.error(error);
                    zoomImage(el, imgURL, width, addZoomClass, scale).then(resolve, reject);
                }
            } else {
                zoomImage(el, imgURL, width, addZoomClass, scale).then(resolve, reject);
            }

        });
    }

    function zoomImage(el, imgURL, width, addZoomClass, scale, cache) {
        return new Promise(function(resolve, reject) {
            getZoomedImage(imgURL, width, addZoomClass, scale, cache).then(function(objectURL){
                if(!objectURL) {
                    reject();
                    return;
                }
                el.classList.add('loaded', 'loaded__zoomed');
                el.classList.remove('loading__zoomed')
                el.src = objectURL;
                resolve();
            }, function(){
                reject();
            });
        });
    }

    function getZoomedImage(imgURL, width, addZoomClass, scale, cache) {
        return new Promise(function(resolve, reject) {
            var img = document.createElement('IMG');

            $(img).on('load', function() {
                var aspectRatio = img.width / img.height;
                var height = width / aspectRatio;
                
                // console.log('LOADED', imgURL, width, height);
                var canvas = document.createElement('CANVAS');
                canvas.width = width;
                canvas.height = height;
                
                if(window.devicePixelRatio > 1) {
                    canvas.width *= window.devicePixelRatio;
                    canvas.height *= window.devicePixelRatio;
                }

                var imgType = imgURL.indexOf('.png') > -1 ? 'image/png' : 'image/jpeg';

                picaR.resize(img, canvas, {
                    alpha: imgURL.indexOf('.png') > -1,
                }).then(function(result){
                    window.res = result;
                    return picaR.toBlob(result, imgType);
                }).then(function(blob){
                    if(!$slideshowMainElem.hasClass('zoomedIn')) {
                        return;
                    }

                    if(cache) {
                        cache.put(imgURL + "_" + scale*window.devicePixelRatio, new Response(blob));
                    }

                    if(addZoomClass) {
                        $slideshowMainElem.addClass('slideshow-zoomed');
                    }
                    var objectURL = URL.createObjectURL(blob);
                    resolve(objectURL);
                }).catch(function(error) {
                  console.log(error);
                  resolve();
                });
            });

            $(img).on('error', function(error) {
                console.error(error);
                // try again
                setTimeout(function(){
                    self.scaleImage(el, scale, addZoomClass).then(resolve, reject);
                }, 1000);
            });

            img.classList.add('loading__zoomed');
            img.setAttribute('src', imgURL);
        });
    }

    // (pre)load an image, with all its trimmings
    function loadImage($this) {

        if (!$this[0]) return;

        if (!$this.hasClass('loaded') && !$this.attr('src')) {
            logger.debug('(pre)loading double: ' + $this.attr('data-double-src'));
            $this.on('load', function() {
                $this.addClass('loaded').parent('.image-holder').addClass('double-loaded');
            });
            $this.attr('src', $this.attr('data-double-src'));
        }
    }

    me.fsoSliderZoomOut = function() {
        $('.bs-extender__slideshow-holder').removeClass('bs-extender__slideshow-holder__fixed');
        
        // no zooming for IE8-
        if (globalIsIE) return;

        if (!fsoSliderZoomedIn) return;
        sliderEndAnimation();

        EventTracker.trackZoom("Out");

        $('.fso-zoomer').css('display', 'block').addClass('fadeIn').removeClass('fadeOut');

        // $('.fso-custom-slider-fader').css('opacity', 0);
        $('.fso-custom-slider-fader').css('display', 'none');

        // $('#header_and_content_container').css('overflow', 'hidden');

        fsoSliderZoomTimeout = setTimeout(function() {
            // $('#header_and_content_container').css('overflow', 'hidden');
            fsoSliderZoomTimeout = 0;
        }, 1500);

        $slideshowMainElem.find('.slide-stretcher-outer').css('transform', 'none')
            .css('-moz-transform', 'none')
            .css('-ms-transform', 'none')
            .css('-o-transform', 'none')
            .css('-webkit-transform', 'none');
        $('.additional-zoomer-elem').css('transform', 'none')
            .css('-moz-transform', 'none')
            .css('-ms-transform', 'none')
            .css('-o-transform', 'none')
            .css('-webkit-transform', 'none');

        // zoom back videos
        $slideshowMainElem.find('.video-slide').css('transform', 'none')
            .css('-moz-transform', 'none')
            .css('-ms-transform', 'none')
            .css('-o-transform', 'none')
            .css('-webkit-transform', 'none');


        var endWidth = $slideshowMainElem.find('.slide-right-arrow2')[0].offsetLeft - $slideshowMainElem.find('.slide-left-arrow2')[0].offsetLeft -
                   $slideshowMainElem.find('.slide-arrow-holder').width();

        // slide controls animation
        // get original position
        $slideshowMainElem.find('.slide-controls').css('position', 'fixed');
        var originalOffset = $slideshowMainElem.find('.slide-arrow-holder').offset();
        var dotsOriginalOFfset = $slideshowMainElem.find('.scrolling-dots').offset();


        $slideshowMainElem.removeClass('zoomedIn slideshow-zoomed');
        $('body').removeClass('slideshow-zoomed-in');
        fsoSliderZoomedIn = false;
        fsoSliderZoomedInScaled = false;

        // end position
        $slideshowMainElem.find('.slide-arrow-holder').addClass('no-transition');
        $slideshowMainElem.find('.slide-controls').css('position', 'absolute');
        var fixedFixedOffset = $slideshowMainElem.find('.slide-arrow-holder').offset();;

        timeline && timeline.stop();
        timeline = new TimelineMax();
        TweenMax.set($slideshowMainElem.find('.slide-controls'), {clearProps: 'all'});

        // transform
        timeline.fromTo($slideshowMainElem.find('.slide-controls'), 0.5, {
            x: ( originalOffset.left - fixedFixedOffset.left ),
            y: (originalOffset.top - fixedFixedOffset.top),
            width: endWidth,
        }, {
            x: 0,
            y: 0,
            width: 1080,
            clearProps: 'all',
            onComplete: function(){
                var target = this.target;
                target.find('.slide-arrow-holder').removeClass('no-transition');
            },
            ease: Power4.easeInOut
        });
        
        var fixedDotsOffset = $slideshowMainElem.find('.scrolling-dots').offset();;
        timeline.from($slideshowMainElem.find('.scrolling-dots'), 0.5, {
            y: dotsOriginalOFfset.top - fixedDotsOffset.top,
            clearProps: 'all',
            ease: Power4.easeInOut
        }, 0.1);
        // end of slide controls animation

        /*
        // $('.slide-zoomer').css('opacity', 0);
        setTimeout(function() {
            $('.slide-zoomer').find('span').text(jsStrings['scn-fso-expand']);
        }, 100);
        */

        // fix up the apple dots again
        // $('.slide-dots-holder-inner').css('opacity', 0);
        // setTimeout(function() {
        //     fsoSliderRecalculateAppleDots();
        //     fsoSliderFixAppleDots(currentActiveSlideIdx);
        // }, 2000);

        // load normal resoulution for slides
        $mySlides.find('img').removeClass('loaded');
        loadSurroundingSlides(currentActiveSlideIdx);
        this.preloadSlides();

        $('slide [data-original-width]').each(function(index, el) {
            var $el = $(el);
            $el.css('width', $el.attr('data-original-width'));
        });

        var scrollTop = this.initialScrollTop;
        var that = this;
        if(scrollTop) {
            setTimeout(function() {
                window.scrollTo(window.scrollX, scrollTop);
            }, 20);
            setTimeout(function() {
                window.scrollTo(window.scrollX, scrollTop);
                that.initialScrollTop = 0;
            }, 50);
        }

    }

    me.fsoSliderCalculateZoomRatio = function() {

        var tempSliderTop = fsoSliderTop || 0;

        // FIXME review this further - this seems to only work if this is zero
        tempSliderTop = 0;

        var windowWidth = $(window).width();

        var horizRatio = (windowWidth - 200) / fsoSlideWidth;
        var verticalRatio = ($(window).height() - 120) / this.fsoSliderZoomHeight;
        var scaleRatio = Math.min(horizRatio, verticalRatio);

        if (scaleRatio < 1) scaleRatio = 1;

         // max size is 1400px
        if(860 * scaleRatio > 1400) {
            scaleRatio = 1400 / 860;
        }

        scaleRatio = Math.round( scaleRatio * 10 ) / 10;

        // more then that sometimes create pixalated images...
        if(scaleRatio > 1.3) {
            scaleRatio = 1.3;
        }
        if(scaleRatio <= 1.1) {
            scaleRatio = 1;
        }

        var myNewTop = Math.floor(tempSliderTop - ((this.fsoSliderZoomHeight / 2) * scaleRatio - (this.fsoSliderZoomHeight / 2)));

        // remove me if want to scale image up
        // scaleRatio = 1;
        
        // if this is a horizontal zoom, center it vertically
        myNewTop -= Math.floor(($(window).height() - this.fsoSliderZoomHeight * scaleRatio) / 2) - 30;

        myNewTop -= $(window).scrollTop();


        if ($('#header_and_content_container').length) {
            myNewTop += $('#header_and_content_container').position().top;
        } else if ($slideshowMainElem.length) {
            myNewTop += $slideshowMainElem.offset().top;
        }

        // HACK for now - don't zoom
        if (false && window.deviceCustomType && deviceCustomType == 'desktop') {
            scaleRatio = 1;
            myNewTop = Math.floor(($(window).height() - this.fsoSliderZoomHeight * scaleRatio) / 2);
            myNewTop -= $('#header_and_content').position().top;
            myNewTop *= -1;
        }  

        return {
            verticalDelta: myNewTop,
            scaleRatio: scaleRatio
        };

    }

    // returns the current active slide index (starts with '0')
    me.currentSlideIdx = function() {
        return currentActiveSlideIdx;
    }

    // total number of slides
    me.totalSlides = function() {
        return totalSlides;
    }

    // if circular or not
    me.isCircularClone = function() {
        return isCloned;
    }

    // extracting event firing here, in case we wanna change what the events fire on
    function fireEvent(eventName, eventData) {
        $mySlideshowWrapper.trigger(eventName, eventData);
    }

    // change hash without adding to history (if the browser supports it)
    function replaceHash(newHash) {
        if (history && history.replaceState) {
            history.replaceState({}, document.title, '#' + newHash);
            return fsoSliderHashChange();
        }
        location.hash = newHash;
    }

    me.startVideoForSlide = function(num) {
        $myVideoJsElem = $mySlides.eq(num).addClass('ios-video-playing').find('.video-js');
        if ($myVideoJsElem.length) {
            playVideoJS($myVideoJsElem);
        }
    }

    me.gotoSlide = function(num) {
        if(num != currentActiveSlideIdx)
        fsoSliderGotoSlide(num, true);
    }

    me.gotoSlideNoAnimation = function(num) {
        if(num != currentActiveSlideIdx)
        fsoSliderGotoSlide(num, false);
    }

    me.replaceHash = function(num) {
        replaceHash(num);
    }

    function initVideoJS(el) {

        // 26 Feb 2015 - we're not going to use videojs at all for the iPad, as it was
        // contributing to the video playback being funky on the iPad
        if ($('html').hasClass('device-ipad')) {

            $('video').each(function() {
                this.preload = 'auto';
                this.controls = true;
                var thisVideo = this;
                this.addEventListener('play', function(e) {
                    thisVideo.parentNode.classList.add('ios-video-playing');
                    // thisVideo.parentNode.parentNode.parentNode.classList.add('ios-video-playing');
                });
            });
            return {
                play: function() {}
            }
        }

        el = $(el);
        el.addClass('video-js-inited')
        var vid;
        if (el && el.get(0) && el.get(0).tagName && el.get(0).tagName.toUpperCase() === 'VIDEO') {
            var opts = jQuery.extend({}, videoOptions);
            opts.muted = true;
            opts.autoplay = false;
            try {
                opts = JSON.parse(el.attr('data-gsc-setup'));
            } catch (e) {}
            
            if(el.attr('data-src-prefix')) {
                var src = el.attr('data-src-prefix');
                opts.sources = [
                    { src: src + '.webm', type: 'video/webm; codecs="vp9"' },
                    { src: src + '-h265.mp4', type: 'video/mp4; codecs="hvc1"' },
                    { src: src + '.mp4?1', type: 'video/mp4; codecs="avc1"' }
                ];

                if(el.data('translatable') == true) {
                    var lang = globalLang;
                    if($('html').attr('lang') == 'es-ES') {
                        lang = 'es_ES';
                    }
                    opts.sources = [
                        { src: src + '_' + lang + '.webm', type: 'video/webm; codecs="vp9"' },
                        { src: src + '_' + lang + '-h265.mp4', type: 'video/mp4; codecs="hvc1"' },
                        { src: src + '_' + lang + '.mp4?1', type: 'video/mp4; codecs="avc1"' }
                    ];
                }
            }

            
            if (navigator.userAgent.toLowerCase().indexOf('firefox') > -1 && 
                navigator.platform.indexOf("Win") > -1 &&
                el.find('source').eq(0).attr('type') != 'video/webm') {
            }

            opts.html5 = {
                nativeAudioTracks: false,
                nativeVideoTracks: false,
                vfh: {
                    overrideNative: true,
                },
              };

            vid = videojs(el.get(0), opts || 
                {
                    controls: true,
                    html5: {
                        nativeVideoTracks : false,
                        nativeAudioTracks : false,
                        vfh: {
                          overrideNative: true,
                        }
                      },
                });

            vid.on('play', function() {
                $('body').addClass('slideshow-vid-playing');
                $(el).closest('slide').addClass('video-playing');
                $(el).closest('slide').removeClass('video-played');
            });

            vid.on('ended', function() {
                $('body').removeClass('slideshow-vid-playing');
                $(el).closest('slide').removeClass('video-playing');
                $(el).closest('slide').addClass('video-played');
            });

            if(el.data('translatable') == true) {
                vid.one('error', function() {
                    // try default language
                    var src = el.attr('data-src-prefix');
                    setTimeout(() => {
                        vid.src([
                            { src: src + '.webm', type: 'video/webm; codecs="vp9"' },
                            { src: src + '-h265.mp4', type: 'video/mp4; codecs="hvc1"' },
                            { src: src + '.mp4?1', type: 'video/mp4; codecs="avc1"' }
                        ]);
                        vid.play();
                    }, 500);
                    console.log('error loading video, trying default language');
                });
                
            }



            // Show poster on video end (option)
            if (opts && opts.showPosterOnVideoEnnd) {
                vid.on('ended', function() {

                    // cancel out fullscreen
                    try { vid.cancelFullScreen() } catch (e) {}
                    
                    // reset the video to the beginning
                    vid.pause(); // (IE10 requires us to pause it)
                    if (typeof vid.currentTime === 'function') vid.currentTime(0);

                    // show the poster image
                    vid.posterImage.show();

                    // add a class
                    $(vid.el()).addClass('gsc-ended');
                });
            }

            // Remove spinner on play (Firefox requires this sometimes)
            vid.on('play', function (e) {
                el.siblings('.vjs-loading-spinner').hide();
            })
            
            var slide = el.closest('slide');
            $(slide).find('.item-replay-button').click(function() {
                vid.currentTime(0);
                vid.play();
            });

            $(slide).find('.item-replay-button').on('touchend', function(event) {
                event.preventDefault();
                event.stopPropagation();
                event.stopImmediatePropagation();
                vid.currentTime(0);
                vid.play();
            });

        } else {
            vid = videojs(el.get(0));
        }

        return vid;
    }

    function playVideoJS(el) {

        // for testing
        if (window.globalGetParams && globalGetParams.headless) return;

        var vid = initVideoJS(el);
        setTimeout(function () {

            if( vid.el().classList.contains('video-overlay-autoplay') ) {
                setTimeout(function () {
                    vid.controls(false);
                    vid.muted(true);
                    vid.play();
                }, 250);
            } else {
                if (vid.muted()) {
                    vid.muted(false);
                    vid.controls(true);
                    vid.pause();
                    $('.video-slide-muted').removeClass('video-slide-muted');
                    vid.currentTime(0);
                }
            }


            vid.play();
            $('body').addClass('slideshow-vid-playing');

            vid.on('ended', function() {
                $('body').removeClass('slideshow-vid-playing');
            });

            vid.on('timeupdate', function() {
                if (vid.paused()) {
                    $('body').removeClass('slideshow-vid-playing');
                } else {
                    $('body').addClass('slideshow-vid-playing');
                }
            });

        }, 1);
    }

    // Static methods
    GscResponsiveSlider.initVideoJS = initVideoJS;
    GscResponsiveSlider.playVideoJS = playVideoJS;

    return me;

})();

var globalHas3dResult;

// @from https://gist.github.com/lorenzopolidori/3794226
var globalHas3d = (function(){
    if(globalHas3dResult !== undefined ) {
        return globalHas3dResult;
    }
    var el = document.createElement('p'),
    globalHas3d,
    transforms = {
        'webkitTransform':'-webkit-transform',
        'OTransform':'-o-transform',
        'msTransform':'-ms-transform',
        'MozTransform':'-moz-transform',
        'transform':'transform'
    };

    // body doest exists yet
    if(!document.body) {
        return true;
    }

    // Add it to the body to get the computed style
    document.body.insertBefore(el, null);

    var style = window.getComputedStyle(el);

    for(var t in transforms){
      if (transforms.hasOwnProperty(t)) {
        if( el.style[t] !== undefined ){
            el.style[t] = 'translate3d(1px,1px,1px)';
            globalHas3d = style.getPropertyValue(transforms[t]);
          }
        }
    }

    document.body.removeChild(el);

    globalHas3dResult = (globalHas3d !== undefined && globalHas3d.length > 0 && globalHas3d !== "none")

    return globalHas3dResult;
}());

function determineDownloadSpeed(callback) {

    var oProgress = document.getElementById("progress");
    var startTime, endTime;
    var download = new Image();
    download.onload = function () {
        endTime = (new Date()).getTime();
        callback && callback();
    }
        
    download.onerror = function (err, msg) {
        oProgress.innerHTML = "Invalid image, or error downloading";
    }
        
    startTime = (new Date()).getTime();
    var cacheBuster = "?nnn=" + startTime;
    download.src = imageAddr + cacheBuster;
    
    /*
    function showResults() {
        var duration = (endTime - startTime) / 1000;
        var bitsLoaded = downloadSize * 8;
        var speedBps = (bitsLoaded / duration).toFixed(2);
        var speedKbps = (speedBps / 1024).toFixed(2);
        var speedMbps = (speedKbps / 1024).toFixed(2);
        oProgress.innerHTML = "Your connection speed is: <br />" + 
           speedBps + " bps<br />"   + 
           speedKbps + " kbps<br />" + 
           speedMbps + " Mbps<br />";
    }
    */

}

function gscSlideshowCanZoomIn() {
    var isChrome = /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor);


    // safari has blurry text zooming bug
    return isChrome;
}


/**

@file
Autoplayer/controller for a slideshow.
@documentation http://wiki.goldeneraproductions.org/wiki/Gsc_headers

*/

var GscSliderAutoplay = function(slideshowWrapperDom, slideshowRef, opts) {
    // mix in the opts
    this.slideshowWrapperDom = slideshowWrapperDom;
    this.slideshowRef = slideshowRef;
    if (opts) for (var key in opts) this[key] = opts[key];
}

GscSliderAutoplay.prototype = (function() {

    var me = {};

    // defaults
    me.autosliding = false; // need explicit start() to start sliding
    me.interval = 9000;

    // initializes (hookups, create DOM elements etm.), does not start autoplay yet
    me.init = function() {

        var self = this;

        // don't to it for IE
        if (globalIsIE) return this;

        // sanity checks
        if (!this.slideshowWrapperDom) {
            window.console && console.error('No slideshowWrapperDom supplied - cannot initialize autoslider!');
            return this;
        }

        if (!this.slideshowRef) {
            window.console && console.error('No slideshowRef supplied - cannot initialize autoslider!');
            return this;
        }

        if (!(this.slideshowWrapperDom instanceof jQuery)) this.slideshowWrapperDom = $(this.slideshowWrapperDom);

        // create the DOM elements
        this.slideshowWrapperDom.append('<div class="slide-gutter"><div class="slider-artifact">» {{T "gcui_scientology:menu"}}</div><div class="slider-play-button paused"></div></div>');
        this.slideshowWrapperDom.find('.slide-wrapper').append('<div class="slideshow-autoslide-strip-holder"><div class="slideshow-autoslide-strip"></div></div>');
        this.stripDom = this.slideshowWrapperDom.find('.slideshow-autoslide-strip');
        this.playbuttonDom = this.slideshowWrapperDom.find('.slider-play-button');

        this.playbuttonDom.on('click', function() {
            if (!self.autosliding) {
                self.start();
            } else {
                self.stop();
            }           
        });

        // hook up with the slideshow
        this.slideshowWrapperDom.bind('userInteraction', function() {
            self.stop();
        });
        this.slideshowWrapperDom.bind('videoAutoplay', function() {
            // console.log('videoAutoplay event received');
            _.defer(function() {
                self.stop();    
            });
            setTimeout(function() {
               self.stop();     
           }, 500);
        });

        // console.log('autoplayer is listening for videoAutoplay');

        setTimeout(function(){
            $(window).resize();
        }, 2000);

        return this;

    }

    // animate the strip
    me.animateToNext = function() {

        var self = this;

        this.stripDom.width(0);

        // the end, my friend, the end ...
        if (!this.slideshowRef.isCircularClone() && this.slideshowRef.currentSlideIdx() == this.slideshowRef.totalSlides() - 1) {
            this.stop();
            _.defer(function() {
                self.stop();
            });
            return;
        }

        globalAnimationController.cancelAnimation(this.stripDom, true);

        globalAnimationController.animate(this.stripDom, { width: this.stripDom.parent().outerWidth(true) },
            this.interval + 'ms linear',
            function() {
                self.slideshowRef.sliderMoveNext();
                _.defer(function() {
                    self.animateToNext();
                });
            }
        );

    }


    // start autoplaying
    me.start = function() {

        // console.log('autosliding started');

        // don't to it for IE
        if (globalIsIE) return this;

        this.animateToNext();
        this.playbuttonDom.removeClass('paused');
        this.autosliding = true;
        return this;
    }

    // stop autoplaying
    me.stop = function() {
        globalAnimationController.cancelAnimation(this.stripDom, true);
        this.stripDom.width(0);
        this.playbuttonDom.addClass('paused');
        this.autosliding = false;
        return this;
    }

    return me;

})();


var EventTracker = (function () {
    'use strict';

    function EventTracker() {
        // enforces new
        if (!(this instanceof EventTracker)) {
            return new EventTracker();
        }
    }

    function trackEvent(ec, ea, el, options) {
        window._tr = window._tr || [];
        window._tr && _tr.push(['_trackEvent', ec, ea, el]);
        window._paq && _paq.push(['trackEvent', ec, ea, el]); // piwik
        window._gaq && _gaq.push(['_trackEvent', ec, ea, el]);
        window.ga && ga('send', 'event', ec, ea, el);

        var params = {
            'event_category': ec,
            'event_label': el
        };

        if(options) {
            if(options.callback) {
                params['event_callback'] = options.callback;
            }

            if(options.passive) {
                params['non_interaction'] = true;
            }
        }

        window.gtag && gtag('event', ea, params);
        // log the event if analytics is turned off
        window._gaq || window.ga || (window.console && console.log.apply(console, arguments));
    }


    EventTracker.prototype.trackSlideView = function (index) {
        trackEvent("Slideshow", "View", "Slide " + index, {passive: true});
        // for IAS 2024 tracking
        if(window.location.pathname == "/scientology-today/events/ias-event-2024.html") {
            // Ensure the conversion event is tracked only once
            if (!this.conversionTracked && index > 1) {
                window.gtag && gtag('event', 'conversion', {'send_to': 'AW-1005844059/qA_YCP3y4GAQ2-zP3wM'});
                this.conversionTracked = true;
                console.log('conversion tracked');
            }
        }
    }

    EventTracker.prototype.trackArrowClick = function (index, label) {
        trackEvent("Slideshow", "Arrow Click " + label, "To Slide " + index);
    }

    EventTracker.prototype.trackDotClick = function (index) {
        trackEvent("Slideshow", "Clicked Dot", "To Slide " + index);
    }

    EventTracker.prototype.trackZoom = function (label) {
        trackEvent("Slideshow", "Zoomed", label);
    }

    EventTracker.prototype.trackPhotoswipe = function (label) {
        trackEvent("Slideshow", "Photoswipe", label);
    }

    EventTracker.prototype.trackVideo = function (video) {
        video.one('play', function () {
            $('.decade2020--subtitle__overlay').addClass('d-none');
            trackEvent("Video Started", getVideoId(video));
        });

        var tracked = {};

        video.on('timeupdate', function () {
            var watchProgress = video.currentTime() / video.duration() * 100;
            if (isNaN(watchProgress)) {
                return;
            }
            var trackingProgress = Math.floor(watchProgress / 10) * 10;
            if (!tracked[trackingProgress] && (trackingProgress < 20 || trackingProgress > 80)) {
                trackEvent("Video Watched", getVideoId(video), trackingProgress + "%");
            }
            tracked[trackingProgress] = true;
        });

        video.one('ended', function () {
            $('.decade2020--subtitle__overlay').addClass('d-none');
            trackEvent("Video Ended", getVideoId(video));
        });
    }

    EventTracker.prototype.trackScroll = function (video) {
        $(window).scroll(function(event) {
            checkTracking();
        });
        checkTracking();
    }


    function checkTracking() {
        _.each($('.scroll-tracker'), function (element, index) {
            var $el = $(element);
            if(isInViewportVisible($el) && !$el.data('tracked')) {
                var isPassive = true;
                if($el.data('active')) {
                    isPassive = false;
                }
                trackEvent("Scrolling", "Visible", $el.data('label'), {passive: isPassive});
                $el.data('tracked', 'true');
            }
        });
    }

    function getVideoId(vid) {
        var src = vid.src();

        // try to use source
        var els = vid.el().getElementsByTagName('source');
        if (els.length > 0) {
            src = els[0].src;
        }

        // if src ends with /master.m3u8, then trim /master.m3u8
        if (src.endsWith("/master.m3u8")) {
            src = src.substring(0, src.length - "/master.m3u8".length);
            var hlsParts = vid.currentSrc().split('/');

            if (hlsParts && hlsParts.length > 1) {
                var id = hlsParts[hlsParts.length-2];
                var parts = id.split('_');
                if(parts.length > 0) {
                    id = parts.slice(0, parts.length-1).join("_");
                    return id;
                }
            }
        }


        var hlsParts = vid.currentSrc().split('/');

        if (hlsParts && hlsParts.length == 8) {
            var id = hlsParts[hlsParts.length-1];
            var parts = id.split('_');
            if(parts.length > 0) {
                id = parts.slice(0, parts.length-1).join("_");
                return id;
            }
        }

        return "unknown";
    }


    return EventTracker;
}()) ();

/**

@file
Simple animation controller. Had to make a JS animation controller, partially because CSS transitions don't always fire the transitionEnd events (see spec http://dev.w3.org/csswg/css-transitions/#transition-events), which is required for precise control of animation (i.e. in some cases, we need to ensure
that the transition completion callback is called and executed before the next transition
begins).

FIXME: Falls back to jQuery.animate() if no CSS transition capability (uses modernizr for detection).

Requires:
---------

jQuery, underscore.js, modernizr.js

Usage:
------

```javascript
globalAnimationController.animate2d(
	aDomElem,
	{x: -100, y:0},
	'.8s cubic-bezier(0.165, 0.840, 0.440, 1.000)',
	function() { ... }
);
```

*/

var AnimationController = function(opts) {
    // mix in the opts
    if (opts) for (var key in opts) this[key] = opts[key];
}

AnimationController.prototype = (function() {

    var me = {};

    var transitionTransformProps = {
    	'WebkitTransform': '-webkit-transform',
    	'MozTransform': '-moz-transform',
    	'msTransform': '-ms-transform',
    	'OTransform': '-o-transform',
    	'transform': 'transform',
	};

    me.callbacks = {};
    me.maxAnimationId = 0;

    // for 2D transforms (implemented using translate3d for performance)
    me.animate2d = function(aDomElem, aTransform2d, aTransition, aCallbackFunc) {

    	logger.debug('animate2d called for: ' + aTransform2d.x + ', ' + aTransition);

    	var myController = this;
    	if (!(aDomElem instanceof jQuery)) aDomElem = $(aDomElem);

    	var myAnimationId = aDomElem.attr('data-animation-id');
    	if (!myAnimationId) {
    		myAnimationId = myController.maxAnimationId++;
    		aDomElem.attr('data-animation-id', myAnimationId);
    	}

    	myController.cancelAnimation(aDomElem);

    	var myCaller = arguments.callee.caller.parent;
    	_.defer(function() {

	    	if (Modernizr.csstransitions && Modernizr.csstransforms3d) {

	    		// FIXME add to the transition property, don't override (otherwise will cobber other)
	    		if (aTransition != 'none') {
		    		aDomElem.css(
                            Modernizr.prefixed('transition'),
                            transitionTransformProps[Modernizr.prefixed('transform')] + ' ' + aTransition
                        );

                        /*
                        // add some extra CSS that might speed things up
                        .css('-webkit-backface-visibility', 'hidden') // @info http://css-tricks.com/almanac/properties/b/backface-visibility/
                        .css('-webkit-transform-style', 'preserve-3d') // @info http://css-tricks.com/almanac/properties/t/transform-style/
                        .css('transform-style', 'preserve-3d');
                        */

		    	} else {
		    		aDomElem.css(Modernizr.prefixed('transition'), '');
		    	}

	            aDomElem.css(Modernizr.prefixed('transform'), 'translate3d(' + aTransform2d.x + 'px' + ',' + aTransform2d.y + 'px,0)');

	        } else {

	        	// FIXME animation fallback !!!

                /*
	            aDomElem.animate({
	            	left: aTransform2d.x + 'px'
	            });
                */

                aDomElem.css('left', aTransform2d.x + 'px');

	            if (aTransform2d.y != 0) aDomElem.animate({
	            	top: aTransform2d.y + 'px'
	            });

	        }

	        myController.callbacks[myAnimationId] = [aCallbackFunc];

	        logger.debug('animation started to: ' + aTransform2d.x);

	        if (aTransition != 'none' && Modernizr.csstransitions && Modernizr.csstransforms3d) {
		        aDomElem.on('webkitTransitionEnd oTransitionEnd otransitionend transitionend msTransitionEnd MSTransitionEnd gcuiTransitionCancelled', function(e) {
			        if (e.target != aDomElem[0]) return true; // it's not us
			        aDomElem.unbind('webkitTransitionEnd oTransitionEnd otransitionend transitionend msTransitionEnd MSTransitionEnd gcuiTransitionCancelled');
			        logger.debug('transitionEnd called on: ' + aTransform2d.x);
			        _cancelAnimation(aDomElem, myCaller);
			    });
		    } else {

		    	logger.debug('wrapping up no-transition on: ' + aTransform2d.x);

				// if we are not animating at all, just call the animation compeltiong calls right now
		    	if (aTransition == 'none') {
					_cancelAnimation(aDomElem, myCaller);
				} else {

					if (aTransition.match(/ms/)) {
						var myTime = parseFloat(aTransition.replace(/ms .*$/, ''));
					} else {
						var myTime = parseFloat(aTransition.replace(/s .*$/, '')) * 1000;
					}

					setTimeout(function() {
						_cancelAnimation(aDomElem, myCaller);
					}, myTime);

				}
		    }

		});

    };

    // for generic animation
    me.animate = function(aDomElem, aProps, aTransition, aCallbackFunc) {

    	var myController = this;
    	if (!(aDomElem instanceof jQuery)) aDomElem = $(aDomElem);

    	var myAnimationId = aDomElem.attr('data-animation-id');
    	if (!myAnimationId) {
    		myAnimationId = myController.maxAnimationId++;
    		aDomElem.attr('data-animation-id', myAnimationId);
    	}

    	myController.cancelAnimation(aDomElem);

    	var myCaller = arguments.callee.caller.parent;
    	_.defer(function() {

	    	if (Modernizr.csstransitions) {

	    		// FIXME add to the transition property, don't override (otherwise will cobber other)
	    		if (aTransition != 'none') {
	    			aDomElem.css(Modernizr.prefixed('transition'),
	    				/*
	    				_.reduce(aProps, function(m, v, k) {
	    					return m.concat([k + ' ' + aTransition]);
	    				}, []).join(', ')
						*/
						'all ' + aTransition
	    			);

                    /*
	    			// add some extra CSS that might speed things up
					.css('-webkit-backface-visibility', 'hidden') // @info http://css-tricks.com/almanac/properties/b/backface-visibility/
					.css('-webkit-transform-style', 'preserve-3d') // @info http://css-tricks.com/almanac/properties/t/transform-style/
					.css('transform-style', 'preserve-3d');
                    */

		    	} else {
		    		aDomElem.css(Modernizr.prefixed('transition'), '');
		    	}

		    }

	    	_.each(aProps, function(v, k) {
	    		aDomElem.css(k, v);
	    	});

	        myController.callbacks[myAnimationId] = [aCallbackFunc];

	        if (aTransition != 'none' && Modernizr.csstransitions) {

		        aDomElem.on('webkitTransitionEnd oTransitionEnd otransitionend transitionend msTransitionEnd MSTransitionEnd gcuiTransitionCancelled', function(e) {
			        if (e.target != aDomElem[0]) return true; // it's not us
			        aDomElem.unbind('webkitTransitionEnd oTransitionEnd otransitionend transitionend msTransitionEnd MSTransitionEnd gcuiTransitionCancelled');
			        _cancelAnimation(aDomElem, myCaller);
			    });
		    } else {
		    	// if we are not animating at all, just call the animation compeltiong calls right now
		    	if (aTransition == 'none') {
					_cancelAnimation(aDomElem, myCaller);
				} else {

					if (aTransition.match(/ms/)) {
						var myTime = parseFloat(aTransition.replace(/ms .*$/, ''));
					} else {
						var myTime = parseFloat(aTransition.replace(/s .*$/, '')) * 1000;
					}

					setTimeout(function() {
						_cancelAnimation(aDomElem, myCaller);
					}, myTime);

				}
		    }

		});

    };

    // this is an internal one
    var _cancelAnimation = function(aDomElem, aCaller) {

    	var myAnimationId = aDomElem.attr('data-animation-id');

    	// FIXME only remove own transitions, don't clobber all
    	Modernizr.prefixed('transition') && aDomElem.css(Modernizr.prefixed('transition'), '');

    	// call all callbacks for the element first
    	for (var a in me.callbacks[myAnimationId]) {
    		me.callbacks[myAnimationId][a] && me.callbacks[myAnimationId][a].apply(aCaller);
    	}
	    me.callbacks[myAnimationId] = [];

    }

    // call this to cancel any ongoing transitions on the aDomElem
    me.cancelAnimation = function(aDomElem, aSkipCallbacks) {
        if (!(aDomElem instanceof jQuery)) aDomElem = $(aDomElem);
    	if (aSkipCallbacks) this.callbacks[aDomElem.attr('data-animation-id')] = [];
    	aDomElem.trigger('gcuiTransitionCancelled');
    }

    return me;

})();

globalAnimationController = new AnimationController();

/*
@file JS for setting up text elements and any other JS-based styling for slide templates.
Intended to be run before document.ready (does not require jQuery).
*/

// squeeze the text <div> width until it breaks (to be able to center text better)
if (!window.squeezeText) {
    function squeezeText(domElem) {
        return;
        var initialHeight = domElem.offsetHeight;
        var infiniteLoopGuard = 5000;
        while (domElem.offsetHeight == initialHeight && infiniteLoopGuard-- > 0)
            domElem.style.width = (domElem.offsetWidth - 1) + 'px';
        if (infiniteLoopGuard == 0) return window.console && console.error('ERROR: infinite loop');
        domElem.style.width = (domElem.offsetWidth + 1) + 'px';
    }
}

// this was duplicated all over the place (unfortunately, IE8 does not take Array.prototype.forEach)
if (!window._each) {
    function _each(theArray, callback) {
        for (var i = 0, length = theArray.length; i < length; i++) callback(theArray[i]);
    }
}

if(window.globalForceSlideHeight == undefined) {
    if (!globalIsIOS) {
        // legacy slideshows were brought over from a tall format (575px height)
        // so ensure that the height is set properly
        globalForceSlideHeight = 575;
    } else {
        if (window.innerWidth <= 768) {
            globalForceSlideHeight = 455;
        } else {
            globalForceSlideHeight = 575;
        }
    }
}

function initDynamicSlides() {
    var maxCaptionImageTopDelta = 20;
    var maxCaptionImageTopDelta2 = 20;

    // don't wait for document.ready
    var tempFirstSlide = document.querySelectorAll('slide:first-child')[0];
    if (tempFirstSlide) {
        var slideHeight = tempFirstSlide.offsetHeight;
        if (slideHeight == 0 || window.globalForceSlideHeight) slideHeight = globalForceSlideHeight;
        var slideWidth = tempFirstSlide.offsetWidth;
    } else {
        var slideHeight = 575;
        var slideWidth = 860;
    }

    _each(document.querySelectorAll('.caption-center-below'), function(myCaption) {

        // no JS for the build `2-1` of the slideshow
        if (document.body.className.match(/templated-slider-build-2-1/)) return;

        var mySlideImages = myCaption.parentNode.getElementsByTagName('img');
        waitForAllImagesToLoad(mySlideImages, function() {

            // get max image height
            var lowestBottom = 0;
            _each(mySlideImages, function(mySlideImage) {
                lowestBottom = Math.max(lowestBottom, mySlideImage.offsetTop + mySlideImage.offsetHeight);
            });

            // smart centering
            squeezeText(myCaption);
            myCaption.style.left = Math.floor((slideWidth - myCaption.offsetWidth) / 2) + 'px';

            // force resizing
            myCaption.offsetHeight;

            // top setting
            myCaption.style.bottom = 'auto';
            myCaption.style.top = (
                lowestBottom + myCaption.offsetHeight +  2 * maxCaptionImageTopDelta < slideHeight ?
                lowestBottom + maxCaptionImageTopDelta :
                lowestBottom + Math.floor((slideHeight - myCaption.offsetHeight - lowestBottom) / 2)
            ) + 'px';

            myCaption.className += ' dynamically-sized';

        });
    });

    _each(document.querySelectorAll('.caption-bottom-left-corner'), function(myCaption) {

        // no JS for the build `2-1` of the slideshow
        if (document.body.className.match(/templated-slider-build-2-1/)) return;

        waitForAllImagesToLoad(myCaption.parentNode.getElementsByTagName('img'), function() {

            // get max image height
            var smallImage = myCaption.parentNode.querySelector('.image-item-3');
            if (!smallImage) smallImage = myCaption.parentNode.querySelector('.image-item-2');
            var smallImageBottom = smallImage.offsetTop + smallImage.offsetHeight;
            var myLeft = Math.max(smallImage.offsetLeft, 20);

            // left setting
            myCaption.style.left = myLeft + 'px';
            myCaption.style.width = (smallImage.offsetWidth - (myLeft - smallImage.offsetLeft) * 2) + 'px';

            // force resizing
            myCaption.offsetHeight;

            // top setting
            myCaption.style.bottom = 'auto';
            myCaption.style.top = (
                smallImageBottom + myCaption.offsetHeight + 2 * maxCaptionImageTopDelta2 < slideHeight ?
                smallImageBottom + maxCaptionImageTopDelta2 :
                smallImageBottom + Math.floor((slideHeight - myCaption.offsetHeight - smallImageBottom) / 2)
            ) + 'px';

            myCaption.className += ' dynamically-sized';
            
        });
    });


    _each(document.querySelectorAll('.caption-bottom-right-corner'), function(myCaption) {

        // no JS for the build `2-1` of the slideshow
        if (document.body.className.match(/templated-slider-build-2-1/)) return;

        waitForAllImagesToLoad(myCaption.parentNode.getElementsByTagName('img'), function() {

            // get max image height
            var smallImage = myCaption.parentNode.querySelector('.image-item-3');
            if (!smallImage) smallImage = myCaption.parentNode.querySelector('.image-item-2');
            var smallImageBottom = smallImage.offsetTop + smallImage.offsetHeight;
            
            var imageRight = slideWidth - smallImage.offsetLeft - smallImage.offsetWidth;
            var myRight = Math.max(slideWidth - smallImage.offsetLeft - smallImage.offsetWidth, 20);

            // left setting
            // myCaption.style.left = smallImage.offsetLeft + Math.floor((myRight - imageRight) / 2) + 'px';
            if (!isRTL) {
                myCaption.style.right = imageRight + 'px';
            } else {
                myCaption.style.left = imageRight + 'px';
            }
            myCaption.style.width = (smallImage.offsetWidth - (myRight - imageRight)) + 'px';

            // force resizing
            myCaption.offsetHeight;

            // top setting
            myCaption.style.bottom = 'auto';
            myCaption.style.top = (
                smallImageBottom + myCaption.offsetHeight + 2 * maxCaptionImageTopDelta2 < slideHeight ?
                smallImageBottom + maxCaptionImageTopDelta2 :
                smallImageBottom + Math.floor((slideHeight - myCaption.offsetHeight - smallImageBottom) / 2)
            ) + 'px';

            myCaption.className += ' dynamically-sized';
            
        });
    });

    _each(document.querySelectorAll('.caption-center-left'), function(myCaption) {

        // no JS for the build `2-1` of the slideshow
        if (document.body.className.match(/templated-slider-build-2-1/)) return;

        waitForAllImagesToLoad(myCaption.parentNode.getElementsByTagName('img'), function() {

            // get max image left
            var image = myCaption.parentNode.querySelector('.image-item-1');
            var imageLeft = image.offsetLeft;
            if (isRTL) imageLeft += image.offsetWidth;

            // left setting
            if (!isRTL) {
                myCaption.style.left = 20 + 'px';
                myCaption.style.width = (imageLeft - 40) + 'px';
            } else {
                myCaption.style.right = 20 + 'px';
                myCaption.style.width = (slideWidth - imageLeft - 40) + 'px';
            }
            
            // force resizing
            myCaption.offsetHeight;

            // top setting
            myCaption.style.top = Math.floor((slideHeight - myCaption.offsetHeight) / 2) + 'px';
            myCaption.className += ' dynamically-sized';
            
        });
    });

    _each(document.querySelectorAll('.caption-center-right'), function(myCaption) {

        // no JS for the build `2-1` of the slideshow
        if (document.body.className.match(/templated-slider-build-2-1/)) return;
        
        waitForAllImagesToLoad(myCaption.parentNode.getElementsByTagName('img'), function() {

            // get max image left
            var image = myCaption.parentNode.querySelector('.image-item-1');
            var imageRight = image.offsetLeft + image.offsetWidth;
            if (isRTL) imageRight = image.offsetLeft;

            // left setting
            // myCaption.style.left = (imageRight + 20) + 'px';
            if (!isRTL) {
                myCaption.style.width = (slideWidth - imageRight - 40) + 'px';
                myCaption.style.right = '20px';
            } else {
                myCaption.style.width = (imageRight - 40) + 'px';
                myCaption.style.left = '20px';
            }

            // force resizing
            myCaption.offsetHeight;

            // top setting
            myCaption.style.top = Math.floor((slideHeight - myCaption.offsetHeight) / 2) + 'px';

            myCaption.className += ' dynamically-sized';
            
        });
    });
}

// wait for all the images to load (before manipulating positions)
function waitForAllImagesToLoad(imageArray, callback) {

    var num = imageArray.length;
    var waiter = _each(imageArray, function(myImage) {
        // FIXME does addEventListener work in IE8 ???
        if (isImageLoaded(myImage)) {
            if (--num == 0) {
                // HACK possibly we have a 'loading-image-hide' class on these images now,
                // in order to handle a funky resizing problem. Wait a bit to allow for
                // that to be removed - otherwise the size will return a 0
                setTimeout(function() {
                    callback();    
                }, 50);
            }
        } else {
            myImage.addEventListener('load', function() {
                if (--num == 0) {
                    // HACK possibly we have a 'loading-image-hide' class on these images now,
                    // in order to handle a funky resizing problem. Wait a bit to allow for
                    // that to be removed - otherwise the size will return a 0
                    setTimeout(function() {
                        callback();
                    }, 50);
                }
            });
        }

    });

}

function isImageLoaded(img) {
    return img.complete && typeof img.naturalWidth != 'undefined' && img.naturalWidth != 0;
}

if(window.localdev){

    $(document).ready(function() {
        $(window).on('load', function(){

            // return;
            if (window.deviceCustomType != 'desktop') return;

            if (!window.thisIsLegacySlideshow) console.warn('slide not set up for dynamic image sizing:');
            $('slide').each(function() {
                if ($(this).find('.image-holder').length == 0) {

                    // check to make sure that all images are exactly sized
                    $(this).find('img:not(.zoomer-image)').each(function() {
                        if (!$(this).attr('src')) $(this).attr('src', determineImageSources(this)[0]);
                    });


                    // var templ = this.className.match(/slide-template-new-[^ ]+/)
                    // if (!window.thisIsLegacySlideshow) console.debug('{ {define "' + templ + '"} }');

                    var myIdx = $('slide').index(this);
                    
                    var tempImgNum = 1;
                    $(this).find('img').each(function() {

                        if (!window.thisIsLegacySlideshow) {
                            console.debug('<div class="item image-item image-item-' + (tempImgNum++) + ' image-holder" data-width="' + $(this).width() + '" data-height="' + $(this).height() + '">');
                            $(this).css('outline', '2px solid green');
                        } else {

                            var $this = $(this);
                            setTimeout(function() {
                                console.debug('slide#' + (myIdx +1));
                                console.debug('{' + '{.LegacySlideWrap ' + $this.width() + ' ' + $this.height() + ' ' + tempImgNum + ' "');
                                tempImgNum++;
                                $this.css('outline', '2px solid green');
                            }, 2000);

                        }

                    });

                } else {

                    // check to make sure that all images are exactly sized
                    $(this).find('img:not(.zoomer-image)').each(function() {

                        // return;

                        if (!$(this).attr('src')) $(this).attr('src', determineImageSources(this)[0]);

                        var $this = $(this);
                        setTimeout(function() {
                            var currentHeight = $this.height();
                            var currentWidth = $this.width();
                            $("<img/>").attr("src", $this.attr('src')).load(function() {
                                if (this.width != currentWidth || this.height != currentHeight) {
                                    console.error('improperly sized: (' + this.width + 'x' + this.height + ') vs (' + currentWidth + 'x' + currentHeight + ')');
                                    $this.css('outline', '2px solid red');
                                    console.error($this[0]);
                                }
                            });
                        }, 4000);

                    });

                }
            });

        });

    });

// cropper scripts
new function() {

    if (!globalGetParams || !globalGetParams.crop) return;

    var globalCropperURL = 'http://f.edit.firechrome.org/tools/cropper/?q=/imagecache/';

    $(document).ready(function() {

        $('body').append('<div style="position: fixed; bottom: 10%; left: 0;"><span style="border-top-right-radius: 5px; border-bottom-right-radius: 5px; background-color: rgba(0, 0, 0, 0.5); border-left: 1px solid rgba(255, 255, 255, 0.1); font-size: 14px; padding: 15px; color: #fff; font-weight: bolder; text-decoration: none; font-family: sans-serif; display: inline-block; margin-top: 5px; z-index: 10000;">Ctrl+click image<br>to open cropper</span>');

        // collect up the real sizes for all images
        $('.slide-templated .image-item, slide img').each(function() {
            var $this = $(this);
            // get the real image dimensions
            // @from http://stackoverflow.com/questions/318630/get-real-image-width-and-height-with-javascript-in-safari-chrome
            var theSrc = $this.attr("src") ? $this.attr("src") : $this.attr("data-src");
            if (!theSrc) return;
            console.log('loading...');
            $("<img/>").attr("src", theSrc.replace(/\/imagecache\/[^\/]+\//, '/')).load(function() {
                console.log('loaded');
                $this.attr('data-real-width', this.width)
                    .attr('data-real-height', this.height);
            });
        });

        $(document).on('mousedown', '.slide-templated .image-item, slide img', function(e) {
            if (!e.ctrlKey) return true;
            e.preventDefault();
            e.stopPropagation();
            e.stopImmediatePropagation();

            var that = $(e.target);
            var src = that.attr('src');
            var attrs = {};

            var pres = src.match(/(cropfit[^/]*)\//);
            if (!pres) {

                // not cropfit, nuke any imagecache (as it's only resizing, not cropping)
                var widthSetting = src.match(/fit-[0-9]+/);
                if (widthSetting && widthSetting[0]) attrs.w = widthSetting[0].replace(/fit-/, '');

                var qaSetting = src.match(/qa=[0-9]+/);
                if (qaSetting && qaSetting[0]) attrs.qa = qaSetting[0].replace(/qa=/, '');
                
            } else {

                // parse the cropfit attrs
                var parts = pres[1].split('@');
                parts.forEach(function(v) {
                    if (!v.match(/=/)) return;
                    var vparts = v.split('=');
                    if (vparts.length != 2) return;
                    attrs[vparts[0]] = vparts[1];
                });

            }

            // if there's no crop specified, add a basic one
            if (!attrs.cr) {

                // attrs.cr = '0,0,' + that.attr('data-real-width') + ',' + that.attr('data-real-height');

                var ratios = _.reduce(that.attr('data-ratio').split(/x/), function(m, v) {
                    return m.concat([v]);
                }, []);
                attrs.cr = '0,0,' + ratios[0] + ',' + ratios[1];

            }

            if (!attrs.w) attrs.w = 1200;
            
            // console.log(pres);
            // console.log(attrs);
            var adjSrc = src.replace(/\/sites\/default\/files\/imagecache\/[^\/]+\//, '/data/www.scientology.org/files/').replace(/\/sites\/default\/files\//, '/data/www.scientology.org/files/').replace(/http.*firechrome.org.*\/data\/www.scientology.org\/files/, '/data/www.scientology.org/files/');
            var cropUrl = globalCropperURL + 'cropfit@' + Object.keys(attrs).reduce(function(m, k) { return m.concat([k + '=' + attrs[k]]); }, []).join('@') + adjSrc;

            window.open(cropUrl, '_blank');

            return false;
        });

    });

}


    // image aspect ratio measuring and correction script
    // localdev only

    var globalCropperURL = 'http://f.edit.firechrome.org/tools/cropper/?q=/imagecache/';

    // 'cropfit@h=1000@cr=1362,108,1149,1437/data/www.scientology.org/files/nn-2014/nn-latam-outside1-insert.jpg'

    $(document).ready(function() {

        if (globalGetParams.stretcher) {

            $('.slide-templated .image-item, slide img').each(function() {

                var $this = $(this);

                // get the real image dimensions
                // @from http://stackoverflow.com/questions/318630/get-real-image-width-and-height-with-javascript-in-safari-chrome
                $("<img/>").attr("src", ($this.attr("src") ? $this.attr("src") : $this.attr("data-src"))).load(function() {

                    var myWidth = this.width;
                    var myHeight = this.height;
                    var ratio = myHeight / myWidth;
                    var imgRatio = $this.height() / $this.width();

                    if (Math.abs(ratio - imgRatio) > 0.01) {
                        $this.css('outline', '10px solid red');
                        console.log('BAMMBOOO');
                    }

                });

            });

            return;

        }

        // only on "?debug=1"
        if (!globalGetParams.debug) return;

        $(window).on('load', function(){

            $(document).on('click', '.slide-templated .image-item[data-crop-link]', function(e) {
                e.preventDefault();
                e.stopPropagation();
                e.stopImmediatePropagation();
                window.open($(this).attr('data-crop-link'), 'cropper');
                return false;
            });


            // also for those not having data-ratio
            $('.slide-templated .image-item').each(function() {

                var $this = $(this).addClass('ignore-zoom');
                var origSrc = $this.attr('src') || $this.attr('data-src');

                if (!($this.attr('data-ratio'))) {

                    if (origSrc && origSrc.match(/.*cropfit.*/)) {
                        origSrc = origSrc.replace(/\/sites\/default\/files\/imagecache\/([^\/]+)/, function(a, b) {
                            return globalCropperURL + b + '/data/www.scientology.org/files';
                        });
                        $this.css('box-shadow', '-3px 0 green');
                    } else if (origSrc) {
                        origSrc = origSrc.replace(/\/sites\/default\/files\//, function(a, b) {
                            return globalCropperURL + b + '/data/www.scientology.org/files';
                        });
                    }
                    $this.attr('data-crop-link', origSrc);
                    return;
                }

                // get the real image dimensions
                // @from http://stackoverflow.com/questions/318630/get-real-image-width-and-height-with-javascript-in-safari-chrome
                $("<img/>").attr("src", ($this.attr("src") ? $this.attr("src") : $this.attr("data-src"))).load(function() {

                    var myWidth = this.width;
                    var myHeight = this.height;

                    var myRatio = $this.attr('data-ratio');

                    // turn the ratio into a number
                    myRatio = _.reduce(myRatio.split(/x/), function(m, v) {
                        if (m == 1) return m * v;
                        return m / v;
                    }, 1);

                    var deltaY = myHeight - Math.round(myWidth / myRatio);
                    var deltaX = myWidth - Math.round(myHeight * myRatio);
                    if (Math.abs(deltaY) < 3) {

                        if (origSrc.match(/.*cropfit.*/)) {
                            origSrc = origSrc.replace(/\/sites\/default\/files\/imagecache\/([^\/]+)/, function(a, b) {
                                return globalCropperURL + b + '/data/www.scientology.org/files';
                            });
                            $this.css('box-shadow', '-3px 0 green');
                        } else {
                            origSrc = origSrc.replace(/\/sites\/default\/files\//, function(a, b) {
                                return globalCropperURL + b + '/data/www.scientology.org/files';
                            });
                        }
                        $this.attr('data-crop-link', origSrc);
                        return;
                    }

                    
                    var origCrop = '';
                    if (origSrc.match(/.*cropfit.*/)) {

                        origSrc = origSrc.replace(/\/sites\/default\/files\/imagecache\/([^\/]+)/, function(a, b) {
                            // console.log(arguments);
                            origCrop = b;
                            var cropParts = origCrop.split(',');
                            console.log(cropParts);
                            if (cropParts.length != 4) console.error('unexpected crop - please adjust regexp: ' + origCrop);
                            b = cropParts[0] + ',' + cropParts[1] + ',' + cropParts[2] + ',';

                            var currentHeight = parseInt(cropParts[3]);
                            var zoomed = currentHeight / myHeight;
                            var newHeight = (myHeight - deltaY) * zoomed;
                            b += newHeight;
                            return globalCropperURL + b + '/data/www.scientology.org/files';
                        });
                        $this.attr('data-crop-link', origSrc);
                        // origSrc = origSrc.replace(/^.*imagecache\/cropfit/, '');

                    }

                   

                    if (deltaY > 0) {
                        // to tall - cut it off

                        $this.css('max-height', ($this.height() / 575 * 100) + '%').css('border-bottom', Math.floor(deltaY * 575 / myHeight) + 'px solid blue');
                    } else {
                        // not tall enough - extend it
                        $this.css('box-shadow', '0 -' + Math.floor(-deltaY * 575 / myHeight) + 'px 0 red');
                    }

                    // $this.css('outline', Math.min(20, Math.floor((deltaY / myHeight * 100) + 2)) + 'px solid red');

                    return;



                });



                
            });

        });

    });

    // output final caption positions - useful if these need to be hardcoded
    $(document).ready(function() {

        return;

        $(window).on('load', function(){
            setTimeout(function() {
                var current_text_pos = '';

                $('slide .text-item').each(function() {

                    var parent_slide = $(this).parents('slide');
                    parent_slide = parent_slide.attr('class').replace(/^.*[ ]*slide-id-/, 'slide-id-').replace(/ .*$/, '');

                    var stil = $(this).attr('style');

                    if (!stil) {
                        stil = 'width: ' + Math.round($(this).width()) + 'px; top: ' + Math.round($(this).position().top) + 'px; left: ' + Math.round($(this).position().left) + 'px;';
                        // return console.error('no style for text: ' + parent_slide);
                    }

                    stil = stil.replace(/opacity: [0-9\.]+;/, '').replace(/transform[^;]+;/, '')
                        .replace(/transition[^;]+;/, '').replace(/-webkit-transition[^;]+;/, '');
                    stil = '    ' + stil.replace(/[ ]*;[ ]*/g, ' !important;\n    ');

                    stil = stil.replace(/width:[ ]*([0-9]+)px/, function(a, b) {
                        return 'width: {' + '{CSSPercentX ' + b + '}' + '}%';
                    });
                    stil = stil.replace(/left:[ ]*([0-9]+)px/, function(a, b) {
                        return 'left: {' + '{CSSPercentX ' + b + '}' + '}%';
                    });
                    stil = stil.replace(/right:[ ]*([0-9]+)px/, function(a, b) {
                        return 'right: {' + '{CSSPercentX ' + b + '}' + '}%';
                    });

                    stil = stil.replace(/top:[ ]*([0-9]+)px/, function(a, b) {
                        return 'top: {' + '{CSSPercentY ' + b + '}' + '}%';
                    });
                    stil = stil.replace(/height:[ ]*([0-9]+)px/, function(a, b) {
                        return 'height: {' + '{CSSPercentY ' + b + '}' + '}%';
                    });
                    stil = stil.replace(/bottom:[ ]*([0-9]+)px/, function(a, b) {
                        return 'bottom: {' + '{CSSPercentY ' + b + '}' + '}%';
                    });

                    current_text_pos += '.' + parent_slide + ' .text-item {\n' + stil + '\n}\n';

                });

                // this is needed, pls don't remove it - notice that it's localdev only - AT
                console.log(current_text_pos);
            }, 10000);
        });
    });

}



// Automatically wire up block-hover elements

var tempReposlideHeight;

$(document).ready(function() {

	tempReposlideHeight = $('#header_slideshow_wraper').height();

	// click on the first link on block-hover elements
	$('.blocked-hover:not(.blocked-hover-ignore-clicks)').on('click', function(e) {
		// let links through
		for (var el = e.target; el.parentElement; el = el.parentElement) {
			if (el.tagName == 'A') return;
		}

		var firstLink = $(this).find('a').get(0);
		if (firstLink.click) {
			firstLink.click();
		} else if (document.createEvent) {
			// fallback for Safari
			var eventObj = document.createEvent('MouseEvents');
			eventObj.initEvent('click', true, true);
			firstLink.dispatchEvent(eventObj);
		}
	});

	
	if (
        	document.body.className.match(/templated-slider-build-2-1/) && 
        	(window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth) > 767 &&
        	(
                (window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth) < 1025 ||
                !document.body.className.match(/locale-en/) || document.body.className.match(/bio-legacy-page/)
            ) &&
        	window.slideshowCaptionsOverflow
   	   ) {

   // 	   	$(window).on('load', function(){
   // 	   		tempReposlideHeight = $('#header_slideshow_wraper').height();
			// slideshowCaptionsOverflow();
   // 	   	});

		// de-bounce this to happen 0.2s after the resize ended
		var slideDebouncer = 0;
		$(window).on('resize', function() {
			if (slideDebouncer > 0) clearTimeout(slideDebouncer);
			slideDebouncer = setTimeout(function() {
				tempReposlideHeight = $('#header_slideshow_wraper').height();
				slideshowCaptionsOverflow();
				slideDebouncer = 0;
			}, 200);
		});

	}

	$('.embed__org-tour').each(function() {
		var $this = $(this);
		$this.html( $('.press-release-tour-inline-wrapper')[0].outerHTML );
		if(!gscSlideshowCanZoomIn()) {
			$this.find('.press-release-tour-inline-wrapper').replaceWith(function() {
				return $('<a/>', {
					href: $(this).attr('href'),
					html: $(this).html(),
					class: $(this).attr('class'),
					target: '_blank',
				});
			});
		}
	});


	_.each($('.body--videoid[data-videosrc]'), function (el, index) {
		$(el).addClass('video-inline-wrapper');
		$(el).html('<span class="icon-controller-play magazine-video-item-play"></span><video class="video-js vjs-default-skin video-inline-element" preload="none" playsinline></video>');
	});

	_.each($('.video-inline-wrapper'), function (el, index) {
		var $el = $(el);

		if($el.closest('.magazine-toc-menu').length > 0) {
			$el.addClass('video-play-element');
			return;
		}

		var options = jQuery.extend({}, videoOptions);
		options.preload = "none";
		options.autoplay = false;
		options.sources = $el.data('videosrc');
		options.poster = $el.data('videoposter');
		options.controls = true;
		var videos = $el.find('.video-js');
		if (videos.length == 0) {
			var srcset = $el.find('.image img').attr('data-srcset').split(' ');
			if(srcset.length > 0) {
				options.poster = srcset[0];
			}
			$el.find('.image').html('<div class="relative"><span class="icon-controller-play magazine-video-item-play"></span><video class="video-js vjs-default-skin video-inline-element" preload="none" playsinline></video></div>');
			videos = $el.find('.video-js');
		}
		
		videojs(videos[0], options).ready(function() {
			EventTracker.trackVideo(this);
			this.on('play', function() {
				$(el).addClass('video-inline-wrapper__playing');
			});
		});

	});

	$('.press-release-video-title').each(function() {
		var $this = $(this);
		var $video = $this.next('.video-inline-wrapper');
		// insert
		$this.appendTo($video);
		// delete
		// $this.remove();
	});
/*
	// hook listers to the blue strips for the link to the 4D section of Ireland
	{{with $link := .SiteData.Resolve "/"}}

		el = '.templated-slider-slideset-ireland-national-office-tour-inside slide[data-template="slide_template_c-1-with-band"].slide-id-slide-19';
		$(el).html('<a class="ignore-zoom" href="{{($link.WithLocale "en_IE").WithPath "/national-office/drug-free-world/"}}">'  + $(el).html() + '</a>');

		el = '.templated-slider-slideset-ireland-national-office-tour-inside slide[data-template="slide_template_c-1-with-band"].slide-id-slide-20';
		$(el).html('<a class="ignore-zoom" href="{{($link.WithLocale "en_IE").WithPath "/national-office/human-rights/"}}">'  + $(el).html() + '</a>');

		el = '.templated-slider-slideset-ireland-national-office-tour-inside slide[data-template="slide_template_c-1-with-band"].slide-id-slide-21';
		$(el).html('<a class="ignore-zoom" href="{{($link.WithLocale "en_IE").WithPath "/national-office/way-to-happiness/"}}">'  + $(el).html() + '</a>');

		el = '.templated-slider-slideset-ireland-national-office-tour-inside slide[data-template="slide_template_c-1-with-band"].slide-id-slide-22';
		$(el).html('<a class="ignore-zoom" href="{{($link.WithLocale "en_IE").WithPath "/national-office/volunteer-ministers/"}}">'  + $(el).html() + '</a>');

		el = '.templated-slider-slideset-ireland-national-office-tour-inside slide[data-template="slide_template_c-1-with-band"].slide-id-slide-23';
		$(el).html('<a class="ignore-zoom" href="{{($link.WithLocale "en_IE").WithPath "/national-office/narconon/"}}">'  + $(el).html() + '</a>');

		el = '.templated-slider-slideset-ireland-national-office-tour-inside slide[data-template="slide_template_c-1-with-band"].slide-id-slide-24';
		$(el).html('<a class="ignore-zoom" href="{{($link.WithLocale "en_IE").WithPath "/national-office/national-affairs-office-dc.html"}}">'  + $(el).html() + '</a>');

	{{end}}
*/

});

// Listen for orientation changes
if (
        document.body.className.match(/templated-slider-build-2-1/) && 
    	(window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth) > 767 &&
    	(
            (window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth) < 1025 ||
            !document.body.className.match(/locale-en/)
        ) &&
    	window.slideshowCaptionsOverflow
   ) {
	window.addEventListener && window.addEventListener("orientationchange", function() {
		tempReposlideHeight = $('#header_slideshow_wraper').height();
		slideshowCaptionsOverflow();
	}, false);
}

document.addEventListener && document.addEventListener('click', function(e) {
    if (e && e.target && (
            (e.target.className && e.target.className.match(/slider-captions-more/)) ||
            $(e.target).parents('.slider-captions-more').length ||
            $(e.target).parents('.slider-captions-more-full').length
        )) {
		e.preventDefault();
		e.stopPropagation();
		e.stopImmediatePropagation();

		var id = $(e.target).attr('data-id');
		if(!id) {
			id = $(e.target).parents('.slider-captions-more-full').attr('data-id');
		}

		$('.slider-captions-more-full[data-id="' + id + '"]').toggleClass('show-full');

		if($('.slider-captions-more-full[data-id="' + id + '"]').hasClass('show-full')) {
			$(e.target).parents('slide').find('.text-item').hide();
		} else {
			$(e.target).parents('slide').find('.text-item').show();
		}

		// $(e.target).parents('slide').toggleClass('show-full');

		// if($(e.target).parents('slide').hasClass('show-full')) {
		// 	$(e.target).parents('slide').find('.text-item').hide();
		// } else {
		// 	$(e.target).parents('slide').find('.text-item').show();
		// }

		return false;
	}
}, true);

if (/Window/.test(navigator.userAgent)) {
	$('html').addClass('windows');
}


function updateTVRelatedBlock(url, source) {
	// Only english
	if($('html').attr('lang') != "en") {
		return;
	}

	if(window.location.pathname.indexOf('/videos/dianetics/') > -1) {
		url = 'https://www.scientology.tv/films-on-scientology-principles/dianetics-introduction.html';
	}

	if(window.location.pathname.indexOf('/videos/beliefs-and-practices/basic-principles/') > -1) {
		url = 'https://www.scientology.tv/films-on-scientology-principles/principles-of-scientology.html';
	}

	if(!url) {
		$('.related-from-scn-network').addClass('hidden');

		if(window.location.pathname.indexOf('/meet-a-scientologist/') > -1) {
			url = 'https://www.scientology.tv/series/meet-a-scientologist/';
		} else if(window.location.pathname.indexOf("/videos/the-way-to-happiness/") > -1 ||
				  window.location.pathname.indexOf("/videos/applied-scholastics/") > -1 ||
				  window.location.pathname.indexOf("/videos/criminon-introduction/") > -1 ||
				  window.location.pathname.indexOf("/videos/narconon/") > -1 ||
				  window.location.pathname.indexOf("/videos/truth-about-drugs/") > -1 ||
				  window.location.pathname.indexOf("/videos/anti-drug/") > -1 ||
				  window.location.pathname.indexOf("/videos/citizens-commission-on-human-rights/") > -1 ||
				  window.location.pathname.indexOf("/videos/human-rights/") > -1) {
			url = 'https://www.scientology.tv/series/voices-for-humanity/';
		} else if(window.location.pathname.indexOf("/videos/churches/new-churches-of-scientology/") > -1) {
			url = 'https://www.scientology.tv/series/destination-scientology/';
		}

		if(!url) {
			return;
		}
	}

	$('.video-next').append($('.scn-network-series-banner--wrapper').clone());
	$('.video-next .scn-network-series-banner--wrapper').removeClass('hidden');
	$('.scn-network-series-banner').addClass('hidden');

	$('#video-details').append($('.related-from-scn-network').clone());
	$('#video-details .related-from-scn-network').removeClass('hidden');

	$.ajax({
		url: url,
		type: 'GET',
		dataType: 'text',
	})
	.done(function(data) {
		data = '<div>' + data + '</div>';
		_.each($(data).find('script[type="application/ld+json"]'), function(el){
		
			var jsonld = JSON.parse(el.innerText);
			
			if(jsonld["@type"] == "TVSeries" || jsonld["@type"] == "TVEpisode") {

				url += "?utm_source=";
				if(source) {
					url += source;
				} else {
					url += 'scn-video-channel';
				}

				var name = jsonld["name"];
				var description = jsonld["description"];
				var image = jsonld["image"][0];
				if(image == "") {
					image = $(data).find('meta[property="og:image"]').attr('content');
				}

				if(image.indexOf('@w=1280') > -1) {
					image = image.replace('@w=1280', '@w=333');
				} else {
					image = image.replace('/imagecache/cropfit', '/imagecache/cropfit@w=333');
				}

				var season = "";
				var episode = "";
				var series = "";

				if(jsonld["partOfSeason"] && jsonld["partOfSeason"].seasonNumber) {
					season = jsonld["partOfSeason"].seasonNumber;
				}
				if(jsonld["episodeNumber"]) {
					episode = jsonld["episodeNumber"];
				}
				if(jsonld["partOfSeries"] && jsonld["partOfSeries"]["name"]) {
					series = jsonld["partOfSeries"]["name"];
				} else {
					$('#video-details .scnnetwork-series-name').remove();
				}

				// HACK, fix typo
				if(description.trim() == 'gcui_scntv:films_principles-of-scientology_blurp') {
					description = 'Practiced the world over, Scientology is first and foremost a practical religion that helps provide answers and solutions to real life problems. ';
				}

				$('.related-from-scn-network .thumbnail').attr('src', image);
				$('.scnnetwork-episode-title a').attr('href', url);
				$('.related-from-scn-network .video-thumb').attr('href', url);

				$('.scnnetwork-episode-title a').html(name);
				$('.scnnetwork-series-name').html(series);
				$('.related-from-scn-network .scnnetwork-blurb').html(description);
				$('.related-from-scn-network .watch-link').attr('href', url);

				if(episode != "" && season != "") {
					$('.related-from-scn-network .scnnetwork-episodeNumber').html(episode);
					$('.related-from-scn-network .scnnetwork-seasonNumber').html(season);
				} else {
					$('.related-from-scn-network .scnnetwork-season-episode').hide();
				}

				
				if(url.indexOf('/meet-a-scientologist/') > -1) {
					$('.scn-network-series-banner[data-series=meet-a-scientologist]').removeClass('hidden');
				} else if(url.indexOf('/voices-for-humanity/') > -1) {
					$('.scn-network-series-banner[data-series=voices-for-humanity]').removeClass('hidden');
				} else if(url.indexOf('/inside-scientology/') > -1) {
					$('.scn-network-series-banner[data-series=inside-scientology]').removeClass('hidden');
				} else if(url.indexOf('/destination-scientology/') > -1 || window.location.pathname.indexOf("/videos/churches/new-churches-of-scientology/") > -1) {
					$('.scn-network-series-banner[data-series=destination-scientology]').removeClass('hidden');
				} else if(url.indexOf('/l-ron-hubbard-in-his-own-voice/') > -1) {
					$('.scn-network-series-banner[data-series=l-ron-hubbard-in-his-own-voice]').removeClass('hidden');
				}
			}
		
		});
	})
	.fail(function() {
		console.error("error");
	});
	
}

$(document).ready(function($) {
	var $el = $('.related-from-scn-network[data-episode-url]');
	if($el.length > 0) {
		updateTVRelatedBlock($el.attr('data-episode-url'), 'scn-churches-section');
		if($el.attr('data-episode-url').length > 0) {
			$('.related-from-scn-network').removeClass('hidden');
		}
	}
});

window.lazySizesConfig = window.lazySizesConfig || {};
lazySizesConfig.preloadAfterLoad = true;
lazySizesConfig.loadMode = 1;


function initComparison() {
    var dragging = false,
        scrolling = false,
        resizing = false;
    //cache jQuery objects
    var imageComparisonContainers = $('.cd-image-container:not(.cd-image-container__inited)');

    if(imageComparisonContainers.length == 0) {
        return;
    }

    $('.slider-switch').change(function() {
        var $wrapper = $(this).closest('.cd-image-wrapper');
        var $container = $wrapper.find('.cd-image-container');
        // determine the target state class based on the switch value:
        if(this.checked) {
            $container.addClass('cd-image-container__secondary');
        } else {
            $container.removeClass('cd-image-container__secondary');
        }
    });

    //check if the .cd-image-container is in the viewport
    //if yes, animate it
    for (var index = 0; index < imageComparisonContainers.length; index++) {
        var container = imageComparisonContainers[index];
        checkPosition(container);
        $(container).addClass('cd-image-container__inited');
    }
    // checkPosition(imageComparisonContainers);
    // $(window).on('scroll', function(){
    //     if( !scrolling) {
    //         scrolling =  true;
    //         ( !window.requestAnimationFrame )
    //             ? setTimeout(function(){checkPosition(imageComparisonContainers);}, 100)
    //             : requestAnimationFrame(function(){checkPosition(imageComparisonContainers);});
    //     }
    // });

    //make the .cd-handle element draggable and modify .cd-resize-img width according to its position
    imageComparisonContainers.each(function(){
        var actual = $(this);
        drags(actual.find('.cd-handle'), actual.find('.cd-resize-img'), actual, actual.find('.cd-image-label[data-type="original"]'), actual.find('.cd-image-label[data-type="modified"]'));
    });

    //upadate images label visibility
    $(window).on('resize', function(){
        if( !resizing) {
            resizing =  true;
            ( !window.requestAnimationFrame )
                ? setTimeout(function(){checkLabel(imageComparisonContainers);}, 100)
                : requestAnimationFrame(function(){checkLabel(imageComparisonContainers);});
        }
    });

    function checkPosition(container) {
        var actualContainer = $(container);
        $(container).click(function(){
            actualContainer.addClass('is-visible');
        });
        if($(container).next().hasClass('image-compare-caption')) {
            $(container).next().click(function(){
                actualContainer.addClass('is-visible');
            });
        }
        // container.each(function(){
        //     var actualContainer = $(this);
        //     if( $(window).scrollTop() + $(window).height()*0.5 > actualContainer.offset().top) {
        //         actualContainer.addClass('is-visible');
        //     }
        // });

        scrolling = false;
    }

    function checkLabel(container) {
        container.each(function(){
            var actual = $(this);
            updateLabel(actual.find('.cd-image-label[data-type="modified"]'), actual.find('.cd-resize-img'), 'left');
            updateLabel(actual.find('.cd-image-label[data-type="original"]'), actual.find('.cd-resize-img'), 'right');
        });

        resizing = false;
    }


    //draggable funtionality - credits to http://css-tricks.com/snippets/jquery/draggable-without-jquery-ui/
    function drags(dragElement, resizeElement, container, labelContainer, labelResizeElement) {
        dragElement.on("mousedown vmousedown touchstart", function(e) {
            e.stopPropagation();
            e.preventDefault();
            e.stopImmediatePropagation();

            dragElement.addClass('draggable');
            resizeElement.addClass('resizable');
            var containerRect = container[0].getBoundingClientRect();
            var handleWidth   = dragElement.outerWidth();               // ← capture handle width
            e.preventDefault();
            $(window).on("mousemove.vm touchmove.vm", function moveHandler(ev) {
                if (!dragging) {
                    dragging = true;
                    requestAnimationFrame(function() {
                        animateDraggedHandle(
                            ev, 
                            containerRect, 
                            resizeElement, 
                            labelContainer, 
                            labelResizeElement,
                            handleWidth                                   // ← pass it along
                        );
                    });
                }
            }).on("mouseup.vm touchend.vm", function upHandler(e) {
                e.stopPropagation();
                e.preventDefault();
                e.stopImmediatePropagation();
                
                dragElement.removeClass('draggable');
                resizeElement.removeClass('resizable');
                dragging = false;
                $(window).off(".vm");
            });
        });
    }

    function animateDraggedHandle(e, containerRect, resizeElement, labelContainer, labelResizeElement, handleWidth) {
        // use clientX for viewport coords
        var clientX = e.clientX || (e.changedTouches && e.changedTouches[0].clientX),
            relX    = clientX - containerRect.left,
            // clamp so handle never goes closer than half its width to edges:
            minOffset = handleWidth / 2,
            maxOffset = containerRect.width - handleWidth / 2;

        relX = Math.max(minOffset, Math.min(maxOffset, relX));

        var pct = (relX / containerRect.width) * 100 + '%';

        $('.draggable').css('left', pct);
        $('.resizable').css('width', pct);

        updateLabel(labelResizeElement, resizeElement, 'left');
        updateLabel(labelContainer, resizeElement, 'right');
        dragging = false;
    }

    // replace updateLabel entirely:
    function updateLabel(label, resizeElement, position) {
        if (!label.length) return;

        // use boundingClientRect so transforms are accounted for
        var labelRect  = label[0].getBoundingClientRect(),
            resizeRect = resizeElement[0].getBoundingClientRect();

        if (position === 'left') {
            (labelRect.left >  resizeRect.left + resizeRect.width)
                ? label.removeClass('is-hidden')
                : label.addClass('is-hidden');
        } else {
            (labelRect.left + labelRect.width < resizeRect.left + resizeRect.width)
                ? label.removeClass('is-hidden')
                : label.addClass('is-hidden');
        }
    }
}
/**
@file
Generic JS util functions useful for the responsive slideshow.
No dependencies.
Should be included after the slideshow DOM, as early as possible.
*/

if (!window.responsiveSliderDetermineFirstSlide) {

    // this is needed (ideally) before document.ready for optimimum performance (so the first image in
    // the slideshow is never delayed)
    function responsiveSliderDetermineFirstSlide() {

        if (window.globalSlideshowOptionsOverride && globalSlideshowOptionsOverride.startSlide) {
            return globalSlideshowOptionsOverride.startSlide;
        }

        // don't have jQuery yet, so skip this for older browsers
        if (!document.querySelectorAll || !Array.prototype.reduce) return;

        // if there's a video tag matching a video in a slide (?video=...), use that
        if (globalGetParams.video || globalGetParams['video-play']) {

            var videoParam = globalGetParams.video || globalGetParams['video-play'];
            var mySlides = document.querySelectorAll('#header .slideshow-main slide');
            var slideMatching = Array.prototype.reduce.call(
                document.querySelectorAll('#header .slideshow-main slide .video-js'),
                function(m, v) {
                    if (m != null) return m;
                    var parentSlide = window._getParentForType && _getParentForType(v, 'SLIDE');
                    for (var i = 0; i < mySlides.length; i++) {
                        if (mySlides[i] == parentSlide) {
                            if (_getVideoIdForSlide(mySlides, i) == videoParam) return i;
                            break;
                        }
                    }
                },
                null
            );

            if (slideMatching !== void 0) return parseInt(slideMatching) + 1;

            // if there was a slide=... query param use that
            if (globalGetParams.slide) return globalGetParams.slide;

            // otherwise, let it play on first slide
            return 1;

        }

        if (location.hash) {
            var newSlideIdx = parseInt(location.hash.substring(1).replace(/slide/, '')) - 1;
            if (!isNaN(newSlideIdx) && newSlideIdx >= 0 && newSlideIdx <= document.querySelectorAll('#header slide').length - 1) {
                return newSlideIdx + 1;
        }
        }

        // otherwise, start at the beginning
        return 1;

    }

}

function cropImageW(imageDom, width) {
    if (!imageDom || !imageDom.getAttribute || !imageDom.getAttribute('data-src')) {
        window.console && console.error && console.error('cannot get image source, no data-src specified:');
        window.console && console.error && console.error(imageDom);
        return;
    }

    var imgSrc = imageDom.getAttribute('data-src');
    return cropImageSrcW(imgSrc, width);
}

if (!window._slideToSlideId) {

    // simply slide the slideshow div to the right position (visual hack)
    function _slideToSlideId(slidesIdx) {
        var deltaX = (isRTL ? -1 : 1) * (slidesIdx-1) * 100;
        var slideHolder = document.querySelector('#header .slideshow-main .slide-holder');
        if (!slideHolder) return;
        setTransform(slideHolder, 'translate3d(calc(' + (-deltaX) + '% - ' + (deltaX / 2) + 'px), 0, 0)');
    }

}

if (!window.setTransform) {

    // Tone 40 set a transform with vanilla JS
    // @from http://www.andismith.com/blog/2012/02/modernizr-prefixed/
    function setTransform(elem, transform) {
        elem.style.MozTransform = transform; /* Firefox */
        elem.style.msTransform = transform; /* IE (9+) - note ms is lowercase */
        elem.style.OTransform = transform; /* Opera */
        elem.style.WebkitTransform = transform; /* Safari and Chrome */
        elem.style.transform = transform; /* One day, ... */
    }

}

// add/remove a class and max-height to captions. Gets call on init and on window resize
function slideshowCaptionsOverflow() {
    // don't need this on authoring
    if (document.body.className.match(/authoring-true/)) return;

    // TODO maybe review this for initial display of captions
    // if (window.deviceCustomType != 'desktop') return;

    var standardTemplates = document.body.classList.contains('templated-slider-style-standard-templates');
    var slideHeight = document.querySelector('.slide-stretcher').offsetHeight;

    var moreButtonCounter = 0;

    [].forEach.call(document.querySelectorAll('#header_slideshow_wraper .text-item'), function(v) {

        if (v.className.match(/caption-overflow-adjusted/)) {
            v.classList.remove('caption-overflow-adjusted');
            var full = v.parentNode.querySelector('.slider-captions-more-full');

            if (full) {
                v.innerHTML = full.innerHTML;
                $(full).parent('slide').find('.text-item').show();
                full.parentNode.removeChild(full);
                // force re-layout
                // v.offsetTop;
            }
        }

        if(v.className.match(/overlay-item/) && !v.className.match(/overlay-item--bar/)  ) {
            return;
        }

        var captionOverflown = false;
        // affect only new templates and dont touch old ones because they work already well
        if(standardTemplates) {
            captionOverflown = v.offsetTop + v.scrollHeight > slideHeight;
        }

        if (v.offsetHeight < v.scrollHeight || captionOverflown) {

            var origCont = v.innerHTML,
                tempSlideCaptionAdjusted= false;

            for (var infiniteGuard = 200; infiniteGuard > 0; infiniteGuard--) {

                // take out the last word, then measure again
                // because they want space before the dots
                if(locale == "sv" || locale == "da" || locale == "no") {
                    var cont = v.innerHTML.replace(new RegExp(' ... <a[^>]*>' + (window.moreTexti18n ? moreTexti18n : 'more') + ' »<.a>.*$'), '');
                } else {
                    var cont = v.innerHTML.replace(new RegExp('... <a[^>]*>' + (window.moreTexti18n ? moreTexti18n : 'more') + ' »<.a>.*$'), '');
                }

                // clean out any `&nbsp;` or such at the end
                cont = cont.replace(/&[a-z]+;$/, '');

                // , cont.lastIndexOf(';')
                var lastDivider = Math.max(cont.lastIndexOf(' '), cont.lastIndexOf('.'), cont.lastIndexOf(','), cont.lastIndexOf('。'), cont.lastIndexOf('、'), cont.lastIndexOf('・'));

                if (lastDivider < 1) {
                    // we have failed - back out
                    window.console && console.error && console.error('could not break this string: ' + origCont);
                    v.innerHTML = origCont;
                    break;
                }

                var newCont = cont.substring(0, lastDivider);

                // "normalize" this
                var tempElem = document.createElement('DIV');
                tempElem.innerHTML = newCont;
                newCont = tempElem.innerHTML;

                if (cont == newCont) {
                    window.console && console.error && console.error('no change:');
                    window.console && console.error && console.error(cont);
                    window.console && console.error && console.error(newCont);
                    break;
                }

                moreButtonCounter ++ ;

                var moreText = '... <a data-id='+moreButtonCounter+' href="#" class="slider-captions-more">' + (window.moreTexti18n ? moreTexti18n : 'more') + ' »</a>';
                // because they want space before the dots
                if(locale == "sv" || locale == "da" || locale == "no") {
                    moreText = " " + moreText;
                }

                if(v.querySelector('.floater-texter')) {
                    var newEl = $(newCont);
                    v.innerHTML = newEl[0].innerHTML + moreText;
                } else {
                    v.innerHTML = newCont + moreText;
                }


                if(standardTemplates) {
                    captionOverflown = v.offsetTop + v.scrollHeight > slideHeight;
                }

                // force re-layout
                // v.offsetTop;
                if (v.offsetHeight >= v.scrollHeight && !captionOverflown) {
                    v.classList.add('caption-overflow-adjusted');

                    v.insertAdjacentHTML('afterend', '<span data-id='+moreButtonCounter+' class="slider-captions-more-full ignore-zoom item">' + origCont + '<div class="close-full-caption">'+closeTexti18n+'<span class="glyphicon glyphicon-remove-circle"></span></div></span>');
                    tempSlideCaptionAdjusted = true;

                    break;
                }

            };

            if (!tempSlideCaptionAdjusted)
                window.console && console.error && console.error('could not break this string: ' + origCont);

        }

    });
}

// determine an image's actual sizes (normal and scaled-up) based on
// A. image's natural size (as from `data-height` and `data-width` attrs),
// B. device pixel density,
// C. screen size
// D. pre-determined breakpoints established.

/**

Slide overall sizes based on viewport width:

992+      - full (860x575)
769 - 991 - tablet (680x454)
-768      - mobile, fluid width

===

"Desktop": at least one dimension > 1024

# Desktop, non-retina

NORMAL: 860x575
HIGHREZ: 2 * NORMAL

# Desktop, retina

NORMAL=HIGHREZ: (860x575) * (pixel density rounded to 1.5 or 2)

===

"Tablet": not desktop and not mobile

# Tablet

NORMAL: (860x575) * (pixel density rounded to 1, 1.5 or 2)
HIGHREZ: (860x575) * (pixel density rounded to 1.5 or 2)

===

"Mobile": both dimensions < 768

NORMAL: 360x240
HIGHREZ: (680x454)  * (pixel density rounded to 1, 1.5 or 2)

*/

/**

ACTUAL IMAGE SIZES THAT ARE USED

* width = [original width]
* width = Math.round([original width] * 1.5)
* width = [original width] * 2
* width = Math.round([original width] / 860 * 680)
* width = Math.round([original width] / 860 * 680 * 1.5)
* width = Math.round([original width] / 860 * 680 * 2)

*/

// we're only figuring these out once - these won't change

// device pixel ratio rounded to 1, 1.5 or 2
var effectivePixelRatio = 1;
if (window.devicePixelRatio) {
    if (window.devicePixelRatio > 1.0 && window.devicePixelRatio <= 1.5) {
        effectivePixelRatio = 1.5;
    } else if (window.devicePixelRatio > 1.5) {
        // we are not taking pixel ratio 3 or above (though iPhone 6+ has that)
        effectivePixelRatio = 2;
    }
}

// can be `desktop`, `tablet` or `mobile`
var deviceCustomType = 'tablet';
if (screen.height > 1024 || screen.width > 1024 || /Trident/.test(navigator.userAgent))  {
    deviceCustomType = 'desktop';
} else if (screen.height < 768 && screen.width < 768) {
    deviceCustomType = 'mobile';
}

if (document.documentElement) document.documentElement.className += ' device-custom-type-' + deviceCustomType;

// @ref https://github.com/phonegap/phonegap/wiki/App-Splash-Screen-Sizes
function determineImageSize(imageDom) {

    if (!imageDom.getAttribute('data-height')) {
        if(window.location.pathname == "/") {
            return [[800, 450], [2*800, 2*450]];
        }

        window.console && console.error && console.error('no data-height specified:');
        window.console && console.error && console.error(imageDom && imageDom.outerHTML);

        // return a sensible default (this is an error condition)
        return [[860, 575], [2*860, 2*575]];
    }

    var imageRelativeDims = [parseInt(imageDom.getAttribute('data-width')) / 860, parseInt(imageDom.getAttribute('data-height')) / 575];

    // regular "desktop"
    if (deviceCustomType == 'desktop' && effectivePixelRatio == 1) {
        return [
            [Math.round(imageRelativeDims[0] * 860), Math.round(imageRelativeDims[1] * 575)],
            // HACK for now - don't zoom
            // [Math.round(imageRelativeDims[0] * 860 * 2), Math.round(imageRelativeDims[1] * 575 * 2)]
            [Math.round(imageRelativeDims[0] * 860), Math.round(imageRelativeDims[1] * 575)]
        ];
    }

    // retina "desktop"
    if (deviceCustomType == 'desktop') {
        return [
            [Math.round(imageRelativeDims[0] * 860 * effectivePixelRatio), Math.round(imageRelativeDims[1] * 575 * effectivePixelRatio)],
            [Math.round(imageRelativeDims[0] * 860 * effectivePixelRatio), Math.round(imageRelativeDims[1] * 575 * effectivePixelRatio)]
        ];
    }

    // "tablet"
    if (deviceCustomType == 'tablet') {
        return [
            [Math.round(imageRelativeDims[0] * 860 * effectivePixelRatio), Math.round(imageRelativeDims[1] * 575 * effectivePixelRatio)],
            [Math.round(imageRelativeDims[0] * 860 * Math.max(1.5, effectivePixelRatio)), Math.round(imageRelativeDims[1] * 575 * Math.max(1.5, effectivePixelRatio))]
        ];
    }

    // "mobile"
    return [
        // [imageRelativeDims[0] * 360, imageRelativeDims[1] * 240],
        [Math.round(imageRelativeDims[0] * 680 * effectivePixelRatio), Math.round(imageRelativeDims[1] * 454 * effectivePixelRatio)],
        [Math.round(imageRelativeDims[0] * 680 * effectivePixelRatio), Math.round(imageRelativeDims[1] * 454 * effectivePixelRatio)]
    ];

}

function getSlideInfo(imgSrc) {
    var imgPath = imgSrc.replace('//', "/").trim();
    if(imgPath.indexOf("http") == 0) {
        var u = new URL(imgPath);
        imgPath = u.pathname;
    }
    if(imgPath.indexOf("?") > -1) {
        imgPath = imgPath.split('?')[0];
    }
    if(imgPath.indexOf("/") != 0) {
        imgPath = "/" + imgPath;
    }
    if(imgPath.indexOf("/FURL") != 0) {
        imgPath = "/FURL" + imgPath;
    }
    if(imgSrc.indexOf("placeholder.com") > -1) {
        // replace begnning slah
        var imgSrc = imgSrc.replace(/^\//, "");
        return {
            "Path": imgSrc,
            "Blur": imgSrc,
            "Src1x": imgSrc,
            "Src2x": imgSrc,
            "SrcScale1x": imgSrc,
            "SrcScale2x": imgSrc
        };
    }
    imgPath = unescape(imgPath);
    var slide = slideShowSlides[imgPath];
    if(!slide) {
        console.error('slideShowSlides not found for',imgSrc, imgPath);
    }
    return slide;
}

// determine the 2 sources for the image, using to `determineImageSize` call above
function determineImageSources(imageDom) {
    // nuke any existing width or height setting
    if (!imageDom || !imageDom.getAttribute || !imageDom.getAttribute('data-src')) {
        window.console && console.error && console.error('cannot get image source, no data-src specified:');
        window.console && console.error && console.error(imageDom);
        return;
    }

    var imgSrc = imageDom.getAttribute('data-src');
    if(imgSrc.indexOf("FURL/") == 0) {
        imgSrc = "/" + imgSrc;
    }

    var slide = getSlideInfo(imgSrc);

    if(!slide) {
        console.error('slide not found for', imgSrc);
        return;
    }

    imgSrc2x = slide.Src2x;

    if(effectivePixelRatio > 1) {
        return [imgSrc2x, imgSrc2x];
    }

    return [imgSrc, imgSrc];

    var qaOverride = getParameterByName('qa');
    if (qaOverride) {
        imgSrc = imgSrc.replace(/@qa=85/, '@qa='+qaOverride);
    }

    // TODO: See if overrideW is needed as it doesn't work
    if(imgSrc.indexOf('overrideW')===-1) {
        imgSrc = imgSrc.replace(/@w=[0-9\.]+/, '');
    }
    imgSrc = imgSrc.replace(/@h=[0-9\.]+/, '');

    // if(imgSrc.indexOf('?') > -1) {
    //     imgSrc += "&cb=" + cacheId;
    // } else {
    //     imgSrc += "?cb=" + cacheId;
    // }

    var imgSizes = determineImageSize(imageDom);


    if (imgSrc.match(/cropfit@/)) {
        return [imgSrc.replace(/cropfit@/, 'cropfit@w=' + imgSizes[0][0] + '@'), imgSrc.replace(/cropfit@/, 'cropfit@w=' + imgSizes[1][0] + '@')];
    } else if (imgSrc.match(/cropfit/)) {
        return [imgSrc.replace(/cropfit/, 'cropfit@w=' + imgSizes[0][0]), imgSrc.replace(/cropfit/, 'cropfit@w=' + imgSizes[1][0])];
    } else {
        window.console && console.error && console.error('non-cropfit image: ' + imgSrc);
        return [imgSrc, imgSrc.replace(/temp-color-tests/, 'temp-color-tests/retina')];
    }

}

// special ahead-of-time preloader for the first (visible) slide - so we don't need to wait for
// doc.ready() and all JS libraries loading to have the first slide load
function slideshowPreloadFirstSlide() {

    // all slides were (or should have been) output with "data-src" instead of "src" for images
    // (delayed loading). Get the first slide to load immediately (no jQuery)

    // document.querySelector && !globalIsIOS && new function() {
    document.querySelector && new function() {

        var firstImage = document.querySelector('slide img[data-src]');
        var firstSlide = document.querySelector('slide');

        if (window.responsiveSliderDetermineFirstSlide) {
            var firstSlideNum = responsiveSliderDetermineFirstSlide();
            firstSlide = document.querySelector('slide:nth-child(' + firstSlideNum + ')');
            firstImage = document.querySelector('slide:nth-child(' + firstSlideNum + ') img[data-src], video .vjs-poster');
        }

        // fade the slide in
        if (firstSlide) firstSlide.className += ' fso-slide-active ';

        if (firstImage) {
            var imgSources = determineImageSources(document.querySelector('slide img'));
            var imgSrc =  $(firstImage).attr('data-src');

            if(imgSrc && imgSrc != "") {
                var slide = getSlideInfo(imgSrc);
                if(slide) {
                    imgSrc = slide.Blur;
                }
            }

            if($(window).width() > 768) {
                $('.header-container').css('background-image', 'url(' + imgSrc + ')');

                // remove background after slideshow loaded
                setTimeout(function() {
                    $('.header-container').css('background-image', '');
                }, 3000);
            }


            if (firstSlide.querySelector('.image-holder') && window.determineImageSources) {

                firstSlide.className += ' js-starting-slide';

                [].forEach.call(firstSlide.querySelectorAll('.image-holder'), function(imgHolder) {

                    // better with %s
                    // imgHolder.style.height = imgHolder.getAttribute('data-height') + 'px';
                    // imgHolder.style.width = imgHolder.getAttribute('data-width') + 'px';

                    imgHolder.className += ' js-dynamic-size-set';
                    imgHolder.style.height = (Math.ceil(parseFloat(imgHolder.getAttribute('data-height')) / 575 * 1000000) / 10000) + '%';
                    imgHolder.style.width = (Math.ceil(parseFloat(imgHolder.getAttribute('data-width')) / 860 * 1000000) / 10000) + '%';

                    // dynamic image sizing
                    var theImage = imgHolder.querySelector('img');
                    theImage.addEventListener && theImage.addEventListener('load', function() {
                        imgHolder.classList && imgHolder.classList.remove('js-preview');
                    });
                    var imageSources = determineImageSources(theImage);
                    if(imageSources) {
                        theImage.src = imageSources[0];
                    }
                    theImage.className += ' loaded';

                    $('.slideshow-wrapper').addClass('all-loaded');

                    // console.error('determineImageSources(theImage)[0] = ', determineImageSources(theImage)[0]);

                });

                if (firstSlide.querySelectorAll('.image-holder') && firstSlide.querySelectorAll('.image-holder').length == 1) firstSlide.className += ' js-single-image-slide';

                document.querySelector('.slideshow-wrapper').className += ' js-slideshow-preinited';

            } else {
                [].forEach.call(firstSlide.querySelectorAll('img'), function(theImage) {
                    theImage.src = theImage.getAttribute('data-src');

                    // don't remove `data-src` just yet - that would cancel out the other handlers
                    // for this slide
                    // theImage.removeAttribute('data-src');
                });

                document.querySelector('.slideshow-wrapper').className += ' js-slideshow-preinited';
            }
        } else {
            document.querySelector('.slideshow-wrapper').className += ' js-slideshow-preinited';
        }
    }

}

// prepare the slideshow for immediate view (while it gets initialized and so on):
// * remove various elements if it has only one slide
// * snap to the correct starting position
// * remove the entire DOM if there are no slides in it at all
// * shorten long captions
function slideshowPrepare() {

    // simplify the slideshow if it only has 1 slide
    if (document.querySelectorAll && document.querySelectorAll('.slide-holder slide').length == 1)
        document.getElementById('header_slideshow_wraper').classList.add('slideshow-only-one-slide');

    // slide to the correct slide (before document.ready) and fade in the slideshow
    if (window.responsiveSliderDetermineFirstSlide) {
        var firstSlide = responsiveSliderDetermineFirstSlide();
        _slideToSlideId(firstSlide);
    }

    // remove the entire slideshow (all DOM elements) if there are no slides at all
    if (document.querySelector && !document.querySelector('.slide-holder slide'))
        document.querySelector('.slideshow-wrapper.slideshow-main').parentNode.removeChild(document.querySelector('.slideshow-wrapper.slideshow-main'));

    /*
    // shorten long captions
    if (
            window.deviceCustomType == 'desktop' &&
            document.body.className.match(/templated-slider-build-2-1/) &&
            (window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth) > 767 &&
            (
                (window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth) < 1025 ||
                !document.body.className.match(/locale-en/) ||
                document.body.className.match(/path-scientology-today-church-openings/)
                || document.body.className.match(/path-inside-our-church/)
            ) &&
            window.slideshowCaptionsOverflow
       ) {
        slideshowCaptionsOverflow();
    }*/

}

(function() {
    'use strict';

    function initSlideshow() {
        // blurred slides preview
        var style = document.createElement('style');
        style.appendChild(document.createTextNode(''));
        document.head.appendChild(style);
        var counter = 0;
        var sheet = style.sheet;
        loadPreviews(sheet);


        window.slideshowPreloadFirstSlide && slideshowPreloadFirstSlide();
        slideshowPrepare();

        // if ($('body').hasClass('bio-450px-tall-header')) {
        //     $('.fso-slide-active').removeClass('fso-slide-active');
        //     globalSlideshowFadeout = 0;
        // }

        window.globalSlideshowFadeout = 0.2;

        var globalSlideshowHeader = new GscResponsiveSlider({
            useSimpleSliding: false,
            zoomEnabled: window.globalSlideshowZoomDisable ? false : true,
            slidesMax860: true,
            sliderZoomTopAdjustment: 20,
            touchMode: window.innerWidth < 768 ? 'photoswipe' : 'default',
            zoomOnClick: true,
        });

        globalSlideshowHeader.init();
        window.globalSlideshowHeader = globalSlideshowHeader;

        $(document).on('click', '.press-release-tour-inline', function(event) {
            if($(this).parent()[0].tagName == "A") {
                return;
            }
            event.preventDefault();
            var tourSlideId = getTourSlideId();
            globalSlideshowHeader.initialScrollTop = window.scrollY;

            if(deviceCustomType != 'desktop' && window.globalSlideshowHeader.touchMode == 'photoswipe') {
                window.globalSlideshowHeader.openPhotoswipe(tourSlideId);
                return;
            }


            $('.bs-extender__slideshow-holder').addClass('bs-extender__slideshow-holder__fixed');
            if(tourSlideId) {
                $('.bs-extender__slideshow-holder').addClass('bs-extender__slideshow-holder__fade-out');
                globalSlideshowHeader.fsoSliderZoomIn(true);
                setTimeout(() => {
                    $('.bs-extender__slideshow-holder').addClass('bs-extender__slideshow-holder__fade-in');
                }, 250);
                globalSlideshowHeader.gotoSlide(tourSlideId);
            } else {
                globalSlideshowHeader.fsoSliderZoomIn(true);
            }
        });

        if($('.show-codes-button').length) {
            $('.show-codes-button:not(.copyversion)').click(function(event) {
               $('.image-code').toggleClass('hidden');
            });
            $('slide .image-item').each(function(index, el) {
                // console.log( $(el).find('img').attr('data-src') );
                if($(el).find('img').length > 0) {
                    var src = $(el).find('img').attr('data-src');
                    if(!src) {
                        return;
                    }

                    // check if image name starts with -temp
                    var imageNameParts = src.match(/\/temp[-_].*.jpg/);
                    var imageNameParts2 = src.match(/\/.*[-_]temp.jpg/);
                    if( (imageNameParts && imageNameParts.length > 0) || 
                        (imageNameParts2 && imageNameParts2.length > 0) ) {
                        $(el).append('<div class="image-temp-label">TEMP</div>')
                    }

                    // most are _XX9999.jpg
                    var parts = src.match(/[-_](([0-9]+[a-zA-Z]+|[a-zA-Z]+[0-9]+)[0-9a-zA-Z]*)(-(inet|1))?(-r)?(_en)?.jpg/);
                    if(parts===null) {
                        // Some are DJI_0242
                        parts = src.match(/[-_]([A-Z]+_[0-9]+).jpg/);
                    }
                    if(parts && parts.length > 0) {
                        var code = parts[1];
                        $(el).append('<div class="image-code hidden">'+code+'</div>')
                    }
                }
            });

            loadjs(['/plugins/bootstrap/js/bootstrap.bundle.min.js?_='+cacheId], 'bootstrapjs', {async: false});
            loadjs.ready('bootstrapjs', function() {
                $('.image-code').tooltip({
                    html: true,
                    title: '<span class="icon-zoom-in"></span> VIEW FULL SCREEN',
                    placement: 'bottom',
                });
            });

            // load up photoswipe
            loadJS('/plugins/photoswipe/photoswipe.min.js?_=' + new Date().getTime());
            loadJS('/plugins/photoswipe/photoswipe-ui-default.min.js?_=' + new Date().getTime());

            loadjs(['css!/plugins/photoswipe/photoswipe.css?_=' + cacheId, 'css!/plugins/photoswipe/default-skin/default-skin.css?_=' + cacheId]);

            $('.pswp__container').html('<div class="pswp__item"></div><div class="pswp__item"></div><div class="pswp__item"></div>');

            $(document).on('click', '.image-code', function(e){
                e.stopPropagation();
                e.stopImmediatePropagation();
                e.preventDefault();

                var $imageItem = $(this).closest('.image-item');
                var src = $imageItem.find('img').attr('data-src').replace(/@w=[0-9]*/, '');
                if(src[0] != "/") {
                    src = "/" + src;
                }
                // photoswipe zoom in
                if(src) {
                    var url = new URL(window.location.href);
                    url.pathname = src;
                    var pswpElement = document.querySelectorAll('.pswp')[0];
                    // build items array
                    var items = [
                        {
                            src: unescape(url.toString()),
                            w: 0,
                            h: 0,
                        },
                    ];

                    // define options (if needed)
                    var options = {
                        index: 0,
                        shareEl: false,
                        history: false
                    };
                    var gallery = new PhotoSwipe( pswpElement, PhotoSwipeUI_Default, items, options);

                    // dynamicly set W & H
                    gallery.listen('gettingData', function (index, item) {
                        if (item.w < 1 || item.h < 1) {
                            var img = new Image();
                            img.onload = function () {
                                item.w = this.width;
                                item.h = this.height;
                                gallery.updateSize(true);
                            };
                            img.src = item.src;
                        }
                    });

                    gallery.init();
                }
            });
        }

        $('.fso-slide-mobile-numbers').css('padding-bottom', '0px');

        if ($('body').hasClass('bio-450px-tall-header')) {
            setTimeout(function() {
                $('#header_slideshow_wraper').addClass('slideshow-released');
            }, 1000);
        }

        initDynamicSlides();


        $(document).on('click', '.caption-overlay-button__open', function(event) {
            event.preventDefault();
            event.stopPropagation();

            var $overlay = $('.fso-slide-active .caption-overlay');
            if($overlay.hasClass('d-none')) {
                $overlay.removeClass('d-none');
                TweenMax.fromTo($overlay, 0.25, {autoAlpha: 0}, {autoAlpha: 1});
                $(this).addClass('caption-overlay-button__open--visible');
            } else {
                $(this).removeClass('caption-overlay-button__open--visible');
                TweenMax.to($overlay, 0.25, {autoAlpha: 0, onComplete: function(){
                    $overlay.addClass('d-none');
                }});
            }
        });
    }

    function loadPreviews(sheet) {
        var counter = 0;
        [].forEach.call(document.querySelectorAll('.slide-holder slide .image-holder'), function(imgHolder) {
            if(!imgHolder.querySelector('img').dataset || !imgHolder.querySelector('img').dataset.src) {
                return;
            }
            var previewImage = imgHolder.querySelector('img').getAttribute('data-src');
            var slide = getSlideInfo(previewImage);
            previewImage = slide && slide.Blur;

            // skip pngs
            if(!previewImage || previewImage.indexOf('.png') > -1) {
                return;
            }

            var uuid = (Math.random() + '').replace(/^0./, '');
            // load first 5 images first
            if(counter < 5) {
                insertPlaceholder(sheet, uuid, previewImage, imgHolder, counter);
            } else {
                // delay for fast rendering start (doesnt need other placeholders yet)
                (function(counter){
                    setTimeout(function(){
                        insertPlaceholder(sheet, uuid, previewImage, imgHolder, counter);
                    }, 5000);
                })(counter);
            }
            counter++;
        });
    }

    function getTourSlideId() {
        for (var slideId in slideShowSlides) {
            if (Object.hasOwnProperty.call(slideShowSlides, slideId)) {
                var slide = slideShowSlides[slideId];
                if(slide.SlideSetId) {
                    return slide.Index;
                }
            }
        }
    }

    function insertPlaceholder(sheet, uuid, previewImage, imgHolder, counter) {
        sheet.insertRule('.image-holder[data-uuid="' + uuid + '"].js-preview:before { ' +
            'background-image: url('+ previewImage +')' +
            '}', counter);
        imgHolder.setAttribute('data-uuid', uuid);
        imgHolder.className += ' js-preview';
    }

    if (!$('.slide-holder slide').length) return $('.slideshow-wrapper.slideshow-main').remove();

    // if($('body').hasClass('templated-slider-style-standard-templates')) {
        initSlideshow();
    // } else {
    //     // this is a workaround for safari. slideshows.scss has to be loaded before JS execution, safari seems to be trying to loadcss and JS concurently
    //     loadjs(['css!/_combined/slideshows.scss?_=' + cacheId], 'slideshowsCss', {
    //             async: true,
    //             success: function() {
    //                 initSlideshow();
    //             }
    //         });
    // }
})();
