/*!
 * ASP.NET Core SignalR JavaScript Client v8.0.7
 * modified to wrap and prevent define.amd conflicts with RequireJS
 */

(function(global) {
    // Save original signalR
    var noConflict = global.signalR;
    
    // Save original module and define
    var originalModule = global.module;
    var originalExports = global.exports;
    var originalDefine = global.define;
    var originalDefineAmd = originalDefine && originalDefine.amd;
    
    // Temporarily disable module systems
    global.module = undefined;
    global.exports = undefined;
    global.define = undefined;

     //! signalR.js
    //! ASP.NET Core SignalR JavaScript Client
    //! Version: 8.0.7

var t,e;t=self,e=()=>(()=>{var t={d:(e,s)=>{for(var i in s)t.o(s,i)&&!t.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:s[i]})}};t.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(t){if("object"==typeof window)return window}}(),t.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),t.r=t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"t",{value:!0})};var e,s={};t.r(s),t.d(s,{AbortError:()=>r,DefaultHttpClient:()=>H,HttpClient:()=>d,HttpError:()=>i,HttpResponse:()=>u,HttpTransportType:()=>F,HubConnection:()=>q,HubConnectionBuilder:()=>tt,HubConnectionState:()=>A,JsonHubProtocol:()=>Y,LogLevel:()=>e,MessageType:()=>x,NullLogger:()=>f,Subject:()=>U,TimeoutError:()=>n,TransferFormat:()=>B,VERSION:()=>p});class i extends Error{constructor(t,e){const s=new.target.prototype;super(`${t}: Status code '${e}'`),this.statusCode=e,this.__proto__=s}}class n extends Error{constructor(t="A timeout occurred."){const e=new.target.prototype;super(t),this.__proto__=e}}class r extends Error{constructor(t="An abort occurred."){const e=new.target.prototype;super(t),this.__proto__=e}}class o extends Error{constructor(t,e){const s=new.target.prototype;super(t),this.transport=e,this.errorType="UnsupportedTransportError",this.__proto__=s}}class h extends Error{constructor(t,e){const s=new.target.prototype;super(t),this.transport=e,this.errorType="DisabledTransportError",this.__proto__=s}}class c extends Error{constructor(t,e){const s=new.target.prototype;super(t),this.transport=e,this.errorType="FailedToStartTransportError",this.__proto__=s}}class a extends Error{constructor(t){const e=new.target.prototype;super(t),this.errorType="FailedToNegotiateWithServerError",this.__proto__=e}}class l extends Error{constructor(t,e){const s=new.target.prototype;super(t),this.innerErrors=e,this.__proto__=s}}class u{constructor(t,e,s){this.statusCode=t,this.statusText=e,this.content=s}}class d{get(t,e){return this.send({...e,method:"GET",url:t})}post(t,e){return this.send({...e,method:"POST",url:t})}delete(t,e){return this.send({...e,method:"DELETE",url:t})}getCookieString(t){return""}}!function(t){t[t.Trace=0]="Trace",t[t.Debug=1]="Debug",t[t.Information=2]="Information",t[t.Warning=3]="Warning",t[t.Error=4]="Error",t[t.Critical=5]="Critical",t[t.None=6]="None"}(e||(e={}));class f{constructor(){}log(t,e){}}f.instance=new f;const p="8.0.7";class w{static isRequired(t,e){if(null==t)throw new Error(`The '${e}' argument is required.`)}static isNotEmpty(t,e){if(!t||t.match(/^\s*$/))throw new Error(`The '${e}' argument should not be empty.`)}static isIn(t,e,s){if(!(t in e))throw new Error(`Unknown ${s} value: ${t}.`)}}class g{static get isBrowser(){return!g.isNode&&"object"==typeof window&&"object"==typeof window.document}static get isWebWorker(){return!g.isNode&&"object"==typeof self&&"importScripts"in self}static get isReactNative(){return!g.isNode&&"object"==typeof window&&void 0===window.document}static get isNode(){return"undefined"!=typeof process&&process.release&&"node"===process.release.name}}function m(t,e){let s="";return y(t)?(s=`Binary data of length ${t.byteLength}`,e&&(s+=`. Content: '${function(t){const e=new Uint8Array(t);let s="";return e.forEach((t=>{s+=`0x${t<16?"0":""}${t.toString(16)} `})),s.substr(0,s.length-1)}(t)}'`)):"string"==typeof t&&(s=`String data of length ${t.length}`,e&&(s+=`. Content: '${t}'`)),s}function y(t){return t&&"undefined"!=typeof ArrayBuffer&&(t instanceof ArrayBuffer||t.constructor&&"ArrayBuffer"===t.constructor.name)}async function b(t,s,i,n,r,o){const h={},[c,a]=$();h[c]=a,t.log(e.Trace,`(${s} transport) sending data. ${m(r,o.logMessageContent)}.`);const l=y(r)?"arraybuffer":"text",u=await i.post(n,{content:r,headers:{...h,...o.headers},responseType:l,timeout:o.timeout,withCredentials:o.withCredentials});t.log(e.Trace,`(${s} transport) request complete. Response status: ${u.statusCode}.`)}class v{constructor(t,e){this.i=t,this.h=e}dispose(){const t=this.i.observers.indexOf(this.h);t>-1&&this.i.observers.splice(t,1),0===this.i.observers.length&&this.i.cancelCallback&&this.i.cancelCallback().catch((t=>{}))}}class E{constructor(t){this.l=t,this.out=console}log(t,s){if(t>=this.l){const i=`[${(new Date).toISOString()}] ${e[t]}: ${s}`;switch(t){case e.Critical:case e.Error:this.out.error(i);break;case e.Warning:this.out.warn(i);break;case e.Information:this.out.info(i);break;default:this.out.log(i)}}}}function $(){let t="X-SignalR-User-Agent";return g.isNode&&(t="User-Agent"),[t,C(p,S(),g.isNode?"NodeJS":"Browser",k())]}function C(t,e,s,i){let n="Microsoft SignalR/";const r=t.split(".");return n+=`${r[0]}.${r[1]}`,n+=` (${t}; `,n+=e&&""!==e?`${e}; `:"Unknown OS; ",n+=`${s}`,n+=i?`; ${i}`:"; Unknown Runtime Version",n+=")",n}function S(){if(!g.isNode)return"";switch(process.platform){case"win32":return"Windows NT";case"darwin":return"macOS";case"linux":return"Linux";default:return process.platform}}function k(){if(g.isNode)return process.versions.node}function P(t){return t.stack?t.stack:t.message?t.message:`${t}`}class T extends d{constructor(e){if(super(),this.u=e,"undefined"==typeof fetch||g.isNode){const t=require;this.p=new(t("tough-cookie").CookieJar),"undefined"==typeof fetch?this.m=t("node-fetch"):this.m=fetch,this.m=t("fetch-cookie")(this.m,this.p)}else this.m=fetch.bind(function(){if("undefined"!=typeof globalThis)return globalThis;if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if(void 0!==t.g)return t.g;throw new Error("could not find global")}());if("undefined"==typeof AbortController){const t=require;this.v=t("abort-controller")}else this.v=AbortController}async send(t){if(t.abortSignal&&t.abortSignal.aborted)throw new r;if(!t.method)throw new Error("No method defined.");if(!t.url)throw new Error("No url defined.");const s=new this.v;let o;t.abortSignal&&(t.abortSignal.onabort=()=>{s.abort(),o=new r});let h,c=null;if(t.timeout){const i=t.timeout;c=setTimeout((()=>{s.abort(),this.u.log(e.Warning,"Timeout from HTTP request."),o=new n}),i)}""===t.content&&(t.content=void 0),t.content&&(t.headers=t.headers||{},y(t.content)?t.headers["Content-Type"]="application/octet-stream":t.headers["Content-Type"]="text/plain;charset=UTF-8");try{h=await this.m(t.url,{body:t.content,cache:"no-cache",credentials:!0===t.withCredentials?"include":"same-origin",headers:{"X-Requested-With":"XMLHttpRequest",...t.headers},method:t.method,mode:"cors",redirect:"follow",signal:s.signal})}catch(t){if(o)throw o;throw this.u.log(e.Warning,`Error from HTTP request. ${t}.`),t}finally{c&&clearTimeout(c),t.abortSignal&&(t.abortSignal.onabort=null)}if(!h.ok){const t=await I(h,"text");throw new i(t||h.statusText,h.status)}const a=I(h,t.responseType),l=await a;return new u(h.status,h.statusText,l)}getCookieString(t){let e="";return g.isNode&&this.p&&this.p.getCookies(t,((t,s)=>e=s.join("; "))),e}}function I(t,e){let s;switch(e){case"arraybuffer":s=t.arrayBuffer();break;case"text":default:s=t.text();break;case"blob":case"document":case"json":throw new Error(`${e} is not supported.`)}return s}class _ extends d{constructor(t){super(),this.u=t}send(t){return t.abortSignal&&t.abortSignal.aborted?Promise.reject(new r):t.method?t.url?new Promise(((s,o)=>{const h=new XMLHttpRequest;h.open(t.method,t.url,!0),h.withCredentials=void 0===t.withCredentials||t.withCredentials,h.setRequestHeader("X-Requested-With","XMLHttpRequest"),""===t.content&&(t.content=void 0),t.content&&(y(t.content)?h.setRequestHeader("Content-Type","application/octet-stream"):h.setRequestHeader("Content-Type","text/plain;charset=UTF-8"));const c=t.headers;c&&Object.keys(c).forEach((t=>{h.setRequestHeader(t,c[t])})),t.responseType&&(h.responseType=t.responseType),t.abortSignal&&(t.abortSignal.onabort=()=>{h.abort(),o(new r)}),t.timeout&&(h.timeout=t.timeout),h.onload=()=>{t.abortSignal&&(t.abortSignal.onabort=null),h.status>=200&&h.status<300?s(new u(h.status,h.statusText,h.response||h.responseText)):o(new i(h.response||h.responseText||h.statusText,h.status))},h.onerror=()=>{this.u.log(e.Warning,`Error from HTTP request. ${h.status}: ${h.statusText}.`),o(new i(h.statusText,h.status))},h.ontimeout=()=>{this.u.log(e.Warning,"Timeout from HTTP request."),o(new n)},h.send(t.content)})):Promise.reject(new Error("No url defined.")):Promise.reject(new Error("No method defined."))}}class H extends d{constructor(t){if(super(),"undefined"!=typeof fetch||g.isNode)this.$=new T(t);else{if("undefined"==typeof XMLHttpRequest)throw new Error("No usable HttpClient found.");this.$=new _(t)}}send(t){return t.abortSignal&&t.abortSignal.aborted?Promise.reject(new r):t.method?t.url?this.$.send(t):Promise.reject(new Error("No url defined.")):Promise.reject(new Error("No method defined."))}getCookieString(t){return this.$.getCookieString(t)}}class D{static write(t){return`${t}${D.RecordSeparator}`}static parse(t){if(t[t.length-1]!==D.RecordSeparator)throw new Error("Message is incomplete.");const e=t.split(D.RecordSeparator);return e.pop(),e}}D.RecordSeparatorCode=30,D.RecordSeparator=String.fromCharCode(D.RecordSeparatorCode);class R{writeHandshakeRequest(t){return D.write(JSON.stringify(t))}parseHandshakeResponse(t){let e,s;if(y(t)){const i=new Uint8Array(t),n=i.indexOf(D.RecordSeparatorCode);if(-1===n)throw new Error("Message is incomplete.");const r=n+1;e=String.fromCharCode.apply(null,Array.prototype.slice.call(i.slice(0,r))),s=i.byteLength>r?i.slice(r).buffer:null}else{const i=t,n=i.indexOf(D.RecordSeparator);if(-1===n)throw new Error("Message is incomplete.");const r=n+1;e=i.substring(0,r),s=i.length>r?i.substring(r):null}const i=D.parse(e),n=JSON.parse(i[0]);if(n.type)throw new Error("Expected a handshake response from the server.");return[s,n]}}var x,A;!function(t){t[t.Invocation=1]="Invocation",t[t.StreamItem=2]="StreamItem",t[t.Completion=3]="Completion",t[t.StreamInvocation=4]="StreamInvocation",t[t.CancelInvocation=5]="CancelInvocation",t[t.Ping=6]="Ping",t[t.Close=7]="Close",t[t.Ack=8]="Ack",t[t.Sequence=9]="Sequence"}(x||(x={}));class U{constructor(){this.observers=[]}next(t){for(const e of this.observers)e.next(t)}error(t){for(const e of this.observers)e.error&&e.error(t)}complete(){for(const t of this.observers)t.complete&&t.complete()}subscribe(t){return this.observers.push(t),new v(this,t)}}class L{constructor(t,e,s){this.C=1e5,this.S=[],this.k=0,this.P=!1,this.T=1,this.I=0,this._=0,this.H=!1,this.D=t,this.R=e,this.C=s}async A(t){const e=this.D.writeMessage(t);let s=Promise.resolve();if(this.U(t)){this.k++;let t=()=>{},i=()=>{};y(e)?this._+=e.byteLength:this._+=e.length,this._>=this.C&&(s=new Promise(((e,s)=>{t=e,i=s}))),this.S.push(new N(e,this.k,t,i))}try{this.H||await this.R.send(e)}catch{this.L()}await s}N(t){let e=-1;for(let s=0;s<this.S.length;s++){const i=this.S[s];if(i.q<=t.sequenceId)e=s,y(i.M)?this._-=i.M.byteLength:this._-=i.M.length,i.j();else{if(!(this._<this.C))break;i.j()}}-1!==e&&(this.S=this.S.slice(e+1))}W(t){if(this.P)return t.type===x.Sequence&&(this.P=!1,!0);if(!this.U(t))return!0;const e=this.T;return this.T++,e<=this.I?(e===this.I&&this.O(),!1):(this.I=e,this.O(),!0)}F(t){t.sequenceId>this.T?this.R.stop(new Error("Sequence ID greater than amount of messages we've received.")):this.T=t.sequenceId}L(){this.H=!0,this.P=!0}async B(){const t=0!==this.S.length?this.S[0].q:this.k+1;await this.R.send(this.D.writeMessage({type:x.Sequence,sequenceId:t}));const e=this.S;for(const t of e)await this.R.send(t.M);this.H=!1}X(t){null!=t||(t=new Error("Unable to reconnect to server."));for(const e of this.S)e.J(t)}U(t){switch(t.type){case x.Invocation:case x.StreamItem:case x.Completion:case x.StreamInvocation:case x.CancelInvocation:return!0;case x.Close:case x.Sequence:case x.Ping:case x.Ack:return!1}}O(){void 0===this.V&&(this.V=setTimeout((async()=>{try{this.H||await this.R.send(this.D.writeMessage({type:x.Ack,sequenceId:this.I}))}catch{}clearTimeout(this.V),this.V=void 0}),1e3))}}class N{constructor(t,e,s,i){this.M=t,this.q=e,this.j=s,this.J=i}}!function(t){t.Disconnected="Disconnected",t.Connecting="Connecting",t.Connected="Connected",t.Disconnecting="Disconnecting",t.Reconnecting="Reconnecting"}(A||(A={}));class q{static create(t,e,s,i,n,r,o){return new q(t,e,s,i,n,r,o)}constructor(t,s,i,n,r,o,h){this.K=0,this.G=()=>{this.u.log(e.Warning,"The page is being frozen, this will likely lead to the connection being closed and messages being lost. For more information see the docs at https://learn.microsoft.com/aspnet/core/signalr/javascript-client#bsleep")},w.isRequired(t,"connection"),w.isRequired(s,"logger"),w.isRequired(i,"protocol"),this.serverTimeoutInMilliseconds=null!=r?r:3e4,this.keepAliveIntervalInMilliseconds=null!=o?o:15e3,this.Y=null!=h?h:1e5,this.u=s,this.D=i,this.connection=t,this.Z=n,this.tt=new R,this.connection.onreceive=t=>this.et(t),this.connection.onclose=t=>this.st(t),this.it={},this.nt={},this.rt=[],this.ot=[],this.ht=[],this.ct=0,this.lt=!1,this.ut=A.Disconnected,this.dt=!1,this.ft=this.D.writeMessage({type:x.Ping})}get state(){return this.ut}get connectionId(){return this.connection&&this.connection.connectionId||null}get baseUrl(){return this.connection.baseUrl||""}set baseUrl(t){if(this.ut!==A.Disconnected&&this.ut!==A.Reconnecting)throw new Error("The HubConnection must be in the Disconnected or Reconnecting state to change the url.");if(!t)throw new Error("The HubConnection url must be a valid url.");this.connection.baseUrl=t}start(){return this.wt=this.gt(),this.wt}async gt(){if(this.ut!==A.Disconnected)return Promise.reject(new Error("Cannot start a HubConnection that is not in the 'Disconnected' state."));this.ut=A.Connecting,this.u.log(e.Debug,"Starting HubConnection.");try{await this.yt(),g.isBrowser&&window.document.addEventListener("freeze",this.G),this.ut=A.Connected,this.dt=!0,this.u.log(e.Debug,"HubConnection connected successfully.")}catch(t){return this.ut=A.Disconnected,this.u.log(e.Debug,`HubConnection failed to start successfully because of error '${t}'.`),Promise.reject(t)}}async yt(){this.bt=void 0,this.lt=!1;const t=new Promise(((t,e)=>{this.vt=t,this.Et=e}));await this.connection.start(this.D.transferFormat);try{let s=this.D.version;this.connection.features.reconnect||(s=1);const i={protocol:this.D.name,version:s};if(this.u.log(e.Debug,"Sending handshake request."),await this.$t(this.tt.writeHandshakeRequest(i)),this.u.log(e.Information,`Using HubProtocol '${this.D.name}'.`),this.Ct(),this.St(),this.kt(),await t,this.bt)throw this.bt;!!this.connection.features.reconnect&&(this.Pt=new L(this.D,this.connection,this.Y),this.connection.features.disconnected=this.Pt.L.bind(this.Pt),this.connection.features.resend=()=>{if(this.Pt)return this.Pt.B()}),this.connection.features.inherentKeepAlive||await this.$t(this.ft)}catch(t){throw this.u.log(e.Debug,`Hub handshake failed with error '${t}' during start(). Stopping HubConnection.`),this.Ct(),this.Tt(),await this.connection.stop(t),t}}async stop(){const t=this.wt;this.connection.features.reconnect=!1,this.It=this._t(),await this.It;try{await t}catch(t){}}_t(t){if(this.ut===A.Disconnected)return this.u.log(e.Debug,`Call to HubConnection.stop(${t}) ignored because it is already in the disconnected state.`),Promise.resolve();if(this.ut===A.Disconnecting)return this.u.log(e.Debug,`Call to HttpConnection.stop(${t}) ignored because the connection is already in the disconnecting state.`),this.It;const s=this.ut;return this.ut=A.Disconnecting,this.u.log(e.Debug,"Stopping HubConnection."),this.Ht?(this.u.log(e.Debug,"Connection stopped during reconnect delay. Done reconnecting."),clearTimeout(this.Ht),this.Ht=void 0,this.Dt(),Promise.resolve()):(s===A.Connected&&this.Rt(),this.Ct(),this.Tt(),this.bt=t||new r("The connection was stopped before the hub handshake could complete."),this.connection.stop(t))}async Rt(){try{await this.xt(this.At())}catch{}}stream(t,...e){const[s,i]=this.Ut(e),n=this.Lt(t,e,i);let r;const o=new U;return o.cancelCallback=()=>{const t=this.Nt(n.invocationId);return delete this.it[n.invocationId],r.then((()=>this.xt(t)))},this.it[n.invocationId]=(t,e)=>{e?o.error(e):t&&(t.type===x.Completion?t.error?o.error(new Error(t.error)):o.complete():o.next(t.item))},r=this.xt(n).catch((t=>{o.error(t),delete this.it[n.invocationId]})),this.qt(s,r),o}$t(t){return this.kt(),this.connection.send(t)}xt(t){return this.Pt?this.Pt.A(t):this.$t(this.D.writeMessage(t))}send(t,...e){const[s,i]=this.Ut(e),n=this.xt(this.Mt(t,e,!0,i));return this.qt(s,n),n}invoke(t,...e){const[s,i]=this.Ut(e),n=this.Mt(t,e,!1,i);return new Promise(((t,e)=>{this.it[n.invocationId]=(s,i)=>{i?e(i):s&&(s.type===x.Completion?s.error?e(new Error(s.error)):t(s.result):e(new Error(`Unexpected message type: ${s.type}`)))};const i=this.xt(n).catch((t=>{e(t),delete this.it[n.invocationId]}));this.qt(s,i)}))}on(t,e){t&&e&&(t=t.toLowerCase(),this.nt[t]||(this.nt[t]=[]),-1===this.nt[t].indexOf(e)&&this.nt[t].push(e))}off(t,e){if(!t)return;t=t.toLowerCase();const s=this.nt[t];if(s)if(e){const i=s.indexOf(e);-1!==i&&(s.splice(i,1),0===s.length&&delete this.nt[t])}else delete this.nt[t]}onclose(t){t&&this.rt.push(t)}onreconnecting(t){t&&this.ot.push(t)}onreconnected(t){t&&this.ht.push(t)}et(t){if(this.Ct(),this.lt||(t=this.jt(t),this.lt=!0),t){const s=this.D.parseMessages(t,this.u);for(const t of s)if(!this.Pt||this.Pt.W(t))switch(t.type){case x.Invocation:this.Wt(t).catch((t=>{this.u.log(e.Error,`Invoke client method threw error: ${P(t)}`)}));break;case x.StreamItem:case x.Completion:{const s=this.it[t.invocationId];if(s){t.type===x.Completion&&delete this.it[t.invocationId];try{s(t)}catch(t){this.u.log(e.Error,`Stream callback threw error: ${P(t)}`)}}break}case x.Ping:break;case x.Close:{this.u.log(e.Information,"Close message received from server.");const s=t.error?new Error("Server returned an error on close: "+t.error):void 0;!0===t.allowReconnect?this.connection.stop(s):this.It=this._t(s);break}case x.Ack:this.Pt&&this.Pt.N(t);break;case x.Sequence:this.Pt&&this.Pt.F(t);break;default:this.u.log(e.Warning,`Invalid message type: ${t.type}.`)}}this.St()}jt(t){let s,i;try{[i,s]=this.tt.parseHandshakeResponse(t)}catch(t){const s="Error parsing handshake response: "+t;this.u.log(e.Error,s);const i=new Error(s);throw this.Et(i),i}if(s.error){const t="Server returned handshake error: "+s.error;this.u.log(e.Error,t);const i=new Error(t);throw this.Et(i),i}return this.u.log(e.Debug,"Server handshake complete."),this.vt(),i}kt(){this.connection.features.inherentKeepAlive||(this.K=(new Date).getTime()+this.keepAliveIntervalInMilliseconds,this.Tt())}St(){if(!(this.connection.features&&this.connection.features.inherentKeepAlive||(this.Ot=setTimeout((()=>this.serverTimeout()),this.serverTimeoutInMilliseconds),void 0!==this.Ft))){let t=this.K-(new Date).getTime();t<0&&(t=0),this.Ft=setTimeout((async()=>{if(this.ut===A.Connected)try{await this.$t(this.ft)}catch{this.Tt()}}),t)}}serverTimeout(){this.connection.stop(new Error("Server timeout elapsed without receiving a message from the server."))}async Wt(t){const s=t.target.toLowerCase(),i=this.nt[s];if(!i)return this.u.log(e.Warning,`No client method with the name '${s}' found.`),void(t.invocationId&&(this.u.log(e.Warning,`No result given for '${s}' method and invocation ID '${t.invocationId}'.`),await this.xt(this.Bt(t.invocationId,"Client didn't provide a result.",null))));const n=i.slice(),r=!!t.invocationId;let o,h,c;for(const i of n)try{const n=o;o=await i.apply(this,t.arguments),r&&o&&n&&(this.u.log(e.Error,`Multiple results provided for '${s}'. Sending error to server.`),c=this.Bt(t.invocationId,"Client provided multiple results.",null)),h=void 0}catch(t){h=t,this.u.log(e.Error,`A callback for the method '${s}' threw error '${t}'.`)}c?await this.xt(c):r?(h?c=this.Bt(t.invocationId,`${h}`,null):void 0!==o?c=this.Bt(t.invocationId,null,o):(this.u.log(e.Warning,`No result given for '${s}' method and invocation ID '${t.invocationId}'.`),c=this.Bt(t.invocationId,"Client didn't provide a result.",null)),await this.xt(c)):o&&this.u.log(e.Error,`Result given for '${s}' method but server is not expecting a result.`)}st(t){this.u.log(e.Debug,`HubConnection.connectionClosed(${t}) called while in state ${this.ut}.`),this.bt=this.bt||t||new r("The underlying connection was closed before the hub handshake could complete."),this.vt&&this.vt(),this.Xt(t||new Error("Invocation canceled due to the underlying connection being closed.")),this.Ct(),this.Tt(),this.ut===A.Disconnecting?this.Dt(t):this.ut===A.Connected&&this.Z?this.Jt(t):this.ut===A.Connected&&this.Dt(t)}Dt(t){if(this.dt){this.ut=A.Disconnected,this.dt=!1,this.Pt&&(this.Pt.X(null!=t?t:new Error("Connection closed.")),this.Pt=void 0),g.isBrowser&&window.document.removeEventListener("freeze",this.G);try{this.rt.forEach((e=>e.apply(this,[t])))}catch(s){this.u.log(e.Error,`An onclose callback called with error '${t}' threw error '${s}'.`)}}}async Jt(t){const s=Date.now();let i=0,n=void 0!==t?t:new Error("Attempting to reconnect due to a unknown error."),r=this.zt(i++,0,n);if(null===r)return this.u.log(e.Debug,"Connection not reconnecting because the IRetryPolicy returned null on the first reconnect attempt."),void this.Dt(t);if(this.ut=A.Reconnecting,t?this.u.log(e.Information,`Connection reconnecting because of error '${t}'.`):this.u.log(e.Information,"Connection reconnecting."),0!==this.ot.length){try{this.ot.forEach((e=>e.apply(this,[t])))}catch(s){this.u.log(e.Error,`An onreconnecting callback called with error '${t}' threw error '${s}'.`)}if(this.ut!==A.Reconnecting)return void this.u.log(e.Debug,"Connection left the reconnecting state in onreconnecting callback. Done reconnecting.")}for(;null!==r;){if(this.u.log(e.Information,`Reconnect attempt number ${i} will start in ${r} ms.`),await new Promise((t=>{this.Ht=setTimeout(t,r)})),this.Ht=void 0,this.ut!==A.Reconnecting)return void this.u.log(e.Debug,"Connection left the reconnecting state during reconnect delay. Done reconnecting.");try{if(await this.yt(),this.ut=A.Connected,this.u.log(e.Information,"HubConnection reconnected successfully."),0!==this.ht.length)try{this.ht.forEach((t=>t.apply(this,[this.connection.connectionId])))}catch(t){this.u.log(e.Error,`An onreconnected callback called with connectionId '${this.connection.connectionId}; threw error '${t}'.`)}return}catch(t){if(this.u.log(e.Information,`Reconnect attempt failed because of error '${t}'.`),this.ut!==A.Reconnecting)return this.u.log(e.Debug,`Connection moved to the '${this.ut}' from the reconnecting state during reconnect attempt. Done reconnecting.`),void(this.ut===A.Disconnecting&&this.Dt());n=t instanceof Error?t:new Error(t.toString()),r=this.zt(i++,Date.now()-s,n)}}this.u.log(e.Information,`Reconnect retries have been exhausted after ${Date.now()-s} ms and ${i} failed attempts. Connection disconnecting.`),this.Dt()}zt(t,s,i){try{return this.Z.nextRetryDelayInMilliseconds({elapsedMilliseconds:s,previousRetryCount:t,retryReason:i})}catch(i){return this.u.log(e.Error,`IRetryPolicy.nextRetryDelayInMilliseconds(${t}, ${s}) threw error '${i}'.`),null}}Xt(t){const s=this.it;this.it={},Object.keys(s).forEach((i=>{const n=s[i];try{n(null,t)}catch(s){this.u.log(e.Error,`Stream 'error' callback called with '${t}' threw error: ${P(s)}`)}}))}Tt(){this.Ft&&(clearTimeout(this.Ft),this.Ft=void 0)}Ct(){this.Ot&&clearTimeout(this.Ot)}Mt(t,e,s,i){if(s)return 0!==i.length?{arguments:e,streamIds:i,target:t,type:x.Invocation}:{arguments:e,target:t,type:x.Invocation};{const s=this.ct;return this.ct++,0!==i.length?{arguments:e,invocationId:s.toString(),streamIds:i,target:t,type:x.Invocation}:{arguments:e,invocationId:s.toString(),target:t,type:x.Invocation}}}qt(t,e){if(0!==t.length){e||(e=Promise.resolve());for(const s in t)t[s].subscribe({complete:()=>{e=e.then((()=>this.xt(this.Bt(s))))},error:t=>{let i;i=t instanceof Error?t.message:t&&t.toString?t.toString():"Unknown error",e=e.then((()=>this.xt(this.Bt(s,i))))},next:t=>{e=e.then((()=>this.xt(this.Vt(s,t))))}})}}Ut(t){const e=[],s=[];for(let i=0;i<t.length;i++){const n=t[i];if(this.Kt(n)){const r=this.ct;this.ct++,e[r]=n,s.push(r.toString()),t.splice(i,1)}}return[e,s]}Kt(t){return t&&t.subscribe&&"function"==typeof t.subscribe}Lt(t,e,s){const i=this.ct;return this.ct++,0!==s.length?{arguments:e,invocationId:i.toString(),streamIds:s,target:t,type:x.StreamInvocation}:{arguments:e,invocationId:i.toString(),target:t,type:x.StreamInvocation}}Nt(t){return{invocationId:t,type:x.CancelInvocation}}Vt(t,e){return{invocationId:t,item:e,type:x.StreamItem}}Bt(t,e,s){return e?{error:e,invocationId:t,type:x.Completion}:{invocationId:t,result:s,type:x.Completion}}At(){return{type:x.Close}}}const M=[0,2e3,1e4,3e4,null];class j{constructor(t){this.Gt=void 0!==t?[...t,null]:M}nextRetryDelayInMilliseconds(t){return this.Gt[t.previousRetryCount]}}class W{}W.Authorization="Authorization",W.Cookie="Cookie";class O extends d{constructor(t,e){super(),this.Qt=t,this.Yt=e}async send(t){let e=!0;this.Yt&&(!this.Zt||t.url&&t.url.indexOf("/negotiate?")>0)&&(e=!1,this.Zt=await this.Yt()),this.te(t);const s=await this.Qt.send(t);return e&&401===s.statusCode&&this.Yt?(this.Zt=await this.Yt(),this.te(t),await this.Qt.send(t)):s}te(t){t.headers||(t.headers={}),this.Zt?t.headers[W.Authorization]=`Bearer ${this.Zt}`:this.Yt&&t.headers[W.Authorization]&&delete t.headers[W.Authorization]}getCookieString(t){return this.Qt.getCookieString(t)}}var F,B;!function(t){t[t.None=0]="None",t[t.WebSockets=1]="WebSockets",t[t.ServerSentEvents=2]="ServerSentEvents",t[t.LongPolling=4]="LongPolling"}(F||(F={})),function(t){t[t.Text=1]="Text",t[t.Binary=2]="Binary"}(B||(B={}));class X{constructor(){this.ee=!1,this.onabort=null}abort(){this.ee||(this.ee=!0,this.onabort&&this.onabort())}get signal(){return this}get aborted(){return this.ee}}class J{get pollAborted(){return this.se.aborted}constructor(t,e,s){this.$=t,this.u=e,this.se=new X,this.ie=s,this.ne=!1,this.onreceive=null,this.onclose=null}async connect(t,s){if(w.isRequired(t,"url"),w.isRequired(s,"transferFormat"),w.isIn(s,B,"transferFormat"),this.re=t,this.u.log(e.Trace,"(LongPolling transport) Connecting."),s===B.Binary&&"undefined"!=typeof XMLHttpRequest&&"string"!=typeof(new XMLHttpRequest).responseType)throw new Error("Binary protocols over XmlHttpRequest not implementing advanced features are not supported.");const[n,r]=$(),o={[n]:r,...this.ie.headers},h={abortSignal:this.se.signal,headers:o,timeout:1e5,withCredentials:this.ie.withCredentials};s===B.Binary&&(h.responseType="arraybuffer");const c=`${t}&_=${Date.now()}`;this.u.log(e.Trace,`(LongPolling transport) polling: ${c}.`);const a=await this.$.get(c,h);200!==a.statusCode?(this.u.log(e.Error,`(LongPolling transport) Unexpected response code: ${a.statusCode}.`),this.oe=new i(a.statusText||"",a.statusCode),this.ne=!1):this.ne=!0,this.he=this.ce(this.re,h)}async ce(t,s){try{for(;this.ne;)try{const n=`${t}&_=${Date.now()}`;this.u.log(e.Trace,`(LongPolling transport) polling: ${n}.`);const r=await this.$.get(n,s);204===r.statusCode?(this.u.log(e.Information,"(LongPolling transport) Poll terminated by server."),this.ne=!1):200!==r.statusCode?(this.u.log(e.Error,`(LongPolling transport) Unexpected response code: ${r.statusCode}.`),this.oe=new i(r.statusText||"",r.statusCode),this.ne=!1):r.content?(this.u.log(e.Trace,`(LongPolling transport) data received. ${m(r.content,this.ie.logMessageContent)}.`),this.onreceive&&this.onreceive(r.content)):this.u.log(e.Trace,"(LongPolling transport) Poll timed out, reissuing.")}catch(t){this.ne?t instanceof n?this.u.log(e.Trace,"(LongPolling transport) Poll timed out, reissuing."):(this.oe=t,this.ne=!1):this.u.log(e.Trace,`(LongPolling transport) Poll errored after shutdown: ${t.message}`)}}finally{this.u.log(e.Trace,"(LongPolling transport) Polling complete."),this.pollAborted||this.ae()}}async send(t){return this.ne?b(this.u,"LongPolling",this.$,this.re,t,this.ie):Promise.reject(new Error("Cannot send until the transport is connected"))}async stop(){this.u.log(e.Trace,"(LongPolling transport) Stopping polling."),this.ne=!1,this.se.abort();try{await this.he,this.u.log(e.Trace,`(LongPolling transport) sending DELETE request to ${this.re}.`);const t={},[s,n]=$();t[s]=n;const r={headers:{...t,...this.ie.headers},timeout:this.ie.timeout,withCredentials:this.ie.withCredentials};let o;try{await this.$.delete(this.re,r)}catch(t){o=t}o?o instanceof i&&(404===o.statusCode?this.u.log(e.Trace,"(LongPolling transport) A 404 response was returned from sending a DELETE request."):this.u.log(e.Trace,`(LongPolling transport) Error sending a DELETE request: ${o}`)):this.u.log(e.Trace,"(LongPolling transport) DELETE request accepted.")}finally{this.u.log(e.Trace,"(LongPolling transport) Stop finished."),this.ae()}}ae(){if(this.onclose){let t="(LongPolling transport) Firing onclose event.";this.oe&&(t+=" Error: "+this.oe),this.u.log(e.Trace,t),this.onclose(this.oe)}}}class z{constructor(t,e,s,i){this.$=t,this.Zt=e,this.u=s,this.ie=i,this.onreceive=null,this.onclose=null}async connect(t,s){return w.isRequired(t,"url"),w.isRequired(s,"transferFormat"),w.isIn(s,B,"transferFormat"),this.u.log(e.Trace,"(SSE transport) Connecting."),this.re=t,this.Zt&&(t+=(t.indexOf("?")<0?"?":"&")+`access_token=${encodeURIComponent(this.Zt)}`),new Promise(((i,n)=>{let r,o=!1;if(s===B.Text){if(g.isBrowser||g.isWebWorker)r=new this.ie.EventSource(t,{withCredentials:this.ie.withCredentials});else{const e=this.$.getCookieString(t),s={};s.Cookie=e;const[i,n]=$();s[i]=n,r=new this.ie.EventSource(t,{withCredentials:this.ie.withCredentials,headers:{...s,...this.ie.headers}})}try{r.onmessage=t=>{if(this.onreceive)try{this.u.log(e.Trace,`(SSE transport) data received. ${m(t.data,this.ie.logMessageContent)}.`),this.onreceive(t.data)}catch(t){return void this.le(t)}},r.onerror=t=>{o?this.le():n(new Error("EventSource failed to connect. The connection could not be found on the server, either the connection ID is not present on the server, or a proxy is refusing/buffering the connection. If you have multiple servers check that sticky sessions are enabled."))},r.onopen=()=>{this.u.log(e.Information,`SSE connected to ${this.re}`),this.ue=r,o=!0,i()}}catch(t){return void n(t)}}else n(new Error("The Server-Sent Events transport only supports the 'Text' transfer format"))}))}async send(t){return this.ue?b(this.u,"SSE",this.$,this.re,t,this.ie):Promise.reject(new Error("Cannot send until the transport is connected"))}stop(){return this.le(),Promise.resolve()}le(t){this.ue&&(this.ue.close(),this.ue=void 0,this.onclose&&this.onclose(t))}}class V{constructor(t,e,s,i,n,r){this.u=s,this.Yt=e,this.de=i,this.fe=n,this.$=t,this.onreceive=null,this.onclose=null,this.pe=r}async connect(t,s){let i;return w.isRequired(t,"url"),w.isRequired(s,"transferFormat"),w.isIn(s,B,"transferFormat"),this.u.log(e.Trace,"(WebSockets transport) Connecting."),this.Yt&&(i=await this.Yt()),new Promise(((n,r)=>{let o;t=t.replace(/^http/,"ws");const h=this.$.getCookieString(t);let c=!1;if(g.isNode||g.isReactNative){const e={},[s,n]=$();e[s]=n,i&&(e[W.Authorization]=`Bearer ${i}`),h&&(e[W.Cookie]=h),o=new this.fe(t,void 0,{headers:{...e,...this.pe}})}else i&&(t+=(t.indexOf("?")<0?"?":"&")+`access_token=${encodeURIComponent(i)}`);o||(o=new this.fe(t)),s===B.Binary&&(o.binaryType="arraybuffer"),o.onopen=s=>{this.u.log(e.Information,`WebSocket connected to ${t}.`),this.we=o,c=!0,n()},o.onerror=t=>{let s=null;s="undefined"!=typeof ErrorEvent&&t instanceof ErrorEvent?t.error:"There was an error with the transport",this.u.log(e.Information,`(WebSockets transport) ${s}.`)},o.onmessage=t=>{if(this.u.log(e.Trace,`(WebSockets transport) data received. ${m(t.data,this.de)}.`),this.onreceive)try{this.onreceive(t.data)}catch(t){return void this.le(t)}},o.onclose=t=>{if(c)this.le(t);else{let e=null;e="undefined"!=typeof ErrorEvent&&t instanceof ErrorEvent?t.error:"WebSocket failed to connect. The connection could not be found on the server, either the endpoint may not be a SignalR endpoint, the connection ID is not present on the server, or there is a proxy blocking WebSockets. If you have multiple servers check that sticky sessions are enabled.",r(new Error(e))}}}))}send(t){return this.we&&this.we.readyState===this.fe.OPEN?(this.u.log(e.Trace,`(WebSockets transport) sending data. ${m(t,this.de)}.`),this.we.send(t),Promise.resolve()):Promise.reject("WebSocket is not in the OPEN state")}stop(){return this.we&&this.le(void 0),Promise.resolve()}le(t){this.we&&(this.we.onclose=()=>{},this.we.onmessage=()=>{},this.we.onerror=()=>{},this.we.close(),this.we=void 0),this.u.log(e.Trace,"(WebSockets transport) socket closed."),this.onclose&&(!this.ge(t)||!1!==t.wasClean&&1e3===t.code?t instanceof Error?this.onclose(t):this.onclose():this.onclose(new Error(`WebSocket closed with status code: ${t.code} (${t.reason||"no reason given"}).`)))}ge(t){return t&&"boolean"==typeof t.wasClean&&"number"==typeof t.code}}class K{constructor(t,s={}){var i;if(this.me=()=>{},this.features={},this.ye=1,w.isRequired(t,"url"),this.u=void 0===(i=s.logger)?new E(e.Information):null===i?f.instance:void 0!==i.log?i:new E(i),this.baseUrl=this.be(t),(s=s||{}).logMessageContent=void 0!==s.logMessageContent&&s.logMessageContent,"boolean"!=typeof s.withCredentials&&void 0!==s.withCredentials)throw new Error("withCredentials option was not a 'boolean' or 'undefined' value");s.withCredentials=void 0===s.withCredentials||s.withCredentials,s.timeout=void 0===s.timeout?1e5:s.timeout;let n=null,r=null;if(g.isNode){const t=require;n=t("ws"),r=t("eventsource")}g.isNode||"undefined"==typeof WebSocket||s.WebSocket?g.isNode&&!s.WebSocket&&n&&(s.WebSocket=n):s.WebSocket=WebSocket,g.isNode||"undefined"==typeof EventSource||s.EventSource?g.isNode&&!s.EventSource&&void 0!==r&&(s.EventSource=r):s.EventSource=EventSource,this.$=new O(s.httpClient||new H(this.u),s.accessTokenFactory),this.ut="Disconnected",this.dt=!1,this.ie=s,this.onreceive=null,this.onclose=null}async start(t){if(t=t||B.Binary,w.isIn(t,B,"transferFormat"),this.u.log(e.Debug,`Starting connection with transfer format '${B[t]}'.`),"Disconnected"!==this.ut)return Promise.reject(new Error("Cannot start an HttpConnection that is not in the 'Disconnected' state."));if(this.ut="Connecting",this.ve=this.yt(t),await this.ve,"Disconnecting"===this.ut){const t="Failed to start the HttpConnection before stop() was called.";return this.u.log(e.Error,t),await this.It,Promise.reject(new r(t))}if("Connected"!==this.ut){const t="HttpConnection.startInternal completed gracefully but didn't enter the connection into the connected state!";return this.u.log(e.Error,t),Promise.reject(new r(t))}this.dt=!0}send(t){return"Connected"!==this.ut?Promise.reject(new Error("Cannot send data if the connection is not in the 'Connected' State.")):(this.Ee||(this.Ee=new G(this.transport)),this.Ee.send(t))}async stop(t){return"Disconnected"===this.ut?(this.u.log(e.Debug,`Call to HttpConnection.stop(${t}) ignored because the connection is already in the disconnected state.`),Promise.resolve()):"Disconnecting"===this.ut?(this.u.log(e.Debug,`Call to HttpConnection.stop(${t}) ignored because the connection is already in the disconnecting state.`),this.It):(this.ut="Disconnecting",this.It=new Promise((t=>{this.me=t})),await this._t(t),void await this.It)}async _t(t){this.$e=t;try{await this.ve}catch(t){}if(this.transport){try{await this.transport.stop()}catch(t){this.u.log(e.Error,`HttpConnection.transport.stop() threw error '${t}'.`),this.Ce()}this.transport=void 0}else this.u.log(e.Debug,"HttpConnection.transport is undefined in HttpConnection.stop() because start() failed.")}async yt(t){let s=this.baseUrl;this.Yt=this.ie.accessTokenFactory,this.$.Yt=this.Yt;try{if(this.ie.skipNegotiation){if(this.ie.transport!==F.WebSockets)throw new Error("Negotiation can only be skipped when using the WebSocket transport directly.");this.transport=this.Se(F.WebSockets),await this.ke(s,t)}else{let e=null,i=0;do{if(e=await this.Pe(s),"Disconnecting"===this.ut||"Disconnected"===this.ut)throw new r("The connection was stopped during negotiation.");if(e.error)throw new Error(e.error);if(e.ProtocolVersion)throw new Error("Detected a connection attempt to an ASP.NET SignalR Server. This client only supports connecting to an ASP.NET Core SignalR Server. See https://aka.ms/signalr-core-differences for details.");if(e.url&&(s=e.url),e.accessToken){const t=e.accessToken;this.Yt=()=>t,this.$.Zt=t,this.$.Yt=void 0}i++}while(e.url&&i<100);if(100===i&&e.url)throw new Error("Negotiate redirection limit exceeded.");await this.Te(s,this.ie.transport,e,t)}this.transport instanceof J&&(this.features.inherentKeepAlive=!0),"Connecting"===this.ut&&(this.u.log(e.Debug,"The HttpConnection connected successfully."),this.ut="Connected")}catch(t){return this.u.log(e.Error,"Failed to start the connection: "+t),this.ut="Disconnected",this.transport=void 0,this.me(),Promise.reject(t)}}async Pe(t){const s={},[n,r]=$();s[n]=r;const o=this.Ie(t);this.u.log(e.Debug,`Sending negotiation request: ${o}.`);try{const t=await this.$.post(o,{content:"",headers:{...s,...this.ie.headers},timeout:this.ie.timeout,withCredentials:this.ie.withCredentials});if(200!==t.statusCode)return Promise.reject(new Error(`Unexpected status code returned from negotiate '${t.statusCode}'`));const e=JSON.parse(t.content);return(!e.negotiateVersion||e.negotiateVersion<1)&&(e.connectionToken=e.connectionId),e.useStatefulReconnect&&!0!==this.ie._e?Promise.reject(new a("Client didn't negotiate Stateful Reconnect but the server did.")):e}catch(t){let s="Failed to complete negotiation with the server: "+t;return t instanceof i&&404===t.statusCode&&(s+=" Either this is not a SignalR endpoint or there is a proxy blocking the connection."),this.u.log(e.Error,s),Promise.reject(new a(s))}}He(t,e){return e?t+(-1===t.indexOf("?")?"?":"&")+`id=${e}`:t}async Te(t,s,i,n){let o=this.He(t,i.connectionToken);if(this.De(s))return this.u.log(e.Debug,"Connection was provided an instance of ITransport, using that directly."),this.transport=s,await this.ke(o,n),void(this.connectionId=i.connectionId);const h=[],a=i.availableTransports||[];let u=i;for(const i of a){const a=this.Re(i,s,n,!0===(null==u?void 0:u.useStatefulReconnect));if(a instanceof Error)h.push(`${i.transport} failed:`),h.push(a);else if(this.De(a)){if(this.transport=a,!u){try{u=await this.Pe(t)}catch(t){return Promise.reject(t)}o=this.He(t,u.connectionToken)}try{return await this.ke(o,n),void(this.connectionId=u.connectionId)}catch(t){if(this.u.log(e.Error,`Failed to start the transport '${i.transport}': ${t}`),u=void 0,h.push(new c(`${i.transport} failed: ${t}`,F[i.transport])),"Connecting"!==this.ut){const t="Failed to select transport before stop() was called.";return this.u.log(e.Debug,t),Promise.reject(new r(t))}}}}return h.length>0?Promise.reject(new l(`Unable to connect to the server with any of the available transports. ${h.join(" ")}`,h)):Promise.reject(new Error("None of the transports supported by the client are supported by the server."))}Se(t){switch(t){case F.WebSockets:if(!this.ie.WebSocket)throw new Error("'WebSocket' is not supported in your environment.");return new V(this.$,this.Yt,this.u,this.ie.logMessageContent,this.ie.WebSocket,this.ie.headers||{});case F.ServerSentEvents:if(!this.ie.EventSource)throw new Error("'EventSource' is not supported in your environment.");return new z(this.$,this.$.Zt,this.u,this.ie);case F.LongPolling:return new J(this.$,this.u,this.ie);default:throw new Error(`Unknown transport: ${t}.`)}}ke(t,e){return this.transport.onreceive=this.onreceive,this.features.reconnect?this.transport.onclose=async s=>{let i=!1;if(this.features.reconnect){try{this.features.disconnected(),await this.transport.connect(t,e),await this.features.resend()}catch{i=!0}i&&this.Ce(s)}else this.Ce(s)}:this.transport.onclose=t=>this.Ce(t),this.transport.connect(t,e)}Re(t,s,i,n){const r=F[t.transport];if(null==r)return this.u.log(e.Debug,`Skipping transport '${t.transport}' because it is not supported by this client.`),new Error(`Skipping transport '${t.transport}' because it is not supported by this client.`);if(!function(t,e){return!t||0!=(e&t)}(s,r))return this.u.log(e.Debug,`Skipping transport '${F[r]}' because it was disabled by the client.`),new h(`'${F[r]}' is disabled by the client.`,r);if(!(t.transferFormats.map((t=>B[t])).indexOf(i)>=0))return this.u.log(e.Debug,`Skipping transport '${F[r]}' because it does not support the requested transfer format '${B[i]}'.`),new Error(`'${F[r]}' does not support ${B[i]}.`);if(r===F.WebSockets&&!this.ie.WebSocket||r===F.ServerSentEvents&&!this.ie.EventSource)return this.u.log(e.Debug,`Skipping transport '${F[r]}' because it is not supported in your environment.'`),new o(`'${F[r]}' is not supported in your environment.`,r);this.u.log(e.Debug,`Selecting transport '${F[r]}'.`);try{return this.features.reconnect=r===F.WebSockets?n:void 0,this.Se(r)}catch(t){return t}}De(t){return t&&"object"==typeof t&&"connect"in t}Ce(t){if(this.u.log(e.Debug,`HttpConnection.stopConnection(${t}) called while in state ${this.ut}.`),this.transport=void 0,t=this.$e||t,this.$e=void 0,"Disconnected"!==this.ut){if("Connecting"===this.ut)throw this.u.log(e.Warning,`Call to HttpConnection.stopConnection(${t}) was ignored because the connection is still in the connecting state.`),new Error(`HttpConnection.stopConnection(${t}) was called while the connection is still in the connecting state.`);if("Disconnecting"===this.ut&&this.me(),t?this.u.log(e.Error,`Connection disconnected with error '${t}'.`):this.u.log(e.Information,"Connection disconnected."),this.Ee&&(this.Ee.stop().catch((t=>{this.u.log(e.Error,`TransportSendQueue.stop() threw error '${t}'.`)})),this.Ee=void 0),this.connectionId=void 0,this.ut="Disconnected",this.dt){this.dt=!1;try{this.onclose&&this.onclose(t)}catch(s){this.u.log(e.Error,`HttpConnection.onclose(${t}) threw error '${s}'.`)}}}else this.u.log(e.Debug,`Call to HttpConnection.stopConnection(${t}) was ignored because the connection is already in the disconnected state.`)}be(t){if(0===t.lastIndexOf("https://",0)||0===t.lastIndexOf("http://",0))return t;if(!g.isBrowser)throw new Error(`Cannot resolve '${t}'.`);const s=window.document.createElement("a");return s.href=t,this.u.log(e.Information,`Normalizing '${t}' to '${s.href}'.`),s.href}Ie(t){const e=new URL(t);e.pathname.endsWith("/")?e.pathname+="negotiate":e.pathname+="/negotiate";const s=new URLSearchParams(e.searchParams);return s.has("negotiateVersion")||s.append("negotiateVersion",this.ye.toString()),s.has("useStatefulReconnect")?"true"===s.get("useStatefulReconnect")&&(this.ie._e=!0):!0===this.ie._e&&s.append("useStatefulReconnect","true"),e.search=s.toString(),e.toString()}}class G{constructor(t){this.xe=t,this.Ae=[],this.Ue=!0,this.Le=new Q,this.Ne=new Q,this.qe=this.Me()}send(t){return this.je(t),this.Ne||(this.Ne=new Q),this.Ne.promise}stop(){return this.Ue=!1,this.Le.resolve(),this.qe}je(t){if(this.Ae.length&&typeof this.Ae[0]!=typeof t)throw new Error(`Expected data to be of type ${typeof this.Ae} but was of type ${typeof t}`);this.Ae.push(t),this.Le.resolve()}async Me(){for(;;){if(await this.Le.promise,!this.Ue){this.Ne&&this.Ne.reject("Connection stopped.");break}this.Le=new Q;const t=this.Ne;this.Ne=void 0;const e="string"==typeof this.Ae[0]?this.Ae.join(""):G.We(this.Ae);this.Ae.length=0;try{await this.xe.send(e),t.resolve()}catch(e){t.reject(e)}}}static We(t){const e=t.map((t=>t.byteLength)).reduce(((t,e)=>t+e)),s=new Uint8Array(e);let i=0;for(const e of t)s.set(new Uint8Array(e),i),i+=e.byteLength;return s.buffer}}class Q{constructor(){this.promise=new Promise(((t,e)=>[this.j,this.Oe]=[t,e]))}resolve(){this.j()}reject(t){this.Oe(t)}}class Y{constructor(){this.name="json",this.version=2,this.transferFormat=B.Text}parseMessages(t,s){if("string"!=typeof t)throw new Error("Invalid input for JSON hub protocol. Expected a string.");if(!t)return[];null===s&&(s=f.instance);const i=D.parse(t),n=[];for(const t of i){const i=JSON.parse(t);if("number"!=typeof i.type)throw new Error("Invalid payload.");switch(i.type){case x.Invocation:this.U(i);break;case x.StreamItem:this.Fe(i);break;case x.Completion:this.Be(i);break;case x.Ping:case x.Close:break;case x.Ack:this.Xe(i);break;case x.Sequence:this.Je(i);break;default:s.log(e.Information,"Unknown message type '"+i.type+"' ignored.");continue}n.push(i)}return n}writeMessage(t){return D.write(JSON.stringify(t))}U(t){this.ze(t.target,"Invalid payload for Invocation message."),void 0!==t.invocationId&&this.ze(t.invocationId,"Invalid payload for Invocation message.")}Fe(t){if(this.ze(t.invocationId,"Invalid payload for StreamItem message."),void 0===t.item)throw new Error("Invalid payload for StreamItem message.")}Be(t){if(t.result&&t.error)throw new Error("Invalid payload for Completion message.");!t.result&&t.error&&this.ze(t.error,"Invalid payload for Completion message."),this.ze(t.invocationId,"Invalid payload for Completion message.")}Xe(t){if("number"!=typeof t.sequenceId)throw new Error("Invalid SequenceId for Ack message.")}Je(t){if("number"!=typeof t.sequenceId)throw new Error("Invalid SequenceId for Sequence message.")}ze(t,e){if("string"!=typeof t||""===t)throw new Error(e)}}const Z={trace:e.Trace,debug:e.Debug,info:e.Information,information:e.Information,warn:e.Warning,warning:e.Warning,error:e.Error,critical:e.Critical,none:e.None};class tt{configureLogging(t){if(w.isRequired(t,"logging"),void 0!==t.log)this.logger=t;else if("string"==typeof t){const e=function(t){const e=Z[t.toLowerCase()];if(void 0!==e)return e;throw new Error(`Unknown log level: ${t}`)}(t);this.logger=new E(e)}else this.logger=new E(t);return this}withUrl(t,e){return w.isRequired(t,"url"),w.isNotEmpty(t,"url"),this.url=t,this.httpConnectionOptions="object"==typeof e?{...this.httpConnectionOptions,...e}:{...this.httpConnectionOptions,transport:e},this}withHubProtocol(t){return w.isRequired(t,"protocol"),this.protocol=t,this}withAutomaticReconnect(t){if(this.reconnectPolicy)throw new Error("A reconnectPolicy has already been set.");return t?Array.isArray(t)?this.reconnectPolicy=new j(t):this.reconnectPolicy=t:this.reconnectPolicy=new j,this}withServerTimeout(t){return w.isRequired(t,"milliseconds"),this.Ve=t,this}withKeepAliveInterval(t){return w.isRequired(t,"milliseconds"),this.Ke=t,this}withStatefulReconnect(t){return void 0===this.httpConnectionOptions&&(this.httpConnectionOptions={}),this.httpConnectionOptions._e=!0,this.Y=null==t?void 0:t.bufferSize,this}build(){const t=this.httpConnectionOptions||{};if(void 0===t.logger&&(t.logger=this.logger),!this.url)throw new Error("The 'HubConnectionBuilder.withUrl' method must be called before building the connection.");const e=new K(this.url,t);return q.create(e,this.logger||f.instance,this.protocol||new Y,this.reconnectPolicy,this.Ve,this.Ke,this.Y)}}return Uint8Array.prototype.indexOf||Object.defineProperty(Uint8Array.prototype,"indexOf",{value:Array.prototype.indexOf,writable:!0}),Uint8Array.prototype.slice||Object.defineProperty(Uint8Array.prototype,"slice",{value:function(t,e){return new Uint8Array(Array.prototype.slice.call(this,t,e))},writable:!0}),Uint8Array.prototype.forEach||Object.defineProperty(Uint8Array.prototype,"forEach",{value:Array.prototype.forEach,writable:!0}),s})(),"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.signalR=e():t.signalR=e();


    // Store signalR in your namespace
    window.signalR = global.signalR;
 
    // Restore original globals
    if(global !== window) {
        global.signalR = noConflict;
    }
    global.module = originalModule;
    global.exports = originalExports;
    global.define = originalDefine;
    if (originalDefine) {
        global.define.amd = originalDefineAmd;
    }
    
})(this);;
_insideGraph.registerModule("realtime", function () {

    function getSocialHubRemoteCalls(hub) {
        return {
            acceptCoBrowseRequest: function () {
                return hub.invoke.apply(hub, ["AcceptCoBrowseRequest"]);
            },

            AcceptControlMode: function (chatid) {
                return hub.invoke.apply(hub, ["AcceptControlMode", chatid]);
            },

            RejectControlMode: function (chatid) {
                return hub.invoke.apply(hub, ["RejectControlMode", chatid]);
            },
            active: function () {
                return hub.invoke.apply(hub, ["Active"]);
            },

            chat: function (chatid, text, clickedOnPopupEventId, operatorid, videoFeedAssignment) {
                return hub.invoke("Chat", chatid, text, clickedOnPopupEventId || 0, operatorid || 0, videoFeedAssignment || false);
            },

            chatData: function (chatid, data, notifyToVisitor) {
                return hub.invoke.apply(hub, ["ChatData", chatid, data, notifyToVisitor || false]);
            },

            chatAction: function (action) {
                return hub.invoke.apply(hub, ["ChatAction", action]);
            },

            chatWithAttachments: function (chatid, text, fileids, clickedOnPopupEventId) {
                return hub.invoke.apply(hub, ["ChatWithAttachments", chatid, text, fileids, clickedOnPopupEventId || 0]);
            },

            closeCoBrowseSession: function () {
                return hub.invoke.apply(hub, ["CloseCoBrowseSession"]);
            },

            coBrowseNotSupported: function () {
                return hub.invoke.apply(hub, ["CoBrowseNotSupported"]);
            },

            coBrowseRequestState: function () {
                return hub.invoke.apply(hub, ["CoBrowseRequestState"]);
            },
            
            coBrowseRequestData: function () {
                return hub.invoke.apply(hub, ["CoBrowseRequestData"]);
            },

            coBrowseSendToOperator: function (data) {
                return hub.invoke.apply(hub, ["CoBrowseSendToOperator", data]);
            },

            externalChat: function (chatid, text, platform, platformKey) {
                return hub.invoke.apply(hub, ["ExternalChat", chatid, text, platform, platformKey]);
            },

            getCurrentView: function () {
                return hub.invoke.apply(hub, ["GetCurrentView"]);
            },

            inactive: function () {
                return hub.invoke.apply(hub, ["Inactive"]);
            },

            keepAlive: function () {
                return hub.invoke.apply(hub, ["KeepAlive"]);
            },

            loadChat: function (chatid) {
                return hub.invoke.apply(hub, ["LoadChat", chatid]);
            },

            rejectCoBrowseRequest: function () {
                return hub.invoke.apply(hub, ["RejectCoBrowseRequest"]);
            },

            relatedIntents: function (intentId, conversationId) {
                return hub.invoke.apply(hub, ["RelatedIntents", intentId, conversationId]);
            },

            startChat: function (text) {
                return hub.invoke.apply(hub, ["StartChat", text]);
            },

            stopChat: function (chatid) {
                return hub.invoke.apply(hub, ["StopChat", chatid]);
            },

            unstick: function (stickyid) {
                return hub.invoke.apply(hub, ["Unstick", stickyid]);
            },

            updateCoBrowseSession: function (data) {
                return hub.invoke.apply(hub, ["UpdateCoBrowseSession", data]);
            },

            updateDeliveryStatus: function (messageids, conversationid, status, message) {
                return hub.invoke.apply(hub, ["updateDeliveryStatus", messageids, conversationid, status, message]);
            },
            
            TriggerTimeOnPageEvent: function (eventId, viewId) {
                return hub.invoke.apply(hub, ["TriggerTimeOnPageEvent", eventId, viewId]);
            },

            logVideoFeedAction: function (obj) {
                return hub.invoke.apply(hub, ["LogVideoFeedAction", obj]);
            }
        };
    };

    (function ($, window) {
        var _callback = {};
        var _prebindings = {};
        var _queueEvents = true;
        var _eventQueue = [];
        var _requestQueue = [];
        var _init = [];
        var _deinit = [];

        function debugLog(...message) {
            if (typeof console !== 'undefined' && typeof console.debug === 'function') {
                console.debug(...message);
            }
        }

        try {
            var hub = new signalR.HubConnectionBuilder()
                .withUrl(_insideSocialUrl + "insideSocialHub", {
                    skipNegotiation: true,
                    logMessageContent: true,
                    transport: signalR.HttpTransportType.WebSockets,
                    accessTokenFactory: function () {
                        var tracker = _insideGraph.current || {};
                        return JSON.stringify({
                            account: tracker.account || "",
                            pid: _insideGraph.pid || "",
                            accessKey: _insideGraph.accessKey || "",
                            accessCheck: _insideGraph.accessCheck || "",
                            noCookie: tracker.noCookie || false
                        });
                    }
                })
                .configureLogging(signalR.LogLevel.Information)
                .build();

            hub.client = {
                doEvent: function (name, data, stickyid) {
                    if (_queueEvents && name != "connected" && name != "disconnected") {
                        _eventQueue.push({ "name": name, "data": data, "stickyid": stickyid });
                        return;
                    }
                    if (!_insideLive && typeof (console) != "undefined" && typeof (console.log) != "undefined") {
                        console.log("[INSIDE]: doEvent :: " + name + " :: " + (typeof (stickyid) != "undefined" ? stickyid : "") + " :: ", data);
                    }

                    var prebinds = _prebindings[name];
                    if (prebinds) {
                        delete _prebindings[name];
                        var promises = [];
                        for (var i = 0; i < prebinds.length; i++) {
                            promises.push(prebinds[i]());
                        }
                        Promise.all(promises).then(function () {
                            handleCallbacks(name, data, stickyid);
                        });
                    } else {
                        handleCallbacks(name, data, stickyid);
                    }

                }
            };

            hub.server = getSocialHubRemoteCalls(hub);

            hub.init = function (callback) {
                _init[_init.length] = callback;
                hubStarted();
            };

            hub.deinit = function (callback) {
                _deinit[_deinit.length] = callback;
            };

            hub.on("doEvent", hub.client.doEvent);

            hub.bind = function (name, callback) {
                if (!_insideLive && typeof (console) != "undefined" && typeof (console.log) != "undefined") {
                    console.log("[INSIDE]: bind :: " + name);
                }
                if (typeof callback == "function") {
                    if (!_callback[name])
                        _callback[name] = [];
                    _callback[name][_callback[name].length] = callback;
                }
            };

            hub.prebindModule = function (name, module, source) {
                _prebindings[name] = _prebindings[name] || [];
                _prebindings[name].push(function () {
                    return _insideGraph.loadModule(module, source);
                });
            };

            hub.unbind = function (name, callback) {
                if (typeof _callback[name] != "undefined" && typeof callback == "function") {
                    var index = _callback[name].indexOf(callback);
                    if (index != -1) {
                        if (name === "chat") debugLog("unbind => chat event unbinded");
                        _callback[name].splice(index, 1);
                    }
                }
            };

            hub.unbindAll = function (name) {
                if (name === "chat") debugLog("unbindAll => chat event unbinded");
                if (typeof _callback[name] != "undefined") {
                    _callback[name] = [];
                }
            };

            hub.clearAllEvents = function () {
                _callback = {};
            };

            function handleCallbacks(name, data, stickyid) {
                var eventCallbackList = _callback[name];
                if (eventCallbackList) {
                    for (var i = 0; i < eventCallbackList.length; i++)
                        eventCallbackList[i](data, stickyid);
                } else {
                    console.trace("Pushing to event queue...");
                    _eventQueue.push({ "name": name, "data": data, "stickyid": stickyid });
                }
            }

            hub.flushQueue = function () {
                _queueEvents = false;
                var events = _eventQueue;
                _eventQueue = [];
                hub.client.doEvents(events);
            };

            hub.client.doEvents = function (events) {
                for (var i = 0; i < events.length; i++) {
                    hub.client.doEvent(events[i].name, events[i].data, events[i].stickyid);
                }
            };
            hub.on("doEvents", hub.client.doEvents);
            hub.client.stopInside = function () {
                hub.stop();
                hub.client.doEvent("disconnected", null);
                for (var i = 0; i < _deinit.length; i++)
                    _deinit[i]();
                _deinit = [];
            };

            hub.setCookie = function (cName, value) {
                var exdate = new Date();
                exdate.setDate(exdate.getDate() + 365 * 50);
                var c_value = escape(value) + ";expires=" + exdate.toUTCString() + ";path=/";
                document.cookie = cName + "=" + c_value;
            };

            // Checks whether the string is null or whitespace
            function isNullOrWhiteSpace(str) {
                return (!str || str.length === 0 || /^\s*$/.test(str));
            }

            hub.ga = function (event) {
                if (typeof (event) == "object" && !isNullOrWhiteSpace(event.category) && !isNullOrWhiteSpace(event.action))
                {
                    if (_insideGraph.hasEvent("googleAnalytics")) {
                        hub.unbind("ga", hub.ga);
                        if(!_callback["ga"] || !_callback["ga"].length) {
                            hub.bind("ga", function (event) {
                                _insideGraph.doEvent("googleAnalytics", event);
                            });
                        }
                        _insideGraph.doEvent("googleAnalytics", event);
                    } else {
                        if (typeof (gtag) == "function")
                            gtag('event', event.action, {
                                'event_category': event.category,
                                'event_label': event.label,
                                'value': event.value,
                                'non_interaction': true
                            });
                        if (typeof (ga) == "function")
                            ga('send', 'event', event.category, event.action, event.label, event.value, true);
                        if (typeof (_gaq) == "object")
                            _gaq.push('_trackEvent', event.category, event.action, event.label, event.value, true);
                        if (typeof (google_tag_manager) != "undefined" && typeof (dataLayer) == "object") {
                            dataLayer.push({
                                "event": "insideEvent",
                                "eventCategory": event.category,
                                "eventAction": event.action,
                                "eventLabel": event.label,
                                "eventValue": event.value,
                                "eventNI": true
                            });
                        }
                    }
                }
            };

            hub.bind("ga", hub.ga);

            hub.resetting = false;
            hub.bind("reset", function () {
                if (hub.resetting) {
                    console.error("Cannot reset the connection when a reset it already in progress");
                    return;
                }

                hub.resetting = true;
                _insideGraph.reset();
            });

            hub.bind("connected", function () {
                hub.resetting = false;
            });

            hub.starts = 0;
            hub.videoChat = false;
            var tryingToReconnect = false;
            var disconnected = false;

            hub.onclose(function (change) {
                hub.resetting = false;
                if (hub.state === signalR.HubConnectionState.Reconnecting) {
                    tryingToReconnect = true;
                }

                hub.client.doEvent("disconnected", tryingToReconnect);
                if (!disconnected) {
                    disconnected = true;
                    debugLog("disconnected");
                    if (hub.videoChat) {
                        setTimeout(function () {
                            startHubSafely();
                        }, 5000);
                    }
                }
            });

            // Safe start function that checks state before starting
            function startHubSafely() {
                if (hub.state === signalR.HubConnectionState.Disconnected) {
                    debugLog("Starting social hub connection...");
                    hub.start().then(function() {
                        hubStarted();
                    }).catch(function(err) {
                        console.error("Failed to start social hub connection:", err);
                        // Retry after a delay if still disconnected
                        setTimeout(function() {
                            if (hub.state === signalR.HubConnectionState.Disconnected) {
                                startHubSafely();
                            }
                        }, 5000);
                    });
                } else {
                    debugLog("Social hub connection start skipped - current state:", hub.state);
                }
            }

            hub.startHub = function (callback) {
                debugLog("startHub called, current state:", hub.state);
                
                if (hub.state === signalR.HubConnectionState.Connected) {
                    // Already connected, just run callback
                    if (typeof (callback) == "function") {
                        callback();
                    }
                    return;
                }
                
                if (hub.state === signalR.HubConnectionState.Connecting) {
                    // Already connecting, wait for it to complete
                    var checkConnection = function() {
                        if (hub.state === signalR.HubConnectionState.Connected) {
                            if (typeof (callback) == "function") {
                                callback();
                            }
                        } else if (hub.state === signalR.HubConnectionState.Disconnected) {
                            // Connection failed, try again
                            startHubWithCallback(callback);
                        } else {
                            // Still connecting, check again
                            setTimeout(checkConnection, 500);
                        }
                    };
                    setTimeout(checkConnection, 500);
                    return;
                }
                
                if (hub.state !== signalR.HubConnectionState.Disconnected) {
                    // Stop the connection first
                    hub.stop().then(function() {
                        startHubWithCallback(callback);
                    }).catch(function(err) {
                        console.error("Error stopping hub:", err);
                        // Wait a bit then try to start anyway
                        setTimeout(function() {
                            startHubWithCallback(callback);
                        }, 2000);
                    });
                } else {
                    startHubWithCallback(callback);
                }
            };

            function startHubWithCallback(callback) {
                if (!_insideLive)
                    hub.logging = true;

                if (hub.state === signalR.HubConnectionState.Disconnected) {
                    hub.start().then(function () {
                        hubStarted();
                        if (typeof (callback) == "function") {
                            callback();
                        }
                    }).catch(function(err) {
                        console.error("Failed to start hub with callback:", err);
                        // Retry after delay if still disconnected
                        setTimeout(function() {
                            if (hub.state === signalR.HubConnectionState.Disconnected) {
                                startHubWithCallback(callback);
                            }
                        }, 3000);
                    });
                } else {
                    debugLog("Cannot start hub with callback - state is:", hub.state);
                }
            }

            function hubStarted() {
                if ($.inside.starts == 0) {
                    $(window).on('beforeunload', function () {
                        if (!hub.isDisconnected() && !(typeof insideWebApp != "undefined" && insideWebApp))
                            hub.stop();
                    });
                    _insideGraph.doEvent("onconnected", true);
                }
                for (var i = 0; i < _init.length; i++)
                    _init[i]();
                _init = [];
                $.inside.starts++;
                hub.videoChat = false;

                _insideGraph.setState(2);
            }

            hub.keepAlive = function () {
                if (hub.isConnected())
                    hub.server.keepAlive();
            };

            hub.isConnected = function () {
                return hub.state == signalR.HubConnectionState.Connected;
            };

            hub.isDisconnected = function () {
                return hub.state == signalR.HubConnectionState.Disconnected;
            };

            hub.isEnabled = function (func) {
                var temp = $.inArray(func, _insideGraph.enabled);
                return typeof (temp) != "undefined" && temp != -1;
            };

            hub.sendCall = function (methodName, params, doneCallback, failCallback, deferCallback) {
                if ($.inside.isConnected()) {
                    hub.invokeServerMethod(methodName, params, doneCallback, failCallback);
                } else {
                    if (typeof (deferCallback) == "function") {
                        deferCallback();
                    }
                    _requestQueue.push({ methodName: methodName, params: params, doneCallback: doneCallback, failCallback: failCallback });
                    $.inside.startHub(function () {
                        for (var i = 0; i < _requestQueue.length; i++) {
                            hub.invokeServerMethod(_requestQueue[i].methodName, _requestQueue[i].params, _requestQueue[i].doneCallback, _requestQueue[i].failCallback);
                        }
                        _requestQueue = [];
                    });
                }
            };

            hub.invokeServerMethod = function (methodName, params, doneCallback, failCallback) {
                hub.server[methodName].apply(hub, params).then(function (response) {
                    if (typeof (doneCallback) == "function") doneCallback(response);
                }).catch(function (response) {
                    if (typeof (failCallback) == "function") failCallback(response);
                });
            };

            hub.reset = function () {
                tryingToReconnect = false;
                hub.videoChat = false;
                hub.stop();
            }

            hub.isDisconnected = function () {
                return hub.state === signalR.HubConnectionState.Disconnected;
            }

            var lastViewId = null;
            var timeOnPageTimeouts = [];
            var timeOnPageBuffer = {};

            function processTimeOnPageEvent(data) {
                var currentTimeOnPage = _insideGraph.getTimeOnPage();
                var targetTimeOnPage = data.timeOnPage * 1000;

                if (currentTimeOnPage > targetTimeOnPage) {
                    hub.sendCall("TriggerTimeOnPageEvent", [data.eventId, data.viewId]);
                    return;
                }

                var timeoutId = setTimeout(function () {
                    hub.sendCall("TriggerTimeOnPageEvent", [data.eventId, data.viewId]);
                    timeOnPageTimeouts.splice(timeOnPageTimeouts.indexOf(timeoutId), 1);
                }, targetTimeOnPage - currentTimeOnPage);

                timeOnPageTimeouts.push(timeoutId);
            }

            hub.bind("registerTimeOnPageEvent", function (data) {
                if (data.viewId !== _insideGraph.viewId) {
                    timeOnPageBuffer[data.viewId] = data;
                    return;
                }

                processTimeOnPageEvent(data);
            });

            _insideGraph.bind("view", function () {
                if (lastViewId != _insideGraph.viewId) {
                    lastViewId = _insideGraph.viewId;
                    var timeouts = timeOnPageTimeouts;
                    timeOnPageTimeouts = [];
                    for (var i = 0; i < timeouts.length; i++) {
                        clearTimeout(timeouts[i]);
                    }
                }

                if (timeOnPageBuffer[lastViewId]) {
                    var data = timeOnPageBuffer[lastViewId];
                    delete timeOnPageBuffer[lastViewId];
                    processTimeOnPageEvent(data);
                }
            });

            $.inside = hub;
        }
        catch (err) {
            console.error("Error loading hub", err);
        }
        


    })(_insideGraph.jQuery, window);

    (function($,window){
        var _keepAliveTimeout = 120000;  // 2 minutes
        var _idleTimeout = 180000;	     // 3 minutes
        var _awayTimeout = 300000;	     // 5 minutes
	 
        var _idleNow = false;
        var _idleTimestamp = null;
        var _idleTimer = null;
        var _awayNow = false;
        var _awayTimestamp = null;
        var _awayTimer = null;
    
        $.inside.bind("poke", function() { _active(true); });
	
        var agent = window.navigator.userAgent.toLowerCase();
        if(agent.indexOf("ipad") != -1){
            var lastTime = new Date();
            setTimeout(checkTime, 500);
        }

        var _keepAliveTimer = setTimeout(keepAlive, _keepAliveTimeout);
        function keepAlive(){
            $.inside.keepAlive();
            _keepAliveTimer = setTimeout(keepAlive, _keepAliveTimeout);
        }
    
        function checkTime(){		
            var dt = (new Date()).valueOf() - lastTime.valueOf();
            if(dt > 300000 && $.inside.connection){
                $.inside.stop();
            }
            if(dt > 1000)
            {
                _idleNow = true;
                _active();
            }
            lastTime = new Date();
            setTimeout(checkTime, 500);
        }
		
        function setIdleTimeout(ms) {
            _idleTimeout = ms;
            _idleTimestamp = new Date().getTime() + ms;
            if (_idleTimer != null)
                clearTimeout(_idleTimer);
            _idleTimer = setTimeout(_makeIdle, ms + 50);
        }
	 
        function setAwayTimeout(ms) {
            _awayTimeout = ms;
            _awayTimestamp = new Date().getTime() + ms;
            if (_awayTimer != null)
                clearTimeout(_awayTimer);
            _awayTimer = setTimeout(_makeAway, ms + 50);
        }
	 
        function _makeIdle(override) {
            if (_idleNow)
                return;
			
            if (!override)
            {
                var t = new Date().getTime();
                if (t < _idleTimestamp) {
                    _idleTimer = setTimeout(_makeIdle, _idleTimestamp - t + 50);
                    return;
                }
            }
            if(_idleTimer != null)
                clearTimeout (_idleTimer);
		
            _idleNow = true;
            if ($.inside.isConnected()) {

                $.inside.server.inactive();
                _insideGraph.doEvent("idle", null);
            }
        }
	 
        function _makeAway(override)
        {
            if (_awayNow)
                return;

            if (!override)
            {
                var t = new Date().getTime();
                if (t < _awayTimestamp || override) {
                    _awayTimer = setTimeout(_makeAway, _awayTimestamp - t + 50);
                    return;
                }
            }
            if(_awayTimer != null)
                clearTimeout (_awayTimer);
			
            if (_keepAliveTimer != null)
                clearTimeout(_keepAliveTimer);
        
            _awayNow = true;
            $.inside.stop();
        }
	 
        function insideChatFrameInFocus() {
            if(typeof insideChatPane == "undefined" || typeof insideChatPane.frame == "undefined") {
                return false;
            }
            return insideChatPane.frame.contentWindow.document.hasFocus();
        }
	 
        function _active(data)
        {
            var poke = false;
            if (typeof(data) === "boolean")
                poke = data;
			
            if (!poke && (_idleNow || _awayNow)) {
                if (typeof(window.document.hasFocus) != "undefined" && !window.document.hasFocus() && !window.top.document.hasFocus() && !insideChatFrameInFocus()) {
                    return;
                }
            }
	
            var t = new Date().getTime();
            _idleTimestamp = t + _idleTimeout;
            _awayTimestamp = t + _awayTimeout;
	 
            try	{
                if (_keepAliveTimer == null)
                    _keepAliveTimer = setTimeout(keepAlive, _keepAliveTimeout);
            
                if (_awayNow) {
                    setAwayTimeout(_awayTimeout);
                    $.inside.startHub();
                }

                if (_idleNow) {
                    setIdleTimeout(_idleTimeout);
                    if (!_awayNow)
                    {
                        if (!$.inside.isConnected())
                            $.inside.startHub();
                        else {
                            $.inside.server.active().then(function(connected){
                                if (!connected)
                                    $.inside.startHub();
                            }).catch(function(err) {
                                console.error("Error calling active():", err);
                                $.inside.startHub();
                            });
                        }
                    }
                }
                if (poke)
                    $.inside.keepAlive();
            } catch(err) { }

            _idleNow = false;
            _awayNow = false;
        }
	
        _inside._onFocusChange = _onchange;
        function _onchange(evt)
        {
            evt = evt || window.event;
        
            if (evt.type == "blur" || evt.type == "focusout" || evt.type == "pagehide") {
                if(window.document.hasFocus() || insideChatFrameInFocus()) {
                    return;
                }
                _makeIdle(true);
            } else {
                _active();
            }
        }
    
        function getDevice() {
            var userAgent = navigator.userAgent.toLowerCase();
            $.browser.chrome = /chrome/.test(navigator.userAgent.toLowerCase());
				
            var agent = window.navigator.userAgent.toLowerCase();
            var iPod = (agent.indexOf("ipod") > 0);
            var iPhone = (agent.indexOf("iphone") > 0);
            var iPad = (agent.indexOf("ipad") > 0);
            var android = ((agent.indexOf("android") > 0) && (agent.indexOf("mobile") > 0));
            var androidTablet = !android && (agent.indexOf("android") > 0);
            var webOS = (agent.indexOf("webos") > 0);
            var blackBerry = (agent.indexOf("blackberry") > 0);
            var rimTablet = (agent.indexOf("rimtablet") > 0);
            var device = 1;
            if(iPod || iPhone || android || webOS || blackBerry){
                device = 2;
            } else if (iPad || rimTablet || androidTablet){
                device = 3;
            }
            return device;
        }
	 
        function _init()
        {
            var doc = $(window.document);
            doc.mousemove(_active);
            doc.mouseenter(_active);
            doc.scroll(_active);
            doc.keydown(_active);
            doc.click(_active);
            doc.dblclick(_active);
            if (doc.addEventListener) {
                doc.addEventListener("touchstart", _active, false);
                doc.addEventListener("touchmove", _active, false);
            }

            setIdleTimeout(180000);
            setAwayTimeout(300000);
		
            $(window).focus(_onchange);
            $(window).blur(_onchange);
            if (typeof (window.addEventListener) != "undefined"){
                window.addEventListener("pageshow", _onchange);
                window.addEventListener("pagehide", _onchange);
            }
        }
	
        function _deinit()
        {
            var doc = $(window.document);
            doc.unbind("mousemove", _active);
            doc.unbind("mouseenter", _active);
            doc.off("scroll", _active);
            doc.unbind("keydown", _active);
            doc.off("click", _active);
            doc.unbind("dblclick", _active);
            if (doc.removeEventListener) {
                doc.removeEventListener("touchstart", _active, false);
                doc.removeEventListener("touchmove", _active, false);
            }

            $(window).unbind("focus", _onchange);
            $(window).unbind("blur", _onchange);
            if (typeof (window.removeEventListener) != "undefined"){
                window.removeEventListener("pageshow", _onchange);
                window.removeEventListener("pagehide", _onchange);
            }
        }
	
        $.inside.forceIdle = function() { _makeIdle(true); };
        $.inside.forceAway = function() { _makeAway(true); };
        $.inside.init(_init);
        $.inside.deinit(_deinit);
	
    })(_insideGraph.jQuery, window);
});;

insideFrontInterface.regexContainsHtmlTag = new RegExp(/<[a-z][\s\S]*/i);
insideFrontInterface.smellsHTML = function(str) {
    return insideFrontInterface.regexContainsHtmlTag.test(str);
}
insideFrontInterface.escapeHtml = function (str, check, forceEscape) {
    if (str == null || str == undefined) {
        return str;
    }
    if (typeof str != "string" && (str != null && (str.type === "multilangstring" || str.type === "multilangobject"))) {
        return str;
    }

    if (forceEscape != true && str && !insideFrontInterface.smellsHTML(str)) {
        return str;
    }

    var encode = true;
    if (check)
        encode = regexContainsHtmlTag.test(str);

    if (encode) {
        var div = document.createElement('div');
        div.appendChild(document.createTextNode(str));
        return div.innerHTML;
    }
    return str;
}

insideFrontInterface.updateLinkAttr = function () {
    var $ = _insideGraph.jQuery;
    try {
        if ($(this).attr('target') != '_blank') {
            if (insideFrontInterface.chat.version == 1) {
                $(this).attr('target', "_self");
            }
            else if (insideFrontInterface.chat.version == 2) {
                $(this).attr('target', "_top");
            }
        }
    }
    catch (e) { console.log(e); }
}

insideFrontInterface.openChatPane = function (force, readyCallback) {
    if(typeof insideFrontInterface.loadTranslations == "undefined") {
        //front module not initiated
        setTimeout(function() {
            insideFrontInterface.openChatPane(force, readyCallback);
        }, 100)
        return;
    }
    insideFrontInterface.loadTranslations(function() {
        _insideGraph.loadModule("chat", "frontend-chat.js.bundle")
            .then(function () {
                insideFrontInterface.openChatPane(force, readyCallback);               
            })
            .catch(function (err) {
                console.log("Error opening chat pane: ", err);
            });
    });
}

if(!insideFrontInterface.chat) {
    insideFrontInterface.chat = {};
    insideFrontInterface.chat.open = insideFrontInterface.openChatPane;
}

insideFrontInterface.chat.closeChatPane = function () {
    //inside is not initialised yet, nothing needs to occur.
    return;
}

_insideGraph.registerModule("front", function () {
    (function (window, $) {

        var jQuery = $;
        
        //jquery easing
        jQuery.easing.jswing = jQuery.easing.swing;
        jQuery.extend(jQuery.easing, {
            def: "easeOutQuad", swing: function (e, a, c, b, d) { return jQuery.easing[jQuery.easing.def](e, a, c, b, d) }, easeInQuad: function (e, a, c, b, d) { return b * (a /= d) * a + c }, easeOutQuad: function (e, a, c, b, d) { return -b * (a /= d) * (a - 2) + c }, easeInOutQuad: function (e, a, c, b, d) { return 1 > (a /= d / 2) ? b / 2 * a * a + c : -b / 2 * (--a * (a - 2) - 1) + c }, easeInCubic: function (e, a, c, b, d) { return b * (a /= d) * a * a + c }, easeOutCubic: function (e, a, c, b, d) { return b * ((a = a / d - 1) * a * a + 1) + c }, easeInOutCubic: function (e, a, c, b, d) {
                return 1 > (a /= d / 2) ? b / 2 * a * a * a + c :
                    b / 2 * ((a -= 2) * a * a + 2) + c;
            }, easeInQuart: function (e, a, c, b, d) { return b * (a /= d) * a * a * a + c }, easeOutQuart: function (e, a, c, b, d) { return -b * ((a = a / d - 1) * a * a * a - 1) + c }, easeInOutQuart: function (e, a, c, b, d) { return 1 > (a /= d / 2) ? b / 2 * a * a * a * a + c : -b / 2 * ((a -= 2) * a * a * a - 2) + c }, easeInQuint: function (e, a, c, b, d) { return b * (a /= d) * a * a * a * a + c }, easeOutQuint: function (e, a, c, b, d) { return b * ((a = a / d - 1) * a * a * a * a + 1) + c }, easeInOutQuint: function (e, a, c, b, d) { return 1 > (a /= d / 2) ? b / 2 * a * a * a * a * a + c : b / 2 * ((a -= 2) * a * a * a * a + 2) + c }, easeInSine: function (e, a, c, b, d) {
                return -b * Math.cos(a /
                    d * (Math.PI / 2)) + b + c;
            }, easeOutSine: function (e, a, c, b, d) { return b * Math.sin(a / d * (Math.PI / 2)) + c }, easeInOutSine: function (e, a, c, b, d) { return -b / 2 * (Math.cos(Math.PI * a / d) - 1) + c }, easeInExpo: function (e, a, c, b, d) { return 0 == a ? c : b * Math.pow(2, 10 * (a / d - 1)) + c }, easeOutExpo: function (e, a, c, b, d) { return a == d ? c + b : b * (-Math.pow(2, -10 * a / d) + 1) + c }, easeInOutExpo: function (e, a, c, b, d) { return 0 == a ? c : a == d ? c + b : 1 > (a /= d / 2) ? b / 2 * Math.pow(2, 10 * (a - 1)) + c : b / 2 * (-Math.pow(2, -10 * --a) + 2) + c }, easeInCirc: function (e, a, c, b, d) {
                return -b * (Math.sqrt(1 - (a /= d) *
                    a) - 1) + c;
            }, easeOutCirc: function (e, a, c, b, d) { return b * Math.sqrt(1 - (a = a / d - 1) * a) + c }, easeInOutCirc: function (e, a, c, b, d) { return 1 > (a /= d / 2) ? -b / 2 * (Math.sqrt(1 - a * a) - 1) + c : b / 2 * (Math.sqrt(1 - (a -= 2) * a) + 1) + c }, easeInElastic: function (e, a, c, b, d) { e = 1.70158; var f = 0, g = b; if (0 == a) return c; if (1 == (a /= d)) return c + b; f || (f = .3 * d); g < Math.abs(b) ? (g = b, e = f / 4) : e = f / (2 * Math.PI) * Math.asin(b / g); return -(g * Math.pow(2, 10 * (a -= 1)) * Math.sin(2 * (a * d - e) * Math.PI / f)) + c }, easeOutElastic: function (e, a, c, b, d) {
                e = 1.70158; var f = 0, g = b; if (0 == a) return c; if (1 ==
                    (a /= d)) return c + b; f || (f = .3 * d); g < Math.abs(b) ? (g = b, e = f / 4) : e = f / (2 * Math.PI) * Math.asin(b / g); return g * Math.pow(2, -10 * a) * Math.sin(2 * (a * d - e) * Math.PI / f) + b + c;
            }, easeInOutElastic: function (e, a, c, b, d) { e = 1.70158; var f = 0, g = b; if (0 == a) return c; if (2 == (a /= d / 2)) return c + b; f || (f = .3 * d * 1.5); g < Math.abs(b) ? (g = b, e = f / 4) : e = f / (2 * Math.PI) * Math.asin(b / g); return 1 > a ? -.5 * g * Math.pow(2, 10 * (a -= 1)) * Math.sin(2 * (a * d - e) * Math.PI / f) + c : g * Math.pow(2, -10 * (a -= 1)) * Math.sin(2 * (a * d - e) * Math.PI / f) * .5 + b + c }, easeInBack: function (e, a, c, b, d, f) {
                void 0 == f &&
                    (f = 1.70158); return b * (a /= d) * a * ((f + 1) * a - f) + c;
            }, easeOutBack: function (e, a, c, b, d, f) { void 0 == f && (f = 1.70158); return b * ((a = a / d - 1) * a * ((f + 1) * a + f) + 1) + c }, easeInOutBack: function (e, a, c, b, d, f) { void 0 == f && (f = 1.70158); return 1 > (a /= d / 2) ? b / 2 * a * a * (((f *= 1.525) + 1) * a - f) + c : b / 2 * ((a -= 2) * a * (((f *= 1.525) + 1) * a + f) + 2) + c }, easeInBounce: function (e, a, c, b, d) { return b - jQuery.easing.easeOutBounce(e, d - a, 0, b, d) + c }, easeOutBounce: function (e, a, c, b, d) {
                return (a /= d) < 1 / 2.75 ? 7.5625 * b * a * a + c : a < 2 / 2.75 ? b * (7.5625 * (a -= 1.5 / 2.75) * a + .75) + c : a < 2.5 / 2.75 ? b *
                    (7.5625 * (a -= 2.25 / 2.75) * a + .9375) + c : b * (7.5625 * (a -= 2.625 / 2.75) * a + .984375) + c;
            }, easeInOutBounce: function (e, a, c, b, d) { return a < d / 2 ? .5 * jQuery.easing.easeInBounce(e, 2 * a, 0, b, d) + c : .5 * jQuery.easing.easeOutBounce(e, 2 * a - d, 0, b, d) + .5 * b + c }
        });

        var frontEnd = {};
        var device;
        var insideScript = _insideCDN;
        var prevAccessKey;
        /* _insideScriptUrl can override the path for js files. Eg if client is hosting js files.*/
        if(typeof _insideScriptUrl != "undefined" && _insideScriptUrl != null) {
            insideScript = _insideScriptUrl;
        }
        _insideGraph.jQuery.inside.insideScript = insideScript;

        insideFrontInterface.getAriaButtonAttribute = getAriaButtonAttribute;
        function getAriaButtonAttribute(label) {
            return 'onkeydown="if(event&&(event.keyCode==32||event.keyCode==13)){insideFrontInterface.keyboardNavigation=true; event.target.click(); return false;}" role="button" aria-label="' + label + '" tabindex="0"';
        }

        //star selector component - taken from inside.components
        frontEnd.starSelector = starSelector;
        function starSelector(ob) {
            var _this = this;
            init();
            var _value = 0;
            var starSelect;

            function init() { 

                let colorStyle = "";
                if(ob.color && ob.color != "") {
                    colorStyle = "style='color:" + ob.color + "'";
                }

                var starHTML = "";
                starHTML += "<div class='inside_starSelector'>";
                for (var i = 0; i < 5; i++) {
                    starHTML += "<div class='star icon-star' " + colorStyle + " val='" + (i + 1) + "' tabindex='2' aria-label='" + (i + 1) + " star" + (i + 1 > 1 ? 's' : '') + "'></div>";
                }
                starHTML += "</div>";
                starSelect = $(starHTML).appendTo($(ob.holder));

                $(starSelect).find(".star").hover(function () {
                    $(this).addClass("selected").removeClass("icon-star").addClass("icon-star-filled");
                    var val = parseInt($(this).attr("val"));
                    setValue(val);

                }, function () {
                    //$(this).removeClass("selected");
                    setValue(_value);
                });
                $(starSelect).find(".star").click(function () {
                    _value = parseInt($(this).attr("val"));
                    setValue(_value);
                });
                
                $(starSelect).find(".star").keydown(function (event) {
                    if (event.which == 13 || event.which == 32) {
                        event.preventDefault();
                        _value = parseInt($(this).attr("val"));
                        setValue(_value);                   
                    }
                });
            }

            _this.value = value;
            function value(val) {
                if (typeof (val) == "undefined") {
                    return _value;
                } else {
                    _value = val;
                    setValue(val);
                }
            }

            function setValue(val) {
                starSelect.find(".star").removeClass("selected").removeClass("icon-star-filled").addClass("icon-star");
                starSelect.find(".star").each(function () {
                    if (parseInt($(this).attr("val")) <= val) {
                        $(this).addClass("selected").removeClass("icon-star").addClass("icon-star-filled");
                    }
                });
            }

        }

        var standalone = window.navigator.standalone,
            userAgent = window.navigator.userAgent.toLowerCase(),
            safari = /safari/.test(userAgent),
            firefox = /firefox/.test(userAgent),
            ios = /iphone|ipod|ipad/.test(userAgent);

        _insideCDN = _insideCDN || "./";

        imageurl = _insideCDN + "images/";
        offerurl = _insideCDN + "offers/";

        if (typeof (_insideProtocol) == "undefined") {
            _insideProtocol = "";
        }
        frontEnd.imageurl = imageurl;
        frontEnd.offerurl = offerurl;

        insideFrontInterface.chat = insideFrontInterface.chat || {};

        var chatEnabled = true;

        var tabPosition = "right";

        function getParameterByName(name, url) {
            if (!url) url = window.location.href;
            name = name.replace(/[\[\]]/g, '\\$&');
            var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
                results = regex.exec(url);
            if (!results) return null;
            if (!results[2]) return '';
            return decodeURIComponent(results[2].replace(/\+/g, ' '));
        }

        function init() {
            var key = getParameterByName('key');
            if (key) {
                insideFrontInterface.chat.isUrlSurvey = true;
                insideAPI.post("api/surveys/checkConversationSurveyResults", { key: key }, function (response) {
                    if (response && response.status == "Success" && response.errorMessage == null && response.data) {                     
                        var settings = { surveyid: response.data.surveyid, visitorclosedchat: false, position: "6", text: "The survey has already been answered for this conversation!", message: "<div id='insideSurveyCheckMessage'></div>", margin: 10 };
                        var surveyData = { chatid: response.data.chatid, pid: response.data.visitorid, settings: settings, type: "chatsurvey" }

                        if (response.data.answeredQuestions && response.data.answeredQuestions.length > 0) {
                            surveyData.answeredQuestions = response.data.answeredQuestions;
                        }

                        if (!response.data.success) {
                            insideAction(surveyData, undefined, true);
                        } else if (response.data.linkedSurvey) {
                            surveyData.settings.surveyid = response.data.linkedSurvey;
                            surveyData.settings.text = "";
                            delete surveyData.answeredQuestions;
                            insideAction(surveyData, undefined, true);
                        } else if (response.data.success === true) {
                            insideAPI.post("api/surveys/getSurvey", { surveyId: settings.surveyid }, function (response) {
                                if (response && response.data && response.data.settings) {
                                    showSurveyResultsCheckPopup(surveyData, response.data.settings.completionMessage || "Thanks for the feedback!");
                                }
                            });
                        } else {
                            showSurveyResultsCheckPopup(surveyData);
                        }
                    } else {
                        insideFrontInterface.chat.isUrlSurvey = false;
                    }
                });
            } else {
                insideFrontInterface.chat.isUrlSurvey = false;
            }

            showTabs();

            if (window.top != window) {
                //do not run in iframes etc.
                if (!alreadyConnected) {
                    bindEvents();
                    setTimeout(init, 100);
                    return;
                }
                if (frontEnd.settings.allowIframes != true) {
                    $("#inside_holder").remove();
                    return;
                }
            }

            if ($("#inside_holder").length == 0) {
                setTimeout(init, 1000);
                return;
            }
            device = getDevice();
            frontEnd.device = device;
            bindEvents();

            chatEnabled = $.inside.isEnabled("chat");

            loadCssFile(_insideCDN + "ig.css?dev=" + device + "&_" + _insideScriptVersion);

            setTimeout(function () { windowScale(500); }, 1000);

            IE11Quirks = isIE11Quirks();
            if (IE11Quirks) {
                //positioning of inside is done with javascript
                $(window).scroll(IE11ScrollFix);
            }

            if (_insideGraph && _insideGraph.triggerEvents && _insideGraph.triggerEvents.length > 0) {
                for (var i = 0; i < _insideGraph.triggerEvents.length; i++) {
                    triggerVisitorEvent(_insideGraph.triggerEvents[i].label);
                }
            }

            initTabVisible();
        }

        function showSurveyResultsCheckPopup(data, message) {
            var popup = $("<div class='inside_visitorNotify'><div class='inside_closeButton fonticon icon-hclose'></div></div>").appendTo("#inside_holder");
            
            popup[0].data = data;

            viewport = getViewPortSize();

            if (data.settings.position == "1" || data.settings.position == "4" || data.settings.position == "7") {
                popup.css("left", "10px");
            } else if (data.settings.position == "3" || data.settings.position == "6" || data.settings.position == "9") {
                popup.css("left", "auto");
                popup.css("right", "10px");
            } else {
                popup.css("left", "10px");
            }

            if(insideFrontInterface.visitorNotify) {
                insideFrontInterface.visitorNotify.scalePopups();
            }

            var popupMainContent = $("<div class='inside_notify_content'></div>").appendTo(popup);
            popupMainContent.append("<div class='inside_notify_content_message'>" + data.settings.message + "</div>");

            popup.find(".inside_closeButton").click(function () {

                //if (popup.attr("stickyid") != null) {
                //    $.inside.server.unstick(popup.attr("stickyid"));
                //}

                popup.remove();

                $("#inside_holder .inside_windowBlack").remove();
            });

            visitorNotify(data, function () {
                insideFrontInterface.visitorNotify.slideInPopup(popup);
            });

            popup.find("#insideSurveyCheckMessage").html("<h3>" + (message || data.settings.text) + "</h3>");
            $(".inside_visitorNotify").css("background","rgba(255, 255, 255, 0.8)");
        }

        var IE11Quirks = false;

        function isIE11Quirks() {
            var isIE11 = !!navigator.userAgent.match(/Trident\/7/);
            var mode = document.documentMode;
            return (isIE11 && mode == 5);
        }

        function IE11ScrollFix() {
            viewport = getViewPortSize();
            $("#inside_holder").css("top", $(window).scrollTop() + "px");
            $(".inside_chatPane").css("top", viewport.height * 0.5 - $(".inside_chatPane").height() * 0.5);
        }

        frontEnd.showTabs = showTabs;
        function showTabs() {
            if (!device) {
                device = getDevice();
            }
            if ($("#inside_holder").length > 0) {
                return;
            }
            $("<div id='inside_holder'><div id='inside_overlay'></div></div>").appendTo("body");
            $("#inside_holder").css({display:"none", overflow:"visible", position: "fixed", width: "100%", right: 0, left: 0, top: 0, height: 0});
            $("#inside_holder").attr("pagetitle", $("title").text());
            $("#inside_holder").attr("pageurl", document.location.href);

            $("<div id='inside_tabs'></div>").appendTo("#inside_holder");

            $("#inside_holder").attr("device", device);
            $("#inside_tabs").css({position: "fixed"});

            if (device == 2) {
                $("#inside_holder").addClass("mobile-device");
            }


            tabMouseDown = false;
            var mousex = 0;
            var mousey = 0;
            var count = 0;
            $("#inside_tabs").unbind("mousedown");
            $("#inside_tabs").unbind("touchstart");

            $("#inside_tabs").on("mousedown", mouseDown);
            $("#inside_tabs").bind("touchstart", mouseDown);

            function mouseDown(e) {
                tabMouseDown = true;
                count = 0;
                var xmove = 0;
                mousex = e.clientX;
                mousey = e.clientY + parseInt($("#inside_tabs").css("margin-bottom"));

                if (typeof (e.originalEvent.touches) != "undefined") {
                    mousey = e.originalEvent.touches[0].clientY + parseInt($("#inside_tabs").css("margin-bottom"));
                    mousex = e.originalEvent.touches[0].clientX;
                }
                //alert(mousey);
                
                $(window).bind("mousemove", mouseMove);
                window.addEventListener("touchmove", mouseMove, {passive: false});
                

                function mouseMove(e) {
                    e.preventDefault();
                    var clientY = e.clientY;
                    var clientX = e.clientX;
                    if (typeof (e.touches) != "undefined") {
                        clientY = e.touches[0].clientY;
                        clientX = e.touches[0].clientX;
                    }
                    //$("#inside_tabs").css("margin-left",  e.clientX-mousex);
                    $("#inside_tabs").css("margin-bottom", ((clientY - mousey) * -1) + "px");

                    xmove = clientX - mousex;

                    var tabs =  $("#inside_tabs")[0];
                    var rect = tabs.getBoundingClientRect();
                    
                    if(rect.top < 0) {
                        mousey -= -rect.top;
                    }
                    if(rect.top + rect.height > window.innerHeight) {
                        mousey -= window.innerHeight - (rect.top + rect.height);
                    }

                    $("#inside_tabs").css("margin-bottom", ((clientY - mousey) * -1) + "px");

                    count++;
                    e.preventDefault();

                }

                $("#inside_tabs").unbind("mouseup");
                $("#inside_tabs").unbind("touchend");
                //$("#inside_tabs").bind("mouseup", mouseUp);
                //$("#inside_tabs").bind("touchend", mouseUp);
                window.addEventListener("mouseup", mouseUp);
                window.addEventListener("touchend", mouseUp);

                function mouseUp(e) {
                    if (count > 10 && navigator.maxTouchPoints === 0 && e.target.closest('#inside_tabs') !== null) {
                        insideFrontInterface.chat.preventTabClick = true;
                    }
                    if (device != 1) {
                        //touch device
                        if (tabPosition.indexOf("right") != -1 && xmove > 20) {
                            autohideTabs(100);
                        }
                        if (tabPosition.indexOf("left") != -1 && xmove < -20) {
                            autohideTabs(100);
                        }
                    }
                    window.removeEventListener("touchmove", mouseMove, {passive: false});
                    window.removeEventListener("mouseup", mouseUp);
                    window.removeEventListener("touchend", mouseUp);
                }

            }

            $(window).bind("mouseup", windowMouseUp);
            $(window).bind("touchend", windowMouseUp);

            function windowMouseUp(e) {
                $(window).unbind("mousemove");
                $(window).unbind("touchmove");
                tabMouseDown = false;
            }

        }

        frontEnd.getDevice = getDevice;
        function getDevice() {
            var agent = window.navigator.userAgent.toLowerCase();
            var iPod = (agent.indexOf("ipod") > 0);
            var iPhone = (agent.indexOf("iphone") > 0);
            var iPad = (agent.indexOf("ipad") > 0) || (navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1);
            var android = ((agent.indexOf("android") > 0) && (agent.indexOf("mobile") > 0));
            var androidTablet = !android && (agent.indexOf("android") > 0 || (agent.indexOf("linux") > 0 && navigator.maxTouchPoints > 1));
            var webOS = (agent.indexOf("webos") > 0);
            var blackBerry = (agent.indexOf("blackberry") > 0);
            var rimTablet = (agent.indexOf("rimtablet") > 0);
            var device = 1;
            if (iPod || iPhone || android || webOS || blackBerry) {
                device = 2;
            } else if (iPad || rimTablet || androidTablet) {
                device = 3;
            }
            return device;
        }

        var eventsBound = false;
        function bindEvents() {
            if (eventsBound) {
                return;
            }
            eventsBound = true;
            $(window).resize(windowScale);

            $(window).bind('gestureend', windowScale);

            if (typeof $.inside != "object")
                return;

            $.inside.bind("connected", connectedToInside);
            $.inside.bind("disconnected", disconnected);
            $.inside.bind("updateUsers", updateUsers);
            $.inside.bind("removeUsers", removeUsers);
            $.inside.bind("insideAction", insideAction);
            $.inside.bind("unstick", unstick);
            $.inside.bind("coBrowse", coBrowseCommandHandler);
            $.inside.bind("proactiveMessage", proactiveMessage);
            $.inside.prebindModule("chat", "chat", "frontend-chat.js.bundle");
            $.inside.prebindModule("workflow", "chat", "frontend-chat.js.bundle");
            $.inside.prebindModule("nextWorkflowAction", "chat", "frontend-chat.js.bundle");
            $.inside.prebindModule("workflowCanceled", "chat", "frontend-chat.js.bundle");
            $.inside.startHub();
        }

        insideFrontInterface.connectSignalr = connectSignalr;
        function connectSignalr() {
            $.inside.startHub();
        }

        insideFrontInterface.disconnectSignalr = disconnectSignalr;
        function disconnectSignalr() {
            $.inside.stop();
            return $.inside.isConnected();
        }

        insideFrontInterface.checkForCoBrowseRequestState = checkForCoBrowseRequestState;
        function checkForCoBrowseRequestState() {
            $.inside.server.coBrowseRequestState().then(function (state) {
                if (state == "Accept") {
                    coBrowseCommandHandler("/load");
                } else if (state == "Request" && $(".inside_cobrowseRequest").length == 0) {
                    insideFrontInterface.chat.setCoBrowseHtml("request");
                }
            });
            $.inside.server.coBrowseRequestData().then(function (data) {
                if (data && typeof (data) == "string") {
                    coBrowseCommandHandler(data)
                }
            });
        }

        function coBrowseCommandHandler(command) {
            loadInsideChat(function () {
                _insideGraph.loadModule("cobrowse", "inside.front.cobrowse.js").then(function () {
                    if (command == "/load") {
                        frontEnd.Load();
                    }
                    else if (command == "/open") {
                        frontEnd.Open();
                    }
                    else if (command == "/show_control_mode_confirmation") {
                        if ($("#insideChatFrame").contents().find(".inside_cobrowseRequest").closest(".notification .controlmoderequest").length == 0) {
                            setTimeout(function () {
                                frontEnd.CommandHandler(command);
                            }, 2000);     
                        }                  
                    }
                });
            })
        }

        function proactiveMessage(message) {
            loadInsideChat(function () {
                insideFrontInterface.proactiveMessage(message);
            })
        }

        function unstick(stickyid) {

            /*
            //remove all popups with stickyid
            if($(".inside_visitorNotify")[0].data.type != 'chatsurvey') {
                $(".inside_visitorNotify[stickyid='" + stickyid + "']").remove();
            }
            */
        }

        insideFrontInterface.getAccessKey = getAccessKey;
        function getAccessKey() {
            return _insideGraph.current.account + ":" + _insideGraph.pid + ":" + _insideGraph.accessKey;
        }

        var waitingForConnected = false;
        function insideAction(data, stickyid, renderAsPopup) {
            if(!data.settings.sticky && data.type != "visitornotify" && data.type != "chatsurvey" && (waitingForConnected || (data.viewId && _insideGraph.accessKey.indexOf(data.viewId) !== 0))) {
                // ignore this check for sticky events, popups and chatsurveys.
                //check the page is changing - on SPA this triggers before a disconnect.
                waitingForConnected = true;
                setTimeout(function() {
                    insideAction(data, stickyid, renderAsPopup);
                }, 100);
                return;
            }
            data.stickyid = stickyid;
            if (data.type == "liveshownotify") {
                if (typeof insideStreamingCheck != "undefined" && typeof insideStreaming == "undefined") {
                    insideStreamingCheck.loadStreamingBundle(function () {
                        insideStreaming.showLiveStreamNotification(data.settings);
                    });
                }
                else {
                    insideStreaming.showLiveStreamNotification(data.settings);
                }
            }
            else if (data.type == "visitornotify") {
                visitorNotify(data);
            } else if (data.type == "survey") {
                data.settings.message = "<div id='insideSurveyHolder'></div>";
                showSurveyPopup(data);
                //load the survey in, and show it in #insideSurveyHolder
            } else if (data.type == "chatsurvey") {
                var visitorHasDNDFlag = insideFrontInterface.chat && insideFrontInterface.chat.data && insideFrontInterface.chat.data.flags && insideFrontInterface.chat.data.flags.indexOf("dnd") !== -1;
                if(visitorHasDNDFlag) {
                    $.inside.server.unstick(stickyid);
                    return;
                }

                if (typeof insideChatPane != "undefined" && insideChatPane != null && typeof insideChatPane.showSurvey == "function"
                        && typeof insideFrontInterface.chat.isUrlSurvey != "undefined" && insideFrontInterface.chat.isUrlSurvey != null
                        && !insideFrontInterface.chat.isUrlSurvey) {
                    insideChatPane.showSurvey(data);
                    return;
                } else {
                    if (chatPaneVersion() === 2) {
                        if(insideFrontInterface.chatSettings.postChatSurvey && !insideFrontInterface.chat.isUrlSurvey) {
                            insideFrontInterface.openChatPane(true, function(){
                                insideChatPane.showSurvey(data);
                            });
                        }
                        return;
                    }
                }
                data.settings.message = "<div id='insideSurveyHolder'></div>";

                //show the chat in the chat pane
                if ($.inside.front.settings.showPostChatSurveyInChat && !renderAsPopup) {
                    data.settings.useContainer = true;
                    data.settings.containerid = "#inside_chatWindow, #inside_chatPane_custom_chatHolder";

                    if (!insideFrontInterface.chat.chatPaneOpen) {
                        insideFrontInterface.openChatPane();
                        $('.inside_greeting_message').parent().remove();//remove welcome message
                        $(".inside_systemMessage.insideGreetingMessage").remove();//remove welcome message
                        setTimeout(function () {
                            $(".inside_dept_selector").remove();
                            $('.inside_greeting_message').parent().remove();//remove welcome message
                            $(".inside_systemMessage.insideGreetingMessage").remove();//remove welcome message
                        }, 250);
                    }
                    //to do: perhaps hide all chat contents and show survey in .inside_chatPane
                    //data.settings.containerid = ".inside_chatPane";
                    //$(".inside_chatPane").contents().hide();
                }

                if ($.inside.front.settings.postChatSurvey && $.inside.front.settings.postChatSurvey != "") {
                    if ($.inside.front.settings.postChatSurvey && $.inside.front.settings.postChatSurvey.toLowerCase() == "disable") {
                        return; //disabled on this chat pane
                    } else {
                        data.settings.surveyid = $.inside.front.settings.postChatSurvey;
                    }
                }

                data.settings.position = "6";

                //insideFrontInterface.openChatPane(true);
                /*
                if($(data.settings.containerid).length == 0) {
                    setTimeout(function(){
                        showSurveyPopup(data);
                    }, 5000);
                } else {
                    */
                if(!$.inside.front.settings.showPostChatSurveyInChat) {
                    showSurveyPopup(data);
                } else {
                    if ($("#inside_chatWindow, #inside_chatPane_custom_chatHolder").length > 0) {
                        insideFrontInterface.chat.clearChatGrouping();
                        showSurveyPopup(data);
                    } else {
                        //wait until chat is ready
                        chatSurveyQueue.push(data);
                        frontEnd.chatSurveyQueue = chatSurveyQueue;
                        checkChatSurveyQueue();
                    }
                }
            } else if (data.type == "jointhecall") {
                insideFrontInterface.chat.joinTheCallSettings = data.settings || {};
                setTimeout(function () {
                    insideFrontInterface.chat.canJoinTheCall = true;
                    insideFrontInterface.chat.setupJoinTheCallTag(insideFrontInterface.chat.joinTheCallSettings);
                }, insideFrontInterface.chat ? 0 : 5000);
            } else if (data.type == "clicktocall") {
                insideFrontInterface.onClickToCallChatTabImageLoad = onClickToCallChatTabImageLoad;
                insideFrontInterface.onClickToCallChatTabImageClick = onClickToCallChatTabImageClick;
                insideFrontInterface.showClickToCallRequestPopup = showClickToCallRequestPopup;
                insideFrontInterface.clickToCallScript = data.settings.script;
               
                if (typeof (data.settings.clickToCallSettings) != "undefined") {
                    insideFrontInterface.chat.clickToCallSettings = data.settings.clickToCallSettings; 
                } else {
                    insideFrontInterface.chat.clickToCallSettings = data.settings;
                }
                if (typeof (data.settings.clickToCallSettings) != "undefined" && (data.settings.clickToCallSettings.script || "") != "") 
                    insideFrontInterface.clickToCallScript = data.settings.clickToCallSettings.script;
                setupClickToCallTag(data.settings.clickToCallSettings, frontEnd.settings);
            }
        }

        insideFrontInterface.triggerVisitorEvent = triggerVisitorEvent;
        function triggerVisitorEvent(label, callback) {
            if (label) {
                insideAPI.post("/api/visitor/triggerevent", { label: label }, function () {
                    if (typeof callback === "function") {
                        callback();
                    }
                });
            }
        }

        //#region ClickToCall

        var clickToCallSettings;
        var isClickToCallRequestSent = false;

        function setupClickToCallTag(settings, frontEndSettings) {
            if ($("#inside_clickToCallChatTab").length) { return; }

            clickToCallSettings = settings;
            if(typeof clickToCallSettings != "undefined") {
                insideFrontInterface.chat.clickToCallSettings = clickToCallSettings;
            }

            var src = clickToCallSettings && clickToCallSettings.clickToCallTab && clickToCallSettings.clickToCallTab.customTabImage
                ? _insideCDN + "/custom/" + clickToCallSettings.clickToCallTab.customTabImage
                : imageurl + "click-to-call-tab.png";

            var html = "<div id='inside_clickToCallChatTab' tabindex='2' class='noselect' ondragstart='return false;' ondrop='return false;'>" +
                "<img id='inside_clickToCallImage' src='" + src + "' />" +
                "</div>";

            var $html = $(html);
            $html.find("#inside_clickToCallChatTab").hide();
            $html.appendTo("#inside_tabs");
            $html.find("img").on("load", insideFrontInterface.onClickToCallChatTabImageLoad);

            if (tabPosition.indexOf("bottom") != -1) {
                $("#inside_liveChatTab").appendTo("#inside_tabs");
            }

            setClickToCallTag(true);
            $("#inside_clickToCallChatTab").click(onClickToCallChatTabImageClick);
            if (clickToCallSettings && clickToCallSettings.clickToCallTab && clickToCallSettings.clickToCallTab.hideAmount && clickToCallSettings.clickToCallTab.hideAmount != 0) {
                $("#inside_clickToCallChatTab").attr("autohide", clickToCallSettings.clickToCallTab.hideAmount);
            } else {
                if (typeof (frontEnd.settings.autohideTabs) != "undefined" && frontEnd.settings.autohideTabs == true) {
                    $("#inside_clickToCallChatTab").attr("autohide", 30);
                }
            }

            try { _insideGraph.doEvent("c2cavailable", true); } catch (e) { }
        }

        function setClickToCallTag(show) {
            if ($("#inside_clickToCallChatTab").length === 0) { return; }

            if (show) {
                $("#inside_clickToCallChatTab").show();
            } else {
                $("#inside_clickToCallChatTab").hide();
            }
            if (insideFrontInterface && insideFrontInterface.chatSettings && insideFrontInterface.chatSettings.version == "2"
                && typeof (insideChatPane) != "undefined" && typeof (insideChatPane.setClickToCall) == "function") {
                insideChatPane.setClickToCall(show);
            }
        }

        function onClickToCallChatTabImageLoad() {
            var hideAmount = 30;
            if ($.inside.front.settings.autoHideAmount) {
                hideAmount = parseInt($.inside.front.settings.autoHideAmount);
            }
            hideAmount = 30;
            //$("#inside_clickToCallChatTab").css("right", -args.width + hideAmount);
            setTimeout(function () { $("#inside_tabs").show(); }, 500);
            $("#inside_clickToCallChatTab").width(this.width);

            positionTabs();
            windowScale();
            if (typeof (frontEnd.settings.autohideTabs) != "undefined" && frontEnd.settings.autohideTabs == true) {
                if (device > 1 && frontEnd.settings.autohideOnMobile == false) {
                    //don't hide if mobile and disabled
                    positionTabs();
                } else {
                    if (frontEnd.settings.autoHideTabOnLoad != true) {
                        autohideTabs(0);
                    } else {
                        autohideTabs(0);
                    }

                }
            }

        }

        function isValidClickToCallRequestPopupData() {
            var firstname = $(".inside_clicktocall_firstname input").val().trim();
            var phonenum = $(".inside_clicktocall_phone_num input").val().trim();
            return firstname && phonenum && phonenum.length > 3 && phonenum.match(/^\d+$/);
        }

        function onClickToCallChatTabImageClick(args) {
            if (insideFrontInterface.chat.preventTabClick) {
                insideFrontInterface.chat.preventTabClick = false;
                return;
            }
            if (device == 2 && $("#inside_clickToCallChatTab").attr("tabHidden") == "true") {
                insideFrontInterface.hoverShowTabs($("#inside_clickToCallChatTab"));
                return;
            }
            if (parseInt($("#inside_tabs").css("right")) < -30) { return; }
            if (!isClickToCallRequestSent) {
                showClickToCallRequestPopup();
            } else {
                showClickToCallConnectingPopup(true);
            }
        }

        function showClickToCallRequestPopup() {

            if (chatPaneVersion() == 2) {
                insideFrontInterface.openChatPane(true, function() {
                    insideChatPane.clickToCall();
                });                
                return;
            } else {
                $('#inside_holder').addClass('tabClicked');
                insideFrontInterface.openChatPane(true, showClickToCallRequestCont);
            }
        }

        /* todo: move this to legacy chat class */
        function showClickToCallRequestCont() {
            if($(".inside_chatPane, #inside_chatPane_custom").length == 0) {
                setTimeout(showClickToCallRequestCont, 100);
                return;
            }
            $(".inside_chatPane, #inside_chatPane_custom").addClass("clicktocall");

            $("#inside_holder .inside_clicktocall_connecting").hide();

            if ($("#inside_holder .inside_clicktocall_request").length === 0) {
                var html =
                    "<div class='inside_clicktocall_request'>" +
                    "<div class='inside_clicktocall_header'>" +
                    "<table>" +
                    "<tr>" +
                    "<td class='inside_clicktocall_txt0'></td>" +
                    "<td class='inside_clicktocall_header_icons'><span class='icon-minimise'></span></td>" +
                    "<td class='inside_clicktocall_header_icons'><span class='fonticon icon-hclose'></span></td>" +
                    "</tr>" +
                    "</table>" +
                    "</div>" +

                    "<div class='inside_clicktocall_body'>" +

                    "<div class='inside_clicktocall_txt1'></div>" +

                    "<p><br/>" +

                    "<div class='inside_clicktocall_txt2'></div>" +

                    "<p><br/>" +

                    "<table class='inside_clicktocall_name'>" +
                    "<tr>" +
                    "<td>First Name</td>" +
                    "<td>Last Name</td>" +
                    "</tr>" +
                    "<tr>" +
                    "<td class='inside_clicktocall_firstname'><input></td>" +
                    "<td class='inside_clicktocall_lastname'><input></td>" +
                    "</tr>" +
                    "</table>" +

                    "<p><br/>" +

                    "<table class='inside_clicktocall_phone'>" +
                    "<tr>" +
                    "<td class='inside_clicktocall_phone_num_lbl' colspan='2'>Your Number</td>" +
                    "<td class='inside_clicktocall_phone_ext_lbl'>Ext</td>" +
                    "</tr>" +
                    "<tr>" +
                    "<td class='inside_clicktocall_phone_code'><input></td>" +
                    "<td class='inside_clicktocall_phone_num'><input></td>" +
                    "<td class='inside_clicktocall_phone_ext'><input></td>" +
                    "</tr>" +
                    "</table>" +

                    "<div class='inside_clicktocall_form_error'>&nbsp;</div>" +
                    "<div id='inside_clicktocall_button_holder'><button class='inside_clicktocall_btn'></button></div>" +
                    "</div>" +
                    "</div>";

                var $html = $(html);
                var c2c = $html.appendTo(".inside_chatPane, #inside_chatPane_custom");
                c2c.show();

                setClickToCallStyle();
                $(".inside_chatPane, #inside_chatPane_custom").removeClass("offline");

            }

            $(".inside_chatPane_header_text_c2c").remove();
            $("<span class='inside_chatPane_header_text_c2c'>" + insideFrontInterface.chat.translate("Have us call you back") + "</span>").appendTo("#inside_siteLogo");

            var settings = clickToCallSettings && clickToCallSettings.requestForm ? clickToCallSettings.requestForm : {};
            var title = settings.title || "HAVE US CALL YOU BACK";
            var header = settings.heading || "Talk to an Expert now";
            var buttonlabel = settings.buttonlabel || "CALL ME NOW";
            var text = "";
            if (firstname || lastname || phonenum) {
                if (settings.text2) { text = settings.text2; }
                else { text = "Please verify your name and phone number."; }
            } else {
                if (settings.text1) { text = settings.text1; }
                else { text = "Please enter your name and phone number."; }
            }

            $("#inside_holder .inside_clicktocall_request .inside_clicktocall_txt0").html(title);
            $("#inside_holder .inside_clicktocall_request .inside_clicktocall_txt1").html(header);
            $("#inside_holder .inside_clicktocall_request .inside_clicktocall_txt2").html(text);
            $("#inside_holder .inside_clicktocall_request .inside_clicktocall_btn").html(buttonlabel);

            var visitorDetails;
            try {
                visitorDetails = _insideGraph.getVisitorDetails() || {};
            } catch (e) {
                visitorDetails = {};
            }
            var firstname = visitorDetails.firstname || "";
            var lastname = visitorDetails.lastname || "";
            var phone = visitorDetails.phone || "";
            var phonecode = "";
            var phonenum = "";
            var phoneext = "";
            if (phone.length > 10) {
                phonecode = phone.substr(0, 3);
                phonenum = phone.substr(3, 7);
                phoneext = phone.substr(10);
            } else if (phone.length > 7) {
                phonecode = phone.substr(0, 3);
                phonenum = phone.substr(3);
            } else {
                phonenum = phone;
            }

            $("#inside_holder .inside_clicktocall_request .inside_clicktocall_firstname input").val(firstname);
            $("#inside_holder .inside_clicktocall_request .inside_clicktocall_lastname input").val(lastname);
            $("#inside_holder .inside_clicktocall_request .inside_clicktocall_phone_code input").val(phonecode);
            $("#inside_holder .inside_clicktocall_request .inside_clicktocall_phone_num input").val(phonenum);
            $("#inside_holder .inside_clicktocall_request .inside_clicktocall_phone_ext input").val(phoneext);

            $("#inside_holder .inside_clicktocall_request .inside_clicktocall_btn").off("click").on("click", function (e) {
                if (!isValidClickToCallRequestPopupData()) {
                    $(".inside_clicktocall_form_error").text("Invalid name or phone number!");
                    setTimeout(function () { $(".inside_clicktocall_form_error").html("&nbsp;"); }, 5000);
                    return;
                }

                var args = {
                    script: insideFrontInterface.clickToCallScript,
                    firstname: $(".inside_clicktocall_firstname input").val().trim(),
                    lastname: $(".inside_clicktocall_lastname input").val().trim(),
                    phonecode: $(".inside_clicktocall_phone_code input").val().trim(),
                    phonenum: $(".inside_clicktocall_phone_num input").val().trim(),
                    phoneext: $(".inside_clicktocall_phone_ext input").val().trim()
                };

                function onSuccess(e) {
                    if (e && (e.status != "Success" || !e.data)) { return onError(e); }
                    showClickToCallConnectingPopup(true);
                    isClickToCallRequestSent = true;
                }

                function onError(e) {
                    showClickToCallConnectingPopup(false);
                }

                $("#inside_holder .inside_clicktocall_request").hide();
                showClickToCallConnectingPopup();
                $(".inside_clicktocall_header").hide();
                $("#insideOfferHolder").hide();

                insideAPI.post("/api/visitor/clicktocall", args, onSuccess, onerror);
            });

            $("#inside_holder .inside_clicktocall_request .inside_clicktocall_header_icons .icon-hclose").off("click").on("click", function (e) {
                insideFrontInterface.chat.closeChatPane();
                windowScale();
            });

            $("#inside_holder .inside_clicktocall_request .inside_clicktocall_header_icons .icon-minimise").off("click").on("click", function (e) {
                insideFrontInterface.chat.closeChatPane();
            });

            if (!isClickToCallRequestSent) {
                $("#inside_clickToCallChatTab").hide();
                $("#inside_holder .inside_clicktocall_request").show();
            } else {
                showClickToCallConnectingPopup(true);
            }
        }

        function setClickToCallStyle() {
            var cssString = "";
            var headerBgColour = "#02385a";

            cssString += ".inside_chatPane.clicktocall #inside_chatPaneHeader, .inside_chatPane.clicktocall #inside_chatPane_custom_chatHeader { background: " + headerBgColour + "}";
            cssString += "#inside_chatPane_custom.clicktocall #inside_chatPaneHeader, #inside_chatPane_custom.clicktocall #inside_chatPane_custom_chatHeader { background: " + headerBgColour + "}";
            var iconColour = "#ffffff";
            cssString += "#inside_holder .inside_chatPane.clicktocall .inside_closeCross.fonticon, #inside_holder #inside_chatPane_custom.clicktocall .inside_closeCross.fonticon { color: " + iconColour + "}";
            addStyleString(cssString, "clicktocallstyles");
        }

        function showClickToCallConnectingPopup(success) {
            //insideFrontInterface.chat.closeChatPane();
            if ($("#inside_holder .inside_clicktocall_connecting").length === 0) {
                var html =
                    "<div class='inside_clicktocall_connecting'>" +
                    "<div class='inside_clicktocall_header'>" +
                    "<table>" +
                    "<tr>" +
                    "<td class='inside_clicktocall_txt0'></td>" +
                    "<td class='inside_clicktocall_close'>X</td>" +
                    "</tr>" +
                    "</table>" +
                    "</div>" +

                    "<div class='inside_clicktocall_body'>" +
                    "<div class='inside_clicktocall_txt3'></div>" +
                    "<div>" +
                    "</div>";

                var $html = $(html);
                $(html).find(".inside_clicktocall_connecting").hide();
                $html.insertAfter(".inside_clicktocall_request");
                $(".inside_clicktocall_request").remove();
            }

            var settings = clickToCallSettings && clickToCallSettings.connectingForm ? clickToCallSettings.connectingForm : {};
            var title = settings.title || insideFrontInterface.chat.translate("CONNECTING YOU");

            var text = "";
            if (success === true) {
                if (settings.text1) { text = settings.text1; }
                else { text = "Thanks, please stand by. An expert will be calling you soon."; }
            } else if (success == false) {
                if (settings.text2) { text = settings.text2; }
                else { text = "Sorry, we could not place your request. Please try later."; }
            } else {
                text = "Please wait, while we place your request.";
            }

            $(".inside_chatPane_header_text_c2c").text(title);
            $("#inside_holder .inside_clicktocall_connecting .inside_clicktocall_txt3").html(text);

            $("#inside_holder .inside_clicktocall_connecting .inside_clicktocall_close").off("click").on("click", function (e) {
                $("#inside_holder .inside_clicktocall_connecting").hide();
                $("#inside_clickToCallChatTab").show();
            });

            $("#inside_clickToCallChatTab").hide();
            $("#inside_holder .inside_clicktocall_connecting").show();

            insideFrontInterface.scale();
        }

        var clickToCallAutoHideTimeout;
        function startAutoHideClickToCallTab() {
            $("#inside_clickToCallChatTab").bind("mouseenter", hoverShowClickToCallTab);
            $("#inside_clickToCallChatTab").bind("mouseleave", function () {
                clickToCallAutoHideTimeout = setTimeout(autohideClickToCallTab, 100);
            });

            autohideClickToCallTab();
        }

        function hoverShowClickToCallTab() {
            clearTimeout(autoHideTimeout);
            if (tabPosition == "left" || tabPosition == "topleft" || tabPosition == "bottomleft") {
                $("#inside_clickToCallChatTab").stop(true).animate({ left: 0 }, 500);
            } else {
                $("#inside_clickToCallChatTab").stop(true).animate({ right: 0 }, 500);
            }
        }

        frontEnd.autohideClickToCallTab = autohideClickToCallTab;
        function autohideClickToCallTab(time) {
            if (typeof (time) == "undefined") {
                time = 1000;
            }
            var hideAmount = 20;
            if (typeof (frontEnd.settings.autoHideAmount) != "undefined" && frontEnd.settings.autoHideAmount != "" && !isNaN(frontEnd.settings.autoHideAmount)) {
                hideAmount = parseInt(frontEnd.settings.autoHideAmount);
            }

            $("#inside_clickToCallChatTab").show();
            var tabWidth = $("#inside_clickToCallChatTab").width();

            if (tabPosition == "left" || tabPosition == "topleft" || tabPosition == "bottomleft") {
                $("#inside_clickToCallChatTab").animate({ left: -tabWidth + hideAmount }, time);
            } else {
                if (time != 0) {
                    $("#inside_clickToCallChatTab").animate({ right: -tabWidth + hideAmount }, time);
                } else {
                    $("#inside_clickToCallChatTab").show();
                    setTimeout(function () {
                        $("#inside_clickToCallChatTab").css({ right: -tabWidth + hideAmount });
                    }, 0);
                }
            }

            if (insideFrontInterface.chat.chatPaneOpen) {
                $("#inside_clickToCallChatTab").hide();
            }
        }

        //#endregion ClickToCall

        var chatSurveyQueue = [];
        frontEnd.chatSurveyQueue = chatSurveyQueue;

        function checkChatSurveyQueue() {
            if (typeof (insideFrontInterface) == "undefined" || typeof (insideFrontInterface.openChatPane) == "undefined") {
                setTimeout(checkChatSurveyQueue, 1000);
                return;
            }
            if (chatSurveyQueue.length > 0) {
                if (chatSurveyQueue[0].settings.surveyid && chatSurveyQueue[0].settings.surveyid > 0 && insideFrontInterface.getAvailableAssistants && insideFrontInterface.getAvailableAssistants().length > 0 && chatSurveyQueue[0].settings.containerid == "#inside_chatWindow, #inside_chatPane_custom_chatHolder") {
                    insideFrontInterface.openChatPane(true);
                    if ($("#inside_chatWindow, #inside_chatPane_custom_chatHolder").length > 0 || typeof insideChatPane !== "undefined") {
                        if(typeof insideFrontInterface.chat.clearChatGrouping == "function") {
                            //this is in legacychat
                            insideFrontInterface.chat.clearChatGrouping();
                        }
                        for (var i = 0; i < chatSurveyQueue.length; i++) {
                            showSurveyPopup(chatSurveyQueue[i]);
                        }
                    } else {
                        setTimeout(checkChatSurveyQueue, 1000);
                    }
                } else {
                    for (var i = 0; i < chatSurveyQueue.length; i++) {
                        showSurveyPopup(chatSurveyQueue[i]);
                    }
                }

            }
        }

        frontEnd.showSurveyPopup = showSurveyPopup;
        function showSurveyPopup(data) {
            _insideGraph.loadModule("visitornotify", "inside.front.visitornotify.js").then(function () {
                if ($("#insideSurveyHolder").length > 0) {
                    return;
                    //a survey is already showing
                }
                if (!data || !data.settings || !data.settings.surveyid || isNaN(data.settings.surveyid) || data.settings.surveyid < 1) {
                    return;
                    //invalid/junk event
                }
                //remove popups in the same
                $(".inside_visitorNotify[position='" + data.settings.position + "']").remove();

                if (typeof (data.settings.bg) == "undefined" || data.settings.bg == "") {
                    data.settings.bg = "#ffffff";
                }

                var popup = visitorNotify(data, function(popup) {
                    if (!popup) return;
                        loadInsideSurvey(function () {
                        showSurvey(data, popup);
                        insideFrontInterface.visitorNotify.positionPopupOffScreen (popup);
                    });
                });                
            });
        }

        var loadingSurvey = false;
        function showSurvey(data, popup) {
            if(loadingSurvey) {
                return;
            }
            if(typeof insideSurvey == "undefined") {
                loadingSurvey = true;
                loadInsideSurvey(function () {
                    loadingSurvey = false;
                    showSurvey(data, popup);
                });
                return;
            }

            var surveyInChat = data.settings.containerid == "#inside_chatWindow, #inside_chatPane_custom_chatHolder";
            if ((surveyInChat && insideFrontInterface.chatReady != true)
                || (surveyInChat && $("#inside_chatWindow, #inside_chatPane_custom_chatHolder").length == 0)) {
                //chat not ready

                setTimeout(function () {
                    insideFrontInterface.openChatPane(true);
                }, 1000);
                setTimeout(function () {
                    showSurvey(data);
                }, 1500);
                return;
            }

            if(surveyInChat) {
                if ($("#inside_prechatForm").length > 0) {
                    $("#inside_prechatForm").remove();
                }
            }
            
            insideSurvey.showSurvey(data.settings.surveyid, "insideSurveyHolder", function (container) {
                //var popup = $("#insideSurveyHolder").closest(".inside_visitorNotify");

                if(surveyInChat) {
                    if ($("#inside_prechatForm").length > 0) {
                        $("#inside_prechatForm").remove();
                    }
                }
                
                if (data.type == "survey" && typeof (data.settings.headercolour) != "undefined" && data.settings.headercolour != "") {
                    popup.find(".inside_siteLogo, .inside_survey_header").css("background", data.settings.headercolour);

                    if (getBrightnessOfColour(data.settings.headercolour) < 120) {
                        popup.find(".inside_closeButton, .inside_survey_header").css("color", "white");
                    }

                } else {
                    if (typeof (frontEnd.settings.headerColour) != "undefined" && frontEnd.settings.headerColour != null && frontEnd.settings.headerColour != "") {
                        popup.find(".inside_siteLogo").css("background", frontEnd.settings.headerColour);
                    }
                    if (data.type == "survey" && typeof (frontEnd.settings.iconColour) != "undefined" && frontEnd.settings.iconColour != "") {
                        popup.find(".inside_closeButton, .inside_survey_header").css("color", frontEnd.settings.iconColour);
                    }
                }

                if (data.settings.headerTextColour) {
                    addStyleString("#inside_holder .inside_visitorNotify.survey[eventid='" + data.eventId + "'] .inside_survey_header {color: " + data.settings.headerTextColour + " !important}");
                }
                if (data.settings.iconColour) {
                    addStyleString(".inside_visitorNotify.survey .inside_closeButton {color: " + data.settings.iconColour + " !important}");
                }
                if (data.settings.buttonColour) {
                    container.find(".inside_survey_header").css("color", data.settings.buttonColour);
                    addStyleString("#inside_holder .inside_visitorNotify.survey[eventid='" + data.eventId + "'] .insideSubmitButton { background: " + data.settings.buttonColour + "}");
                }
                if (data.settings.buttonTextColour) {
                    addStyleString("#inside_holder .inside_visitorNotify.survey[eventid='" + data.eventId + "'] .insideSubmitButton { color: " + data.settings.buttonTextColour + "}");
                }

                if (popup.length == 0) {
                    return; //survey holder not found
                }
                insideFrontInterface.visitorNotify.positionPopupOffScreen (popup);
                popup[0].ready = true;
                insideFrontInterface.visitorNotify.slideInPopup(popup);
                if (data.type == "chatsurvey") {
                    if (data.settings.containerid == "#inside_chatWindow, #inside_chatPane_custom_chatHolder") {
                        //check if it's a linked survey
                        if ($("#inside_chatWindow, #inside_chatPane_custom_chatHolder").find(".inside_visitorNotify.embed.survey").length == 0) {
                            insideFrontInterface.chat.scrollChatToBottom();
                            insideFrontInterface.openChatPane(true);
                            insideFrontInterface.chat.positionChatPane();
                        }
                    } else {
                        insideFrontInterface.chat.closeChatPane();
                    }
                }

                var surveyInputs = $("#insideSurveyHolder").find('input, textarea, select');
                for (var i = 0; i < surveyInputs.length; i++) {
                    surveyInputs[i].setAttribute('tabindex', 1);
                    /*
                    if (surveyInputs[i].value == '')
                        surveyInputs[i].focus();
                    */
                }

            }, data);
            if (typeof (data.settings.headercolour) != "undefined" && data.settings.headercolour != "") {
                var styleString = "";
                //styleString += "#insideSurveyHolder p.insideSurveyQuestion{background:" + data.settings.headercolour + ";}";
                //styleString += ".inside_visitorNotify.survey .inside_closeButton{background-color:" + data.settings.headercolour + ";}";
                if (data.settings.headercolour != "#ffffff" && data.settings.headercolour != "white") {
                    styleString += ".inside_visitorNotify.survey{border-bottom: 6px solid " + data.settings.headercolour + "}";
                } else {
                    styleString += ".inside_visitorNotify.survey{border-bottom: 1px solid #cccccc}";
                }



                //use black or white text?

                if (getBrightnessOfColour(data.settings.headercolour) > 150) {
                    styleString += "#insideSurveyHolder p.insideSurveyQuestion{ color: black; }";
                }

                addStyleString(styleString, "insideSurvey");
            }
        }

        function getBrightnessOfColour(colourString) {
            var rgb = [];
            if (colourString.indexOf("#") == 0) {
                rgb.push(parseInt(colourString.substr(1, 2), 16));
                rgb.push(parseInt(colourString.substr(3, 2), 16));
                rgb.push(parseInt(colourString.substr(5, 2), 16));
            } else {
                var rgba = colourString.split("(")[1].split(")")[0].split(",");
                rgb.push(parseInt(rgba[0], 16));
                rgb.push(parseInt(rgba[1], 16));
                rgb.push(parseInt(rgba[2], 16));
            }

            return 0.213 * rgb[0] + 0.715 * rgb[1] + 0.072 * rgb[2];
        }

        frontEnd.users = {};
        function updateUsers(data) {
            for (var i = 0; i < data.length; i++) {
                if (typeof (frontEnd.users[data[i].id]) != "undefined" && frontEnd.users[data[i].id] != null) {
                    $.extend(frontEnd.users[data[i].id], data[i]);
                } else {
                    frontEnd.users[data[i].id] = data[i];
                }
            }
            if(typeof insideFrontInterface.chat.setChatTab == "function") {
                insideFrontInterface.chat.setChatTab();
            }
            triggerAssistantEvents();
        }
        function removeUsers(arr) {
            for (var i = 0; i < arr.length; i++) {
                delete frontEnd.users[arr[i]];
            }
            insideFrontInterface.chat.setChatTab();
            triggerAssistantEvents();
        }

        var assistantEvents = [];
        insideFrontInterface.assistantEvents = assistantEvents;
        insideFrontInterface.bind = function (type, callback) {
            if (type == "assistants") {
                assistantEvents.push(callback);
            }
        }  
        function triggerAssistantEvents() {
            var availableAssistants = insideFrontInterface.getAvailableAssistants();
            try {
                _insideGraph.doEvent("chatavailable", availableAssistants.length > 0);
            } catch (ex) { }
            var assistantEvents =  insideFrontInterface.assistantEvents;
            if (assistantEvents && assistantEvents.length > 0) {
                for (var i = 0; i < assistantEvents.length; i++) {
                    assistantEvents[i](availableAssistants);
                }
            }
        }

        frontEnd.bindEvent = bindEvent;
        function bindEvent(eventName, callback) {
            $.inside.bind(eventName, callback);
        }

        var assistantData = [];
        frontEnd.settings = {};
        var alreadyConnected = false;
        var altChatSettingsSet = false;
        var savedAltChat;

        insideFrontInterface.getChatSettings = getChatSettings;
        function getChatSettings() {
            return chatPaneVersion() == 2 ? $.inside.front.settingsData : $.inside.front.settingsData.settings;
        }

        /* The chat theme can be dynamically updated with this function, eg from an event. */
        insideFrontInterface.mergeNewChatSettings = mergeNewChatSettings;
        function mergeNewChatSettings(_chatSettings) {
            $.extend(true, insideChatPane.settings.chatSettings, _chatSettings);
            frontEnd.settings.chatSettings = insideChatPane.settings.chatSettings;
            insideChatPane.setStyling(insideChatPane.settings.chatSettings);
        }

        function connectedToInside(data) {
            console.log("front.js => connectedToInside");
            waitingForConnected = false;
            $.inside.videoChat = false;
            $.inside.connection.id = data.connectionId;

            /* For single page applications and reconnecting to existing pages, settings are updated here. */
            if (alreadyConnected) {
                 if(data.chatSettingsId == 0) {
                    //something went wrong, unexpected data returned. Use existing data.
                    data = frontEnd.settingsData;
                }

                frontEnd.settingsData = data;
                frontEnd.users = [];
                if (typeof (data.users) != "undefined" && data.users.length > 0) {
                    updateUsers(data.users);
                }

                //update chat settings
                if (data.chatSettings) {
                    if (typeof (insideChatPane) != "undefined") {
                        insideChatPane.settings = data.settings;
                        insideChatPane.settings.chatSettings = data.chatSettings;
                        insideChatPane.settings.mimeTypes = data.mimeTypes;
                    }
                    $.extend(frontEnd.settings, data.chatSettings.chatTab);
                    $.extend(frontEnd.settings, data.chatSettings.chatPane);
                    $.extend(frontEnd.settings.offlineChat, data.chatSettings.offline);
                    frontEnd.settings.chatSettings = data.chatSettings;
                    if (typeof frontEnd.settings.chatSettings !== "undefined") frontEnd.settings.chatSettings.chatSettingsId = data.chatSettingsId;
                    if (typeof (insideChatPane) != "undefined" && typeof insideChatPane.setStyling == "function") insideChatPane.setStyling(data.chatSettings);
                    if (typeof insideFrontInterface.updateChatSettings != "undefined") insideFrontInterface.updateChatSettings(data.chatSettings);

                    setTabPosition();

                    if(typeof data.preChat != "undefined") {
                        frontEnd.settings.preChat = data.preChat;
                    }
                }

                if (typeof data.video == "undefined" && typeof data.videoNewTabMsg == "undefined" && typeof insideChatPane != "undefined" && insideChatPane.videoChat && insideChatPane.videoChat.state == "open") {
                    //video chat has been ended while signalr was not connected - close the video chat.
                    insideChatPane.videoChat.close();
                }

                var availableAssistants = getAvailableAssistants();
                _insideGraph.doEvent("chatavailable", availableAssistants.length>0);
                

                /* on a SPA the accessKey will change on connected, old non-sticky popups can be cleared */
                var urlChanged = _insideGraph.accessKey != prevAccessKey;
                if(typeof insideFrontInterface.initVisitorNotifyModule != "undefined") {
                    if(urlChanged) {
                        insideFrontInterface.initVisitorNotifyModule.clearNonStickyPopups();
                    }
                    prevAccessKey = _insideGraph.accessKey;
                }
                return;
            }

            prevAccessKey = _insideGraph.accessKey;

            alreadyConnected = true;
            insideFrontInterface.chatReady = true;

            if (typeof (data.settings) != "undefined" && data.settings != null)
                frontEnd.settings = data.settings;
            
            if(typeof data.preChat != "undefined")
                frontEnd.settings.preChat = data.preChat;

            frontEnd.settingsData = data;
            frontEnd.nickname = data.nickname;
            frontEnd.settings.mimeTypes = data.mimeTypes;

            insideFrontInterface.chat = insideFrontInterface.chat || {};
            insideFrontInterface.chat.userid = data.userid;

            var chatSettings = data.chatSettings || getChatSettings();
            let language = 'en';
            if(data.lang && data.lang != "visitorDataMappings") {
                language = data.lang;
            } else if (chatSettings.language && chatSettings.language != "" && chatSettings.language != "visitorDataMappings") {
                language = chatSettings.language;
            } else if (navigator.language) {
                language = navigator.language;
            }
            insideFrontInterface.language = language;
            isLanguageSet = true;

            setTimeout(checkChatVisible, 0);

            if (frontEnd.settings.addCustomCSS != false && typeof (frontEnd.settings.insideCustomCSSFile) != "undefined") {
                loadCssFile(_insideCDN + frontEnd.settings.insideCustomCSSFile, windowScale);
            }
            if (frontEnd.settings.addCustomJS != false && typeof (frontEnd.settings.insideCustomJSFile) != "undefined") {
                _insideGraph.loadJS(_insideCDN + frontEnd.settings.insideCustomJSFile + '?v=' + _insideScriptVersion);
            }
            if (altChatSettingsSet == true) {
                $.extend(frontEnd.settings, savedAltChat.chatTab);
                $.extend(frontEnd.settings, savedAltChat.chatPane);
                $.extend(frontEnd.settings.offlineChat, savedAltChat.offline);
                $.inside.front.settingsData.settings = frontEnd.settings;
                frontEnd.settings.useCustomChatPane = (savedAltChat.chatPane.useCustomChatPane == true);
                frontEnd.settings.chatSettings = data.chatSettings;
            } else {
                if (typeof (data.chatSettings) != "undefined" && data.chatSettings != null) {
                    savedAltChat = data.chatSettings;
                    savedAltChat.chatSettingsId = data.chatSettingsId;
                    insideFrontInterface.chatSettings = savedAltChat;
                    altChatSettingsSet = true;
                    frontEnd.settings.chatSettings = data.chatSettings;
                    if (data.chatSettings.preChat && typeof (data.chatSettings.preChat) == "object" && Object.keys(data.chatSettings.preChat).length > 0) {
                        frontEnd.settings.preChat = data.chatSettings.preChat;
                    }
                    if(frontEnd.settings.chatSettings.version == "2" && typeof insideChatPaneFrame != "undefined") {
                       // insideChatPane.init($, frontEnd.settings);
                       //insideChatPaneFrame.init($, frontEnd.settings); //moved to inside.chat

                       if (data.chatSettings && data.chatSettings.chatTab) { // reset the default value from legacy chat tab setting
                        delete frontEnd.settings.mobileTabWidth;
                       }
                    }
                    $.extend(frontEnd.settings, data.chatSettings.chatTab);
                    $.extend(frontEnd.settings, data.chatSettings.chatPane);
                    $.extend(frontEnd.settings.offlineChat, data.chatSettings.offline);
                    if (data.chatSettings && data.chatSettings.chatPane) {
                        frontEnd.settings.useCustomChatPane = (data.chatSettings.chatPane.useCustomChatPane == true);
                        if (!data.chatSettings.chatPane.chatInputPlaceholder)
                            frontEnd.settings.chatInputPlaceholder = "";
                        if (!data.chatSettings.chatPane.chatInputDisabledPlaceholder)
                            frontEnd.settings.chatInputDisabledPlaceholder = "";
                    }
                    $("#inside_holder").attr("chatSettingsId", data.chatSettingsId);
                }
            }

            insideFrontInterface.labelTranslations = data.labels;

            if (window.top != window) {
                if (frontEnd.settings.allowIframes != true) {
                    $("#inside_holder").remove();
                    return;
                }
            }

            if (typeof (frontEnd.settingsData.users) != "undefined" && frontEnd.settingsData.users.length > 0) {
                updateUsers($.inside.front.settingsData.users);
            }

            if (frontEnd.settings.chatEnabled == false) {
                chatEnabled = false;
            }           

            //TO DO - make this happen after all necessary files are loaded.
            setTimeout(function () { $.inside.flushQueue(); }, 1000);
            
            insideFrontInterface.videoChatRequested = data.videoChat;
            if (typeof (insideFrontInterface.videoChat) == "undefined") {
                insideFrontInterface.videoChat = { disableChatOnVideoCall: data.disableChatOnVideoCall }
            }
            else
                insideFrontInterface.videoChat.disableChatOnVideoCall = data.disableChatOnVideoCall;

            if (insideFrontInterface.videoChatRequested != true) {
                try {
                    insideChatPane.removeVideoChatNotification();
                }
                catch { }
            }
            if (data.video) {
                frontEnd.settingsData.video = data.video;
                insideFrontInterface.videoChatRequested = false;
            }

            if (chatEnabled) {
                _insideGraph.initModule("tabs");
                setTabPosition();
                startautohideTabs();
            }

            if (chatEnabled) {
                if (frontEnd.settings.showChatPaneHeaderAsChatTab && insideFrontInterface.showChatPaneHeaderForDevice() && !insideFrontInterface.chat.isTabHiddenOnThisDevice()) {
                    $.inside.front.loadInsideChat();
                }
            }

            var isAppointment = false;
            try {
                isAppointment = getQueryStringParameterByName("insidechatlinksrc").includes('appt');
             } catch (ex) {
                isAppointment = false;
            }
            if ((data.chats && data.chats.length)
                || (typeof (data.workflow) != "undefined" && data.workflow != null)
                || data.chatlinkvisitor != null
                || isAppointment) {
                loadInsideChat();
            }

             //todo: if show avatar immediately
            if(chatSettings.chatPane.showAvatars && sessionStorage.getItem("disableInsideAvatars") != "true") {
                insideFrontInterface.showAvatarsAlways = true;
                loadInsideChat();
            }

            if(typeof insideStreamingCheck != "undefined") {
                insideStreamingCheck.init($);
            }            

            insideFrontInterface.chat.data = insideFrontInterface.chat.data || {};
            insideFrontInterface.chat.data.flags = insideFrontInterface.chat.data.flags || data.flags;

            var availableAssistants = getAvailableAssistants();
            if(availableAssistants.length == 0) {
                _insideGraph.doEvent("chatavailable", false);
            }

            //check if currently viewing a live show
            var currentStream = sessionStorage.getItem('inside_currentStream');
            if (currentStream != "" && currentStream != null) {
                if(!window.insideStreamingCheck.bundleLoaded) {
                    window.insideStreamingCheck.loadStreamingBundle();
                }
            }

            if (typeof window.insideStreaming !== "undefined") {
                window.insideStreaming.refreshStreamList();
            }

            var videoKey = getQueryStringParameterByName('vfvid');
            if(videoKey) {
                insideAPI.post(_insideCDN + "api/operator/decodeSharedVideoKey", {
                    key: videoKey
                }, function (sharedVideo) {
                    if (!sharedVideo) {
                        return;
                    }
                    $.inside.front.loadInsideChat(function() {
                        _insideGraph.defer(function() {
                            //insideChatPane.videoPopupMode = true;
                            insideChatPane.frame.contentWindow.insideVideos.showVideoPopupFromLink(sharedVideo.fileLibrary, sharedVideo.shareId, sharedVideo.assignType);
                        }, function(){
                            return typeof insideChatPane !== "undefined" && insideChatPane.chatPane;
                        });
                    });
                }, function(e) {

                });
            }

            var showId = getQueryStringParameterByName('showid');
            if(showId) {
                insideAPI.post(_insideCDN + "api/videoshows/decodeSharedShowKey", {
                    key: showId
                }, function(sharedShow) {
                    if(!sharedShow) {
                        return;
                    }
                    $.inside.front.loadInsideChat(function() {
                        _insideGraph.defer(function() {
                            //insideChatPane.videoPopupMode = true;
                            insideChatPane.frame.contentWindow.insideVideos.showVideoShowPopup(sharedShow);
                        }, function(){
                            return typeof insideChatPane !== "undefined" && insideChatPane.chatPane;
                        });
                    });
                }, function(e) {

                });
            }

            if(data.proactiveMessage) {
                proactiveMessage(data.proactiveMessage);
            }
        }

        insideFrontInterface.updateChatSettings = updateChatSettings;
        function updateChatSettings(_chatSettings) {
            chatSettings = insideFrontInterface.chatSettings = _chatSettings;
            insideFrontInterface.chat.setChatTab(undefined, true);
        }

        /* load in the translations for the current language. This was omitted from the connected data to save on realtime bandwidth.*/
        var languageTranslationsLoaded = false;
        var languagesLoading = false;
        var isLanguageSet = false;
        insideFrontInterface.languagesLoading = false;
        insideFrontInterface.languageTranslationsLoaded = false;
        insideFrontInterface.loadTranslations = loadTranslations;
        var labelCallbacks = [];
        function loadTranslations(callback) {
            if(languageTranslationsLoaded) {
                if(typeof callback == "function") {
                    callback();
                }
                return;
            };
            if(languagesLoading) {
                if(typeof callback == "function") labelCallbacks.push(callback);
                return;
            }

            languagesLoading = true;
            insideFrontInterface.languagesLoading = true;

            _insideGraph.defer(function() {
                insideAPI.get(_insideCDN + "api/websites/labels/" + insideFrontInterface.language + "?acc=" + _insideGraph.current.account + "&v=" + _insideScriptVersion, {}, function(response) {
                    insideFrontInterface.labelTranslations = response;
                    languageTranslationsLoaded = true;
                    insideFrontInterface.languageTranslationsLoaded = true;
                    insideFrontInterface.languagesLoading = languagesLoading = false;

                    if (typeof callback == "function") {
                        callback();
                    }
                    //call any other queued callbacks.
                    for (var i = 0; i < labelCallbacks.length; i++) {
                        labelCallbacks[i]();
                    }
                }, function (err) {
                    console.error("Error loading inside translation labels.");
                    languageTranslationsLoaded = true;
                    insideFrontInterface.languageTranslationsLoaded = true;

                    if (typeof callback == "function") {
                        callback();
                    }

                    for (var i = 0; i < labelCallbacks.length; i++) {
                        labelCallbacks[i]();
                    }
                });
            }, function () {
                return isLanguageSet;
            });
        }

        insideFrontInterface.getLanguageValue = getLanguageValue;
        function getLanguageValue(ob) {
            if (typeof (ob) == "undefined" || !ob) {
                return "";
            }
            if (typeof ob == "string") {
                return ob;
            } else if (typeof ob[insideFrontInterface.language] != "undefined") {
                return ob[insideFrontInterface.language] || ob["en"] || "";
            } else if (insideFrontInterface.language.indexOf("-") !== -1 && typeof ob[insideFrontInterface.language.split("-")[0]] == "string") {
                return ob[insideFrontInterface.language.split("-")[0]];
            } else if (Object.keys(ob).length > 0) {
                for (var property in ob) {
                    if (property === "type") continue;
                    return ob[property];
                }
                return "";
            } else {
                return "";
            }
        }

        function checkChatVisible() {
            var chatSettings = getChatSettings();
            var chatIsVisible = true;
            var data = frontEnd.settingsData;
            try {
                if (chatSettings.useMinimiseButton === true && (hasSessionStorage && sessionStorage.getItem("insideChatClosed") === "True") || insideFrontInterface.chat.isTabHiddenOnThisDevice()) {
                    chatIsVisible = false;
                }
            } catch (e) { }

            if (typeof data.chats != "undefined" && data.chats.length > 0 && (chatSettings.showTabForActive === true || chatSettings.showPaneForActive === true)) {
                chatIsVisible = true;
            }
            _insideGraph.doEvent("chat_visible", chatIsVisible); //chat is visible or not
        }


        insideFrontInterface.setTabPosition = setTabPosition;
        function setTabPosition() {

            if (device >= 2 && typeof (frontEnd.settings.mobileTabPosition) != "undefined") {
                tabPosition = frontEnd.settings.mobileTabPosition || "9";
            } else if (typeof (frontEnd.settings.tabPosition) != "undefined") {
                tabPosition = frontEnd.settings.tabPosition || "6";
            }

            var posNumbers = { 1: "topleft", 2: "top", 3: "topright", 4: "left", 5: "bottom", 6: "right", 7: "bottomleft", 8: "bottom", 9: "bottomright"};
            if(!isNaN(tabPosition)) {
                tabPosition = posNumbers[tabPosition];
            }

            if ($("#inside_liveChatTab").hasClass("usingChatHeader")) {
                if (tabPosition.indexOf("left") != -1) {
                    tabPosition = "bottomleft";
                } else {
                    tabPosition = "bottomright";
                }
            }

            if(frontEnd.settings.chatSettings && frontEnd.settings.chatSettings.version == "2") {
                tabPosition = posNumbers[frontEnd.settings.chatSettings.chatTab.position] || "right";
                if(device >= 2) {
                    tabPosition = posNumbers[frontEnd.settings.chatSettings.chatTab.mobileTabPosition] || "right";                    
                }
            } else if(typeof(insideChatPane) != "undefined" && insideChatPane.settings && insideChatPane.settings.chatSettings.chatTab.position) {
                if(device >= 2) {
                    tabPosition = insideChatPane.settings.chatSettings.chatTab.mobileTabPosition || "9";
                } else {
                    tabPosition = insideChatPane.settings.chatSettings.chatTab.position || "6";
                }
                tabPosition = posNumbers[tabPosition];
            }

            tabYScale = 0.5;
            const holderStyle = document.getElementById('inside_holder').style;

            if (tabPosition.includes("right")) {
                holderStyle.setProperty(`--inside-tab-right`, '0px');
                holderStyle.setProperty(`--inside-tab-left`, 'auto');
            } else if (tabPosition.includes("left")) {
                holderStyle.setProperty(`--inside-tab-right`, 'auto');
                holderStyle.setProperty(`--inside-tab-left`, '0px');
            }

            if (tabPosition.includes("top")) {
                tabYScale = 1.0;
            } else if (tabPosition.includes("bottom")) {
                tabYScale = 0.0;
            }

            $("#inside_tabs").attr('position', tabPosition)

            insideFrontInterface.chat.setTabOffsetPosition();

            windowScale(); // to set the vertical tab position (#19084)

            initPositionOverrides();
        }

        function unquoteAttr(s, preserveCR) {
            return ('' + s)
                .split('&amp;').join("&")
                .replace(/&apos;/g, '')
                .replace(/&quot;/g, '"')
                .replace(/&lt;/g, '<')
                .replace(/&gt;/g, '>')
                .replace(/&#10;/g, "\r\n")
                .replace(/&#39;/g, '"')
                .replace(/&nbsp;/g, ' ')
                .replace(/&#13;/g, "\r\n")
                ;
        }      

        function loadFacebookSDK() {
            (function (d, s, id) {
                var js, fjs = d.getElementsByTagName(s)[0];
                if (d.getElementById(id)) { return; }
                js = d.createElement(s);
                js.id = id;
                js.src = '//connect.facebook.net/en_US/sdk.js';
                fjs.parentNode.insertBefore(js, fjs);
            }(document, 'script', 'facebook-jssdk'));
        }

        window.fbAppId = window.fbAppId || "";
        window.fbQueue = window.fbQueue || [];
        window.fbReady = window.fbReady || false;

        window.fbAsyncInit = window.fbAsyncInit || function () {
            FB.init({ appId: window.fbAppId, xfbml: false, version: 'v21' });
            window.fbReady = true;
            window.processFbQueue();
        };

        window.processFbQueue = window.processFbQueue || function () {
            if (!window.fbReady) { return; }
            if (window.fbQueue.length === 0) { return; }
            fbQueue.shift().call(window);
            setTimeout(window.processFbQueue, 0);
        };

        //visitor popup
        frontEnd.visitorNotify = visitorNotify;
        function visitorNotify(data, callback) {
            /* load in visitor notify module */
            /* send data to module */
            if(insideFrontInterface.visitorNotify) {
                var popup = insideFrontInterface.visitorNotify.show(data);
                if(typeof callback == "function") {
                    callback(popup);
                }
                return;
            }

            loadCssFile(_insideCDN + "./fonts/insideicons/front/icoinside-front-surveys.css?" + _insideScriptVersion);
            _insideGraph.loadModule("visitornotify", "inside.front.visitornotify.js").then(function () {
                var popup = insideFrontInterface.visitorNotify.show(data);
                if(typeof callback == "function") {
                    callback(popup);
                }
            });
        }

        function getSelectionText() {
            var text = "";
            if (window.getSelection) {
                text = window.getSelection().toString();
            } else if (document.selection && document.selection.type != "Control") {
                text = document.selection.createRange().text;
            }
            return text;
        }        

        function disconnected() {
            console.log("disconnected from inside");
            $("#inside_liveChatTab").hide();
            // alreadyConnected = false;
            
            if (chatPaneVersion() === 2 && typeof insideChatPane !== "undefined" && typeof insideChatPane.disconnectedReceived === "function") {
                insideChatPane.disconnectedReceived();
            }
            
        }

        var scaleinit = false;
        var chatPaneMode = "";
        var tabYScale = 0.5;
        var viewport;

        frontEnd.windowScale = windowScale;
        insideFrontInterface.windowScale = windowScale;

        function windowScale(animTime) {
            if (typeof (animTime) == "undefined") {
                animTime = 0;
            }
            viewport = getViewPortSize();

            var offset = viewport.height * tabYScale;

            if (device == 3 && (navigator.platform.indexOf("iPhone") != -1 || navigator.platform.indexOf("iPad") != -1)) {
                offset = viewport.height * tabYScale * getViewportScale();
            }
            if (tabPosition == "left" || tabPosition == "right") {
                offset -= $("#inside_liveChatTab").height() * 0.5;
            }
            if (device > 1 && tabPosition.startsWith('top')) {
                if (typeof (document.documentElement) != 'undefined' && typeof (document.documentElement.clientHeight) != 'undefined' && offset > document.documentElement.clientHeight) {
                    if (device !== 1 && document.documentElement.clientHeight < window.innerHeight) {
                        offset = window.innerHeight;
                    } else {
                        offset = document.documentElement.clientHeight;
                    }
                }
                if (!insideFrontInterface.chat.chatPaneOpen && $("#inside_tabs").is(":visible") && !$("#inside_tabs").is(':empty') && $("#inside_liveChatTab").height() == 0 && $(".inside-notification").length == 0) {
                    setTimeout(windowScale, 250);
                }
            }

            if(tabPosition.startsWith('top')) {
                offset -= $("#inside_liveChatTab").height();
                if($('#inside_clickToCallChatTab').height()) {
                    offset -= $('#inside_clickToCallChatTab').height();
                }
            }

            if (!animTime)  {
                if (!(ios && !standalone && safari && $('input').is(":focus"))) {
                    document.getElementById('inside_holder').style.setProperty(`--inside-tab-bottom`, offset + 'px');
                }
            }

            if(insideFrontInterface.visitorNotify) {
                insideFrontInterface.visitorNotify.scalePopups();
            }

            if (IE11Quirks) {
                IE11ScrollFix();
            }

            var disableChatOnVideoCall = insideFrontInterface.chat.settings && insideFrontInterface.chat.settings.preChat && insideFrontInterface.chat.settings.preChat.disableChatOnVideoCall == true && typeof (insideChatPane) != "undefined" && typeof (insideChatPane.videoChat) != "undefined" && insideChatPane.videoChat.disableChatOnVideoCall==true;
            if (document.getElementById('inside_holder') != null) {
                if (window.innerHeight > window.innerWidth || disableChatOnVideoCall) {
                    document.getElementById('inside_holder').classList.add("portrait");
                } else document.getElementById('inside_holder').classList.remove("portrait");
            }
        }

        insideFrontInterface.positionTabs = positionTabs;
        function positionTabs() {
            if (tabPosition.indexOf("right") != -1) {
                $("#inside_tabs").removeClass("leftTabPosition");
            } else {
                $("#inside_tabs").addClass("leftTabPosition");
            }
            $("#inside_tabs > div").each(function () {
                $(this).css({ "left": "", "right": "" });
                if (tabPosition.indexOf("right") != -1) {
                    if (frontEnd.settings.autohideTabs && (frontEnd.autoHideAllowed || frontEnd.settings.autoHideTabOnLoad) &&
                        !(device > 1 && frontEnd.settings.autohideOnMobile == false)
                        && !$(this).hasClass("noAutoHide")
                    ) {
                        hideAmount = 20;
                        if (typeof (frontEnd.settings.autoHideAmount) != "undefined" && frontEnd.settings.autoHideAmount != "" && !isNaN(frontEnd.settings.autoHideAmount)) {
                            hideAmount = parseInt(frontEnd.settings.autoHideAmount);
                        }
                        $(this).css("right", hideAmount + "px");
                        $(this).attr("tabHidden", true);
                    } else {
                        if ($(this).hasClass("usingChatHeader")) {
                            $(this).css("right", $(this).outerWidth());
                        } else if ($(this).find("img, svg").length > 0) {
                            $(this).css("right", $(this).find("img, svg").width());
                        } else if($(this).find("svg").length > 0) {
                            $(this).css("right", $(this).find("svg").width());
                        }

                    }
                } else {

                    if (frontEnd.settings.autohideTabs && (frontEnd.autoHideAllowed || frontEnd.settings.autoHideTabOnLoad) &&
                        !(device > 1 && frontEnd.settings.autohideOnMobile == false)
                    ) {
                        hideAmount = 20;
                        if (typeof (frontEnd.settings.autoHideAmount) != "undefined" && frontEnd.settings.autoHideAmount != "" && !isNaN(frontEnd.settings.autoHideAmount)) {
                            hideAmount = parseInt(frontEnd.settings.autoHideAmount);
                        }
                        if ($(this).find("img, svg").length > 0) {
                            $(this).css("left", -$(this).find("img, svg").width() + hideAmount + "px");
                        }
                    } else {
                        if ($(this).find("img, svg").length > 0)
                            $(this).css("left", 0);
                    }
                }
                //if (!frontEnd.autoHideAllowed && !insideFrontInterface.chat.chatPaneOpen && !frontEnd.settings.autoHideTabOnLoad)
                    //frontEnd.autoHideAllowed = true;
            });
        }


        //#region meta viewport
        insideFrontInterface.setMetaViewport = setMetaViewPort;
        var siteViewport = $('meta[name="viewport"]:last'), siteViewportContent, siteViewportId, siteViewportClass;
        if(siteViewport.length > 0) {
            siteViewportContent = siteViewport.attr('content');
            siteViewportId = siteViewport.attr('id');
            siteViewportClass = siteViewport.attr('class');
        }
        function setMetaViewPort() {
            if($('meta[name="viewport"]').length == 0) {
                var meta = document.createElement('meta');
                meta.name = 'viewport';
                document.head.appendChild(meta);
            }

            var metaContent = 'width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no';
            var metaContentChanged = $('meta[name="viewport"]:last').attr("content") != metaContent;

            $('meta[name="viewport"]:last').attr({
                'id': 'inside-viewport',
                'class': 'inside-viewport',
                'content': metaContent
            });


            if (metaContentChanged) {
                /* trigger a scale after the viewport meta tag is updated*/
                if (typeof insideChatPane != "undefined") {
                    setTimeout(insideChatPane.windowScale, 0);
                    setTimeout(insideChatPane.windowScale, 500);
                }
            }
        }

        insideFrontInterface.resetMetaViewport = resetMetaViewPort;
        function resetMetaViewPort() {
            if(siteViewport.length > 0) {
                $('meta[name="viewport"]:last').attr({
                    'id': siteViewportId,
                    'class': siteViewportClass,
                    'content': siteViewportContent
                });
                if(typeof siteViewportClass == 'undefined' || siteViewportClass.length == 0)
                    $('meta[name="viewport"]:last').removeAttr('class');
                if(typeof siteViewportId == 'undefined' || siteViewportId.length == 0)
                    $('meta[name="viewport"]:last').removeAttr('id');
            } else $('meta[name="viewport"]:last').remove();
        }
        //#endregion meta viewport

        //viewport scaling on tablet
        frontEnd.getViewportScale = getViewportScale;
        function getViewportScale() {
            this.viewportScale = 1;
            return this.viewportScale;

        }

        var autoHideTimeout;
        frontEnd.autoHideAllowed = false;
        function startautohideTabs() {
            if (device > 1 && frontEnd.settings && frontEnd.settings.autohideOnMobile === false) {
                return;
            }
            if(frontEnd.settings.chatSettings) {
                if(!frontEnd.settings.chatSettings.chatTab.autohideTabs) {
                    return;
                }
            } else {
                if(!frontEnd.settings.autohideTabs) return;
            }
            $("#inside_tabs").off("mouseenter");
            $("#inside_tabs").off("mouseleave");

            if (device != 2 && device != 3) {
                $("#inside_tabs").on("touchmove", "> div[autohide]", autohideTabs);
                $("#inside_tabs").on("mouseenter", "> div[autohide]", hoverShowTabs);
                $("#inside_tabs").on("mouseleave", "> div[autohide]", function () {
                    autoHideTimeout = setTimeout(autohideTabs, 100);
                    frontEnd.autoHideAllowed = true;
                });
            }
            $("#inside_tabs").off("load").on("load", "img", autohideTabs);
            if (frontEnd.settings.autoHideTabOnLoad != true) {
                positionTabs();
                frontEnd.autoHideAllowed = true;
                autohideTabs();
                
                setTimeout(function() {
                    hoverShowTabs($("#inside_tabs > div[autohide]"));
                    frontEnd.autoHideAllowed = false;
                }, 1000);
                setTimeout(function() {
                    frontEnd.autoHideAllowed = true;
                    autohideTabs();
                }, 5000);
            } else {
                autohideTabs(0);
            }
        }

        frontEnd.autohideTabs = autohideTabs;
        function autohideTabs(time) {
            if (device > 1 && frontEnd.settings.autohideOnMobile == false) {
                return;
            }

            $("#inside_tabs").show();
            if (typeof (time) == "undefined") {
                time = 1000;
            }
            var hideAmount = 20;
            if (typeof (frontEnd.settings.autoHideAmount) != "undefined" && frontEnd.settings.autoHideAmount != "" && !isNaN(frontEnd.settings.autoHideAmount)) {
                hideAmount = parseInt(frontEnd.settings.autoHideAmount);
            }
            /*$("#inside_liveChatTab").show();*/

            $("#inside_tabs > div[autohide]").each(function () {
                autohideTab(this, time);
            });

            if (insideFrontInterface.chat.chatPaneOpen || (insideFrontInterface.getAvailableAssistants && insideFrontInterface.getAvailableAssistants().length == 0)) {
                // $("#inside_liveChatTab").hide();
            }
        }

        frontEnd.autohideTab = autohideTab;
        function autohideTab(tab, time) {
            if (!frontEnd.autoHideAllowed && frontEnd.settings.autoHideTabOnLoad != true) return;
            var $tab = $(tab);
            if ($tab.hasClass("noAutoHide")) {
                $tab.stop(true).animate({ right: $tab.outerWidth() }, 0);
                return;
            }
            if ($tab.attr("autohide")) {
                hideAmount = parseInt($tab.attr("autohide"));
            }
            var tabImage = $tab.find("img, svg");
            var tabWidth = tabImage.width();
            if (tabPosition == "left" || tabPosition == "topleft" || tabPosition == "bottomleft") {
                $tab.stop(true, true).css("left", "0px").animate({ left: -tabWidth + hideAmount }, time);
            } else {
                if (time != 0) {
                    $tab.stop(true, true).animate({ right: hideAmount }, time);
                } else {
                    $tab.stop(true, true).css({ right: hideAmount });
                }
            }
            $tab.attr("tabHidden", "true");
        }

        insideFrontInterface.hoverShowTabs = hoverShowTabs;
        function hoverShowTabs(_tab) {
            if (typeof (_tab.currentTarget) == "undefined") {
                tab = _tab;

            } else {
                tab = $(this);
            }
            clearTimeout(autoHideTimeout);
            if (tabPosition == "left" || tabPosition == "topleft" || tabPosition == "bottomleft") {
                tab.css("right", "");
                tab.stop(true).animate({ left: 0 }, 250);
            } else {
                tab.css("left", "");
                var tabImage = tab.find("img, svg");
                var tabWidth = tabImage.width();
                tab.stop(true).animate({ right: tabWidth }, 250);
            }
            tab.removeAttr("tabHidden", "true");
        }


        frontEnd.getViewPortSize = getViewPortSize;
        function getViewPortSize() {
            var viewportwidth;
            var viewportheight;

            if (device === 2 || device === 3) {
                var zoomLevel = document.documentElement.clientWidth / window.innerWidth;
                viewportheight = window.innerHeight * zoomLevel;
                viewportwidth = document.documentElement.clientWidth;
                if(window.innerWidth !== window.outerWidth) {
                    viewportheight = window.innerHeight;
                    viewportwidth = window.innerWidth;
                }
            } else if (typeof document.documentElement != 'undefined' && typeof document.documentElement.clientWidth != 'undefined' && document.documentElement.clientWidth != 0 && document.documentElement.clientHeight <= window.innerHeight && !firefox) {
                viewportwidth = document.documentElement.clientWidth,
                viewportheight = document.documentElement.clientHeight;
            } else if (typeof window.innerWidth != 'undefined') {
                viewportwidth = window.innerWidth,
                viewportheight = window.innerHeight;
            } else { //Older IE
                viewportwidth = document.getElementsByTagName('body')[0].clientWidth,
                viewportheight = document.getElementsByTagName('body')[0].clientHeight;
            }

            return { width: viewportwidth, height: viewportheight };
        }

        frontEnd.setCookie = setCookie;
        frontEnd.getCookie = getCookie;

        function getCookie(c_name) {
            var i, x, y, ARRcookies = document.cookie.split(";");
            for (i = 0; i < ARRcookies.length; i++) {
                x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
                y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
                x = x.replace(/^\s+|\s+$/g, "");
                if (x == c_name) {
                    return unescape(y);
                }
            }
        }

        function setCookie(c_name, value, exdays) {
            var exdate = new Date();
            exdate.setDate(exdate.getDate() + exdays);
            var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
            document.cookie = c_name + "=" + c_value;
        }

        function trace() {
            var arr = Array.prototype.slice.call(arguments);
            if (typeof (console) != "undefined") {
                console.log(arr.join(","));
            }
        }

        frontEnd.loadCssFile = loadCssFile;
        function loadCssFile(url, callback) {
            _insideGraph.loadCSS(url, callback);
        }

        frontEnd.loadInsideChat = loadInsideChat;
        function loadInsideChat(callback) {
            loadTranslations(function() {
                if(insideFrontInterface.chatPaneVersion() != 2 && typeof insideLegacyChat != "undefined") {
                    //legacy already initted
                    callback();
                    return;
                }
                _insideGraph.loadModule("chat", "frontend-chat.js.bundle").then(function () {
                    if(insideFrontInterface.chatPaneVersion() != 2 && typeof insideLegacyChat == "undefined") {
                        _insideGraph.loadJS(insideScript + "/js/inside.front.legacychat.js?"+_insideScriptVersion, function(){return typeof insideLegacyChat != 'undefined'}, function () {
                            insideLegacyChat.init($);
                            if (typeof (callback) == "function") {
                                callback();
                            }
                        });
                       loadCssFile(_insideCDN + "/css/inside.front.legacychat.css?"+_insideScriptVersion, function(){
                            console.log("legacy css loaded");
                        });
                    } else {
                        console.log("chat bundle loaded")
                        if (typeof (callback) == "function") {
                            callback();
                        }
                    }
                }).catch(function (err) {
                    console.error("Error loading chat module: ", err);
                });
            });
        }

        function loadInsideSurvey(callback) {
            loadCssFile(_insideCDN + "./fonts/insideicons/front/icoinside-front-surveys.css?" + _insideScriptVersion);
           _insideGraph.loadModule("survey", "inside.front.survey.js").then(function () {
                _insideGraph.initModule("survey");
                if (typeof (callback) == "function")
                    callback();
            });
        }

        insideFrontInterface.getAvailableAssistants = getAvailableAssistants;
        function getAvailableAssistants() {
            var assistants = [];
            for (var userid in $.inside.front.users) {
                var user = $.inside.front.users[userid];
                if (typeof (user) != "function" && typeof (user) != "string")
                    assistants.push(user);
            }
            return assistants;
        }

        insideFrontInterface.chatPaneVersion = chatPaneVersion;
        function chatPaneVersion() {
            if (insideFrontInterface && insideFrontInterface.chatSettings && insideFrontInterface.chatSettings.version == "2") {
                usingChatPanev2 = true;
                insideFrontInterface.chat.version = 2;
                return 2;
            }
            insideFrontInterface.chat.version = 1;
            return 1;
        }

        //translations should be from English
        insideFrontInterface.language = "en";
        insideFrontInterface.chat.translate = translate;
        function translate(str) {
            if (typeof (str) == "undefined" || str == null || str == "") {
                return "";
            }

            if (typeof str === "object") {
                str = str[insideFrontInterface.language] || str["en"];
            }

            if (typeof (str) == "undefined" || str == null || str == "") {
                return "";
            }

            //check for direct translation
            if (insideFrontInterface.labelTranslations && insideFrontInterface.labelTranslations.translations[str]) {
                return insideFrontInterface.labelTranslations.translations[str];
            }

            if (insideFrontInterface.labelTranslations && insideFrontInterface.labelTranslations.translations) {
                var squareReplace = /\[(.*?)\]/gi;
                var squareReplace2 = /\[(.*?)\]/i;
                var regExCharReplace = /[-[\]{}()*+?.,\\^$|#\s]/g;

                var clearStr = str.toString().replace(/<br\s*[\/]?>/gi, " ").replace(/\[/g, "XOPENBRACKETX");

                for (var i in insideFrontInterface.labelTranslations.translations) {
                    if (i.indexOf("[") == -1) continue;
                    var englishPhrase = i;
                    var translation = insideFrontInterface.labelTranslations.translations[i];
                    if (typeof (translation) == "undefined") continue;

                    var toMatch = "";
                    toMatch = englishPhrase.replace(squareReplace, "XREPLACEX");
                    toMatch = toMatch.replace(regExCharReplace, "\\$&");
                    toMatch = toMatch.split("XREPLACEX").join("(.*)");
                    toMatch = "^" + toMatch + "(.)*" + "$";
                    var regex = new RegExp(toMatch, "gi");
                    var matches = clearStr.match(regex);
                    if (matches != null && matches.length > 0) {
                        var newStr = translation;
                        if (typeof (translation) == "undefined" || translation == "") {
                            return str;
                        }
                        var contentsOfBrackets;
                        regex.lastIndex = 0;
                        var exec = regex.exec(clearStr);

                        if (exec) {
                            contentsOfBrackets = exec[1];
                        }

                        if (exec.length > 1) {
                            for (var i = 1; i < exec.length; i++) {
                                newStr = newStr.replace(squareReplace2, exec[i]);
                            }
                        }
                        return newStr.replace(/XOPENBRACKETX/g, '[');
                    }
                }
            }
            return str;
        }       

        frontEnd.addStyleString = addStyleString;
        function addStyleString(str, id) {
            if (typeof (id) != "undefined") {
                $("style#" + id).remove();
            }
            var styleNode = $("<style>" + str + "</style>").appendTo("body");
            if (typeof (id) != "undefined") {
                styleNode.attr("id", id);
            }
        }

        insideFrontInterface.closePopups = closePopups;
        function closePopups() {
            $(".inside_windowBlack").remove();
            $(".inside_visitorNotify").remove();
        }


        $.inside.front = frontEnd;
        if (_insideGraph.connectImmediately) {
            setTimeout(init, 0);
        } else {
            $(document).ready(init);
        }

        function getQueryStringParameterByName(name, url) {
            if (!url) {
                url = window.location.href;
            }
            name = name.replace(/[\[\]]/g, '\\$&');
            var regex = new RegExp(`[?&]${name}(=([^&#]*)|&|#|$)`, 'i'),
                results = regex.exec(url);
            if (!results) {
                return null;
            }
            if (!results[2]) {
                return '';
            }
            return decodeURIComponent(results[2].replace(/\+/g, ' '));
        }

        let positionOverrideInit = false;
        function initPositionOverrides() {
            if (!_insideGraph.jQuery.inside.front.settings.positionOverrides || positionOverrideInit) {
                return;
            }

            positionOverrideInit = true;

            const overrides = _insideGraph.jQuery.inside.front.settings.positionOverrides;
            const filterOverrides = (o, applicableFor) => {
                const filter1 = o.subsites.length === 0 || _insideGraph.current.subsiteId.length === 0 || o.subsites.filter(s => s === _insideGraph.current.subsiteId).length > 0;
                const filter2 = o.devices.length === 0 || o.devices.filter(d => parseInt(d) === device).length > 0;
                const filter3 = o.applicableFor.length === 0 || o.applicableFor.filter(a => a === applicableFor).length > 0;
                return filter1 && filter2 && filter3;
            }

            const initOverrides = (applicableFor, prefix) => {
                const sideOverrides = {
                    right: overrides.filter(o => o.change === 'Side' && o.sidePosition === 'Left' && filterOverrides(o, applicableFor)),
                    left: overrides.filter(o => o.change === 'Side' && o.sidePosition === 'Right' && filterOverrides(o, applicableFor)),
                    top: overrides.filter(o => o.change === 'Side' && o.sidePosition === 'Bottom' && filterOverrides(o, applicableFor)),
                    bottom: overrides.filter(o => o.change === 'Side' && o.sidePosition === 'Top' && filterOverrides(o, applicableFor))
                }
                const frontOverrides = overrides.filter(o => o.change === 'Front' && filterOverrides(o, applicableFor));
                const backOverrides = overrides.filter(o => o.change === 'Back' && filterOverrides(o, applicableFor));

                const insideHolder = document.getElementById('inside_holder');
                let overrideTimeout = 0;
                const checkOverrides = (target) => {
                    const pos = target.getAttribute('inside-position-overrides');
                    let offset = 0;
                    if(target && target.matches(target.getAttribute('inside-position-overrides-open-selector'))) {
                        const prop = pos === 'left' || pos === 'right' ? 'width' : 'height';
                        offset = target.getBoundingClientRect()[prop];
                    }

                    insideHolder.style.setProperty(`--inside-${prefix}-offset-${pos}`, offset + 'px');
                    insideHolder.classList.add('positioOverrides');
                    clearTimeout(overrideTimeout);
                    overrideTimeout = setTimeout(() => {
                        insideHolder.classList.remove('positioOverrides');
                    }, 1000);
                }
                const observer = new MutationObserver(function(mutations) {
                    checkOverrides(mutations[0].target);
                });
                const config = { attributes: true };
                for (const pos in { top: 0, right: 0, bottom: 0, left: 0, }) {
                    sideOverrides[pos]?.forEach((o) => {
                        const elements = document.querySelectorAll(o.selector);
                        elements?.forEach((el) => {
                            el.setAttribute('inside-position-overrides', pos);
                            el.setAttribute('inside-position-overrides-open-selector', o.openSelector);
                            observer.observe(el, config);
                            checkOverrides(el);
                        });
                    });
                }

                const getZIndexArray = (selector) => {
                    if (!selector) {
                        return [];
                    }
                    let arr = [];
                    document.querySelectorAll(selector).forEach((el) => {
                        arr.push(parseInt($(el).css('z-index')));
                    })
                    return arr;
                }

                let insideZIndex = 200000;
                let frontZIndex = getZIndexArray(frontOverrides?.map(o => o.selector).join());
                if (frontZIndex.length) {
                    insideZIndex = Math.max(...frontZIndex) + 1;
                }

                let backZIndex = getZIndexArray(backOverrides?.map(o => o.selector).join());
                if (backZIndex.length) {
                    insideZIndex = Math.min(...backZIndex) - 1;
                }
    
                document.getElementById('inside_holder').style.setProperty(`--inside-${prefix}-z-index`, insideZIndex);
            }

            initOverrides('Chat Tab', 'tab');
            initOverrides('Notification', 'notif');
            initOverrides('Chat Pane', 'pane');
            initOverrides('Popup', 'popup');
        }

    })(window, _insideGraph.jQuery);


    function initTabVisible() {
        _insideGraph.tabVisible = true;
        // Set the name of the hidden property and the change event for visibility
        var hidden, visibilityChange; 
        if (typeof document.hidden !== "undefined") { // Opera 12.10 and Firefox 18 and later support 
            hidden = "hidden";
            visibilityChange = "visibilitychange";
        } else if (typeof document.msHidden !== "undefined") {
            hidden = "msHidden";
            visibilityChange = "msvisibilitychange";
        } else if (typeof document.webkitHidden !== "undefined") {
            hidden = "webkitHidden";
            visibilityChange = "webkitvisibilitychange";
        }

        function handleVisibilityChange() {
            if (document[hidden]) {
                _insideGraph.tabVisible = false;
            } else {
                _insideGraph.tabVisible = true;
            }
        }

        if (typeof document.addEventListener === "undefined" || hidden === undefined) {
            //no support for page visibility
        } else {
            // Handle page visibility change   
            document.addEventListener(visibilityChange, handleVisibilityChange, false);         

        }
    }

    this.destroy = destroy;
    function destroy() {
        delete window.insideFrontInterface;
        _insideGraph.jQuery.inside.unbindAll();
    }
});
;
_insideGraph.registerModule("tabs", function () {
    
    var $ = _insideGraph.jQuery;
    var settings = $.inside.front.settings;
    var chatSettings = $.inside.front.settings.chatSettings;

    var device = $.inside.front.device;

    var hasSessionStorage = false;
    try {
        hasSessionStorage = typeof (sessionStorage) != 'undefined';
    } catch (e) { }

    var checkMessageReceived = true;

    var useMinimiseButton = false;
    insideFrontInterface.getUseMinimiseButton = function() { return useMinimiseButton; }
    var getAriaButtonAttribute = insideFrontInterface.getAriaButtonAttribute;
    var translate = insideFrontInterface.chat.translate;

    var usingChatPanev2 = false;

    var chatTabMode = "offline";
    var tabPosition = "right";
    var customimageurl = _insideCDN + "/custom/";
    insideFrontInterface.chatTabMode = chatTabMode;

    insideFrontInterface.chat.startOffline = true;

    var messageReceived = false;

    var defaultOnlineSVGs = {
        "default1": '<svg xmlns="http://www.w3.org/2000/svg" width="60" height="60" viewBox="0 0 60 60"><g fill="none" fill-rule="evenodd"><circle cx="30" cy="30" r="30" fill="#1BB9DA"/><path fill="#FFF" d="M32.644 42.097l-.04 5.167-6.552-5.167h-9.3a5.64 5.64 0 0 1-5.64-5.64V21.543a5.64 5.64 0 0 1 5.64-5.64h25.495a5.64 5.64 0 0 1 5.64 5.64v14.914a5.64 5.64 0 0 1-5.64 5.64h-9.603z"/><path fill="#1BB9DA" d="M22.62 32c-1.085 0-1.965-.895-1.965-2s.88-2 1.966-2c1.085 0 1.965.895 1.965 2s-.88 2-1.965 2zm6.88 0c-1.086 0-1.966-.895-1.966-2s.88-2 1.966-2c1.086 0 1.966.895 1.966 2s-.88 2-1.966 2zm6.88 0c-1.086 0-1.966-.895-1.966-2s.88-2 1.965-2c1.086 0 1.966.895 1.966 2s-.88 2-1.966 2z"/></g></svg>',
        "default2": '<svg xmlns="http://www.w3.org/2000/svg" width="60" height="60" viewBox="0 0 60 60"><g fill="none" fill-rule="evenodd"><circle cx="30" cy="30" r="30" fill="#1BB9DA"/><path stroke="#F9F9F9" stroke-width="2" d="M32.644 42.097l-.04 5.167-6.552-5.167h-9.3a5.64 5.64 0 0 1-5.64-5.64V21.543a5.64 5.64 0 0 1 5.64-5.64h25.495a5.64 5.64 0 0 1 5.64 5.64v14.914a5.64 5.64 0 0 1-5.64 5.64h-9.603z"/></g></svg>',
        "default3": '<svg xmlns="http://www.w3.org/2000/svg" width="60" height="60" viewBox="0 0 61 70" class="svgreplace replaced-svg"><g fill="none" fill-rule="evenodd"><path fill="#1BB9DA" d="M30.278 61.583a30.1 30.1 0 0 0 3.454-.198l10.339 8.398a1 1 0 0 0 1.63-.777V58.15c9.724-5.124 14.855-15.452 14.855-27.358C60.556 13.786 47 0 30.278 0S0 13.786 0 30.791c0 17.006 13.556 30.792 30.278 30.792z"></path><path fill="#FFF" d="M19.683 34c-1.629 0-2.95-1.343-2.95-3s1.321-3 2.95-3c1.63 0 2.95 1.343 2.95 3s-1.32 3-2.95 3zM30.5 34c-1.63 0-2.95-1.343-2.95-3s1.32-3 2.95-3c1.63 0 2.95 1.343 2.95 3s-1.32 3-2.95 3zm10.817 0c-1.63 0-2.95-1.343-2.95-3s1.32-3 2.95-3c1.629 0 2.95 1.343 2.95 3s-1.321 3-2.95 3z"></path></g></svg>',
        "default4": '<svg xmlns="http://www.w3.org/2000/svg" width="60" height="60" viewBox="0 0 60 60" class="svgreplace replaced-svg"><g fill="none" fill-rule="evenodd"><circle cx="30" cy="30" r="30" fill="#1BB9DA" fill-rule="nonzero"></circle><path stroke="#FFF" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M38.28 39.548v6.52l-7.693-6.52H17.7a1.488 1.488 0 0 1-1.475-1.5V21c0-.828.66-1.5 1.475-1.5h23.787c.814 0 1.475.672 1.475 1.5v17.048c0 .828-.66 1.5-1.475 1.5H38.28z"></path></g></svg>',
        "default5": '<svg xmlns="http://www.w3.org/2000/svg" width="60" height="60" viewBox="0 0 60 60" class="svgreplace replaced-svg"><g fill="none" fill-rule="nonzero"><circle cx="30" cy="30" r="30" fill="#1BB9DA"></circle><path fill="#FFF" d="M29.594 46c4.019 0 7.753-1.012 10.847-2.744l9.735 1.654-3.774-6.958C48.03 35.61 48.96 32.895 48.96 30c0-8.837-8.67-16-19.365-16C18.9 14 10.23 21.163 10.23 30s8.67 16 19.365 16z"></path></g></svg>',
        "default6": '<svg xmlns="http://www.w3.org/2000/svg" width="60" height="60" viewBox="0 0 60 60"><g fill="none" fill-rule="nonzero">  <circle cx="30" cy="30" r="30" fill="#1BB9DA"/><path fill="#FFF" d="M17.983 20H41.77c.543 0 .983.448.983 1v17.048c0 .552-.44 1-.983 1h-3.697V45l-7.024-5.952H17.983a.992.992 0 0 1-.983-1V21c0-.552.44-1 .983-1z"/></g></svg>',
        "default7": '<?xml version="1.0" encoding="UTF-8"?><svg width="119px" height="33px" viewBox="0 0 119 33" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><title>1B6F7EA9-2573-4783-86AD-15DD810AAACE</title><desc>Created with sketchtool.</desc><g id="Page-1" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">  <g id="Chat-Tab/Styling" transform="translate(-338.000000, -1202.000000)"><g id="chat-tab-2" transform="translate(338.000000, 1202.000000)"><rect id="Rectangle-2-Copy" fill="#1BB9DA" x="0" y="0" width="119" height="32.8999999" rx="4.69999999"></rect><path d="M25.9522868,22.2949544 L25.9224674,26.0257792 L21.3732377,22.4999999 L15.98,22.4999999 C12.865114,22.4999999 10.34,19.9748859 10.34,16.86 L10.34,14.04 C10.34,10.925114 12.865114,8.39999998 15.98,8.39999998 L24.4399999,8.39999998 C27.5548859,8.39999998 30.0799999,10.925114 30.0799999,14.04 L30.0799999,16.86 C30.0799999,19.4510416 28.3327885,21.6340001 25.9522868,22.2949544 Z" id="Combined-Shape-Copy-2" fill="#FFFFFF"></path><text id="LIVE-CHAT" font-family="Nunito-ExtraBold, Nunito" font-size="13.16" font-weight="600" fill="#FFFFFF"><tspan x="38.7199999" y="20.58">LIVE CHAT</tspan></text></g>  </g></g></svg>'
    }

    var defaultOfflineSVGs = {
        "default1": '<svg xmlns="http://www.w3.org/2000/svg" width="60" height="60" viewBox="0 0 60 60"><g fill="none" fill-rule="evenodd"><circle cx="30" cy="30" r="30" fill="#1BB9DA"/><path fill="#FFF" d="M32.644 42.097l-.04 5.167-6.552-5.167h-9.3a5.64 5.64 0 0 1-5.64-5.64V21.543a5.64 5.64 0 0 1 5.64-5.64h25.495a5.64 5.64 0 0 1 5.64 5.64v14.914a5.64 5.64 0 0 1-5.64 5.64h-9.603z"/><path fill="#1BB9DA" d="M22.62 32c-1.085 0-1.965-.895-1.965-2s.88-2 1.966-2c1.085 0 1.965.895 1.965 2s-.88 2-1.965 2zm6.88 0c-1.086 0-1.966-.895-1.966-2s.88-2 1.966-2c1.086 0 1.966.895 1.966 2s-.88 2-1.966 2zm6.88 0c-1.086 0-1.966-.895-1.966-2s.88-2 1.965-2c1.086 0 1.966.895 1.966 2s-.88 2-1.966 2z"/></g></svg>',
        "default2": '<svg xmlns="http://www.w3.org/2000/svg" width="60" height="60" viewBox="0 0 60 60"><g fill="none" fill-rule="evenodd"><circle cx="30" cy="30" r="30" fill="#1BB9DA"/><path stroke="#F9F9F9" stroke-width="2" d="M32.644 42.097l-.04 5.167-6.552-5.167h-9.3a5.64 5.64 0 0 1-5.64-5.64V21.543a5.64 5.64 0 0 1 5.64-5.64h25.495a5.64 5.64 0 0 1 5.64 5.64v14.914a5.64 5.64 0 0 1-5.64 5.64h-9.603z"/></g></svg>',
        "default3": '<svg xmlns="http://www.w3.org/2000/svg" width="60" height="60" viewBox="0 0 61 70" class="svgreplace replaced-svg"><g fill="none" fill-rule="evenodd"><path fill="#1BB9DA" d="M30.278 61.583a30.1 30.1 0 0 0 3.454-.198l10.339 8.398a1 1 0 0 0 1.63-.777V58.15c9.724-5.124 14.855-15.452 14.855-27.358C60.556 13.786 47 0 30.278 0S0 13.786 0 30.791c0 17.006 13.556 30.792 30.278 30.792z"></path><path fill="#FFF" d="M19.683 34c-1.629 0-2.95-1.343-2.95-3s1.321-3 2.95-3c1.63 0 2.95 1.343 2.95 3s-1.32 3-2.95 3zM30.5 34c-1.63 0-2.95-1.343-2.95-3s1.32-3 2.95-3c1.63 0 2.95 1.343 2.95 3s-1.32 3-2.95 3zm10.817 0c-1.63 0-2.95-1.343-2.95-3s1.32-3 2.95-3c1.629 0 2.95 1.343 2.95 3s-1.321 3-2.95 3z"></path></g></svg>',
        "default4": '<svg xmlns="http://www.w3.org/2000/svg" width="60" height="60" viewBox="0 0 60 60" class="svgreplace replaced-svg"><g fill="none" fill-rule="evenodd"><circle cx="30" cy="30" r="30" fill="#1BB9DA" fill-rule="nonzero"></circle><path stroke="#FFF" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M39.03 40.298v7.389l-8.718-7.389H17.7c-1.232 0-2.225-1.01-2.225-2.25V21c0-1.24.993-2.25 2.225-2.25h23.787c1.232 0 2.225 1.01 2.225 2.25v17.048c0 1.24-.993 2.25-2.225 2.25H39.03z"></path><path fill="#FFF" fill-rule="nonzero" d="M26.566 34h-6.028v-.973l4.248-6.392h-4.132v-1.201h5.796v.984l-4.263 6.38h4.379V34zm6.096 0H27.83v-.85l3.22-4.576h-3.024V27.52h4.546v.96l-3.152 4.465h3.244V34zm6.133 0h-4.834v-.85l3.222-4.576h-3.026V27.52h4.546v.96l-3.152 4.465h3.245V34z"></path></g></svg>',
        "default5": '<svg xmlns="http://www.w3.org/2000/svg" width="60" height="60" viewBox="0 0 60 60" class="svgreplace replaced-svg"><g fill="none" fill-rule="nonzero"><circle cx="30" cy="30" r="30" fill="#1BB9DA"></circle><path fill="#FFF" d="M29.594 46c4.019 0 7.753-1.012 10.847-2.744l9.735 1.654-3.774-6.958C48.03 35.61 48.96 32.895 48.96 30c0-8.837-8.67-16-19.365-16C18.9 14 10.23 21.163 10.23 30s8.67 16 19.365 16z"></path><path fill="#1BB9DA" d="M26.346 36H18.8v-1.374l4.86-6.87h-4.728v-1.75h7.28v1.367L21.36 34.25h4.986V36zm7.35 0h-6.123v-1.23l3.59-4.82h-3.375v-1.593h5.781v1.354l-3.494 4.696h3.62V36h.001zm7.434 0h-6.122v-1.23l3.59-4.82h-3.375v-1.593h5.781v1.354l-3.494 4.696h3.62V36z"></path></g></svg>',
        "default6": '<svg xmlns="http://www.w3.org/2000/svg" width="60" height="60" viewBox="0 0 60 60"><g fill="none" fill-rule="nonzero"><circle cx="30" cy="30" r="30" fill="#1BB9DA"/><path fill="#FFF" d="M17.983 20H41.77c.543 0 .983.448.983 1v17.048c0 .552-.44 1-.983 1h-3.697V45l-7.024-5.952H17.983a.992.992 0 0 1-.983-1V21c0-.552.44-1 .983-1z"/></g></svg>'
    }

    function init() {
        $("#inside_holder").show();
        setSVGIconColors();
        setTimeout(setChatTab, 1000);
        window.addEventListener("resize", windowScale);
        
        if (settings && settings.chatSettings && settings.chatSettings.videoFeed && settings.chatSettings.videoFeed.enabled) {
            //theme videos tab is triggered by an event
            //setTimeout(showThemeVideosTab, 2001);
        }

        fixChatTabImageInSafari();
    }
    init();

    function showThemeVideosTab() {
        insideAPI.post("api/operator/getthemevideofeed", { lastFileLibraryId: 0, lastFeaturedFileLibraryId: 0, pageSize:10}, function(response){
            if (response.videos.length > 0) {
                //show the theme videos tab
                $("#inside_tabs").prepend("<div class='tab' id='themeVideosTab'></div>");
            }
            insideChatPane.insideVideos.lastFileLibraryId = response.lastFileLibraryId;
            insideChatPane.insideVideos.lastFeaturedFileLibraryId = response.lastFeaturedFileLibraryId;
            var tabImage = document.createElement("img");
            tabImage.setAttribute("src", response.videos[0].thumbpath);
            $("#themeVideosTab")[0].style.opacity = 0;
            $("#themeVideosTab").html("").append(tabImage);
            tabImage.addEventListener("load", function() {
                windowScale();
                $("#themeVideosTab")[0].style.opacity = 1;
            });
            addCloseToChatTab($("#themeVideosTab"));
            $("#themeVideosTab").click(function() {
                insideFrontInterface.openChatPane(true, function() {
                    insideChatPane.insideVideos.showChatPaneThemeVideos();
                });
            });
        });
    }

    function windowScale() {
        scaleChatTab();
    }

    var svgIconColourSet = false;
    function cloneSvgs(svgs, _colour, svgCategory) {
        var colour = settings.chatSettings.generalStyles.brandColor;
        if (typeof _colour != "undefined") {
            colour = _colour;
        }
        var newSVGs = {};
        for (var i in svgs) {
            newSVGs[i] = updateSvgColors(svgs[i], colour || "#1BB9DA", i, svgCategory);
        }
        return newSVGs;
    }

    function updateSvgColors(svgString, brandColor, svgId, svgCategory) {
        // Create a DOM parser to convert the string into actual DOM nodes
        const parser = new DOMParser();
        const doc = parser.parseFromString(svgString, 'image/svg+xml');
        const circle = doc.querySelector('circle');
        const paths = doc.querySelectorAll('path');

        if (circle) {
            circle.setAttribute('fill', brandColor);
        }

        if (svgCategory === "online") {
            if (svgId === "default3") {
                if (paths.length > 0) {
                    paths[0].setAttribute('fill', brandColor);
                }
            } else {
                if (paths.length > 1) {
                    paths[1].setAttribute('fill', brandColor);
                }
            }
        } else if (svgCategory === "offline") {
            if (svgId !== "default4") {
                if (svgId === "default3") {
                    if (paths.length > 0) {
                        paths[0].setAttribute('fill', brandColor);
                    }
                } else {
                    if (paths.length > 1) {
                        paths[1].setAttribute('fill', brandColor);
                    }
                }
            }
        }
      
        // Serialize the updated SVG DOM back to a string
        const serializer = new XMLSerializer();
        return serializer.serializeToString(doc.documentElement);
      }

    function setSVGIconColors(forceUpdate) {
        if (chatSettings && chatSettings.version == "2" && (!svgIconColourSet || forceUpdate)) {
            chatSettings = _insideGraph.jQuery.inside.front.settings.chatSettings || _insideGraph.jQuery.inside.front.settings;
            defaultOnlineSVGs = cloneSvgs(defaultOnlineSVGs, undefined, "online");
            defaultOfflineSVGs = cloneSvgs(defaultOfflineSVGs, settings.chatSettings.chatTab.offlineColor || "#cccccc", "offline");
            svgIconColourSet = true;
        }
    }

    //for chat tab hiding
    insideFrontInterface.chat.setChatTab = setChatTab;
    function setChatTab(t, chatSettingsUpdated) {

        if (chatSettings && chatSettings.version == "2") {
            usingChatPanev2 = true;
        }
        
        setSVGIconColors(chatSettingsUpdated);

        try {
            const notificationIsVisible = $('.inside-notification, #insideChatFrame.notificationMode').is(':visible');
            const showChatTabAndNotification = notificationIsVisible && chatSettings.chatPane.notifications.showChatTab;
            if (!showChatTabAndNotification && (insideFrontInterface.isBlocked || notificationIsVisible || (insideFrontInterface.chat.data && insideFrontInterface.chat.data.flags.indexOf("dnd") !== -1))) {
                $("#inside_liveChatTab").hide();
                return;
            }
        } catch (e) { }

        if (insideFrontInterface.getAvailableAssistants().length > 0) {
            if ((typeof (t) != "undefined" && !t) || !insideFrontInterface.chat.startOffline) {
                checkMessageReceived = false;
                insideFrontInterface.chat.startOffline = false;
            }
            else {
                checkMessageReceived = true;
            }
            setOnlineChatTab();
            try {
                setJoinTheCallTag(false);
            } catch(e){}
            $("#inside_clickToCallChatTab").show();
        } else {
            setOfflineChatTab();
            if ($("#inside_joinTheCallChatTab").length !== 0) {
                setJoinTheCallTag(true);
            }
            $("#inside_clickToCallChatTab").show();

        }

        if(typeof chatSettings != "undefined" && chatSettings && chatSettings.chatTab && chatSettings.chatTab.draggable === false) {
            $(document.querySelector("#inside_tabs")).unbind("mousedown touchstart");
        } else {
            $(document.querySelector("#inside_tabs img")).css('pointer-events', 'none');
        }

        setTimeout($.inside.front.windowScale, 1000);
    }

    function positionJoinTheCallTag() {
        if ($("#inside_joinTheCallChatTab").length === 0) { return; }
    }

    insideFrontInterface.setJoinTheCallTag = setJoinTheCallTag;
    function setJoinTheCallTag(show) {
        if ($("#inside_joinTheCallChatTab").length === 0) { return; }

        positionJoinTheCallTag();

        if (show && !insideFrontInterface.chat.chatPaneOpen) {
            $("#inside_joinTheCallChatTab").show();
        } else {
            $("#inside_joinTheCallChatTab").hide();
        }
    }

    insideFrontInterface.chat.setupJoinTheCallTag = setupJoinTheCallTag;
    function setupJoinTheCallTag(jtcsettings) {

        if ($("#inside_joinTheCallChatTab").length) { return; }

        var tabImg = imageurl + "assistance-tab.png";
        if (jtcsettings.tabImage) {
            tabImg = customimageurl + jtcsettings.tabImage;
        }
        var html = "<div id='inside_joinTheCallChatTab' " + getAriaButtonAttribute(translate('Join the Call')) + " class='noselect' ondragstart='return false;' ondrop='return false;'>" +
            "<img id='inside_joinTheCallImage' src='" + tabImg + "' alt='" + translate('Join the Call') + "' />" + //width='181' height='115'
            "<div id='inside_joinTheCallPasscode'></div>" +
            "</div>";

        var $html = $(html);
        $(html).find("#inside_joinTheCallChatTab").hide();
        $html.appendTo("#inside_tabs");
        $html.find("img").on("load", insideFrontInterface.chat.onJoinTheCallChatTabImageLoad);

        if (tabPosition.indexOf("bottom") != -1 || $("#inside_liveChatTab.usingChatHeader").length != 0) {
            $("#inside_liveChatTab").appendTo("#inside_tabs");
        }

        var j2cImageIcon = '<svg xmlns="http://www.w3.org/2000/svg" width="15" height="15" viewBox="0 0 15 15"><path fill="currentColor" fill-rule="nonzero" d="M11.198 4.5H2.007v3H0v-5h11.124l-1.092-1.092 1.415-1.414 3.547 3.547-1.414 1.415-2.121 2.121-1.42-1.419L11.199 4.5zm-7.396 5.991h9.191v-3H15v5H3.876l1.092 1.092-1.415 1.414L.006 11.45l1.414-1.415 2.121-2.12 1.42 1.418-1.159 1.158z"/></svg>';
        settings.showJoinTheCallIcon = jtcsettings.showJoinTheCallIcon;
        if (jtcsettings.showJoinTheCallIcon == true && $("#inside_joinTheCallIcon").length == 0) {
            var jtcTooltip = "Session Code: ";
            var jtcIcon = "";
            try {
                jtcTooltip = insideFrontInterface.chat.settings.joinTheCallText || "Session Code: ";
                jtcIcon = insideFrontInterface.chat.settings.joinTheCallIcon || "";
            } catch (e) {
                jtcTooltip = "Session Code: ";
            }

            if (jtcIcon) {
                j2cImageIcon = "<img src='" + (customimageurl + jtcIcon) + "' />";
            }
            $("<div " + getAriaButtonAttribute(jtcTooltip) + " class='inside_icon_image_holder' id='inside_joinTheCallIcon' title-data='" + jtcTooltip + "'>" + j2cImageIcon + "</div>").prependTo("#chatHeaderIcons, #inside_chatPane_custom_chatHeader");
        } else {
            $("#inside_joinTheCallIcon").remove();
        }

        if (jtcsettings.colour) {
            $("#inside_joinTheCallPasscode").css("color", jtcsettings.colour);
        }
        if (jtcsettings.textSize) {
            $("#inside_joinTheCallPasscode").css("font-size", jtcsettings.textSize + "px");
        }

        $("#inside_joinTheCallChatTab").hover(function () {
            if (this.codeLoaded != true) {
                this.codeLoaded = true;
                $.inside.front.loadInsideChat(function () {
                $.when(insideFrontInterface.chat.getVisitorCobrowsePasscode())
                    .done(function (response) {
                        $("#inside_joinTheCallPasscode").text(response.data);
                    })
                    .fail(function (response) {
                        $("#inside_joinTheCallPasscode").text("????");
                    });
                });
            }
        });

        $("#inside_joinTheCallChatTab").click(j2cTabClick);

        $('body').on('click', '#inside_joinTheCallIcon', function () {
            $.inside.front.loadInsideChat(function () {
                $.when(insideFrontInterface.chat.getVisitorCobrowsePasscode())
                    .done(function (response) {
                        var joinTheCallText = "Session Code: ";
                        var joinTheCallIcon = _insideCDN + "/images/icon-join-call-greeen.png";
                        if (insideFrontInterface.chat && insideFrontInterface.chat.settings && insideFrontInterface.chat.settings.joinTheCallText && typeof (insideFrontInterface.chat.settings.joinTheCallText) == "string")
                            joinTheCallText = insideFrontInterface.chat.settings.joinTheCallText;
                        if (insideFrontInterface.chat.clickToCallSettings && insideFrontInterface.chat.clickToCallSettings.joinTheCallMsg) {
                            joinTheCallText = insideFrontInterface.chat.clickToCallSettings.joinTheCallMsg;
                        }

                        var msg =
                            '<div class="insideJoinTheCallSessionCodeHolder" style="max-width:150px;display:inline;">' +
                            '   <svg  class="icon-join-call" style="color:#39e039;vertical-align: middle;margin-left: 20px;" xmlns="http://www.w3.org/2000/svg" width="15" height="15" viewBox="0 0 15 15"><path fill="currentColor" fill-rule="nonzero" d="M11.198 4.5H2.007v3H0v-5h11.124l-1.092-1.092 1.415-1.414 3.547 3.547-1.414 1.415-2.121 2.121-1.42-1.419L11.199 4.5zm-7.396 5.991h9.191v-3H15v5H3.876l1.092 1.092-1.415 1.414L.006 11.45l1.414-1.415 2.121-2.12 1.42 1.418-1.159 1.158z"/></svg>' +
                            '   <span style="padding-left: 12px;vertical-align: middle;">' + joinTheCallText + '<b> ' + response.data + '</b></span>' +
                            '</div>';

                        if ($(".inside_chatPane, #inside_chatPane_custom").hasClass("offline")) {
                            $("#inside_leaveMessageForm .insideJoinTheCallSessionCodeHolder").remove();
                            $(msg).insertAfter("#inside_prechatForm .inside_sendButton, #inside_leaveMessageForm .inside_sendButton");
                        } else if ($(".inside_chatPane, #inside_chatPane_custom").hasClass("prechat")) {
                            $("#inside_prechatForm_form .insideJoinTheCallSessionCodeHolder").remove();
                            $("#inside_prechatForm_form").append('<center style="margin: 20px 0 0 -20px;">' + msg + '</center>');
                        } else {
                            insideFrontInterface.chat.showSystemMessage(msg, false);
                        }
                    })
                    .fail(function (response) {
                        var msg = settings.joinTheCallFailMsg || "Could not get Join the Call code!";
                        insideFrontInterface.chat.showSystemMessage(msg, false);
                    });
            });
        });

        setJoinTheCallTag(insideFrontInterface.getAvailableAssistants().length === 0);
    }

    insideFrontInterface.showChatPaneHeaderForDevice = showChatPaneHeaderForDevice;
    function showChatPaneHeaderForDevice(offline) {
        if (typeof insideChatPane != "undefined") {
            activeChat = insideChatPane.activeChat;
        }

        if (usingChatPanev2 && typeof insideChatPane != "undefined" && insideChatPane.showHeaderForTab) {
            return true;
        }

        if (typeof (settings.showChatPaneHeaderAsChatTab) != "undefined" && settings.showChatPaneHeaderAsChatTab) {
            if (device === 2) {
                if (offline === true && settings.showChatPaneHeaderAsChatTab.indexOf("mobile_offline") !== -1) {
                    return true;
                }
                if (!offline && !activeChat && settings.showChatPaneHeaderAsChatTab.indexOf("mobile") !== -1) {
                    return true;
                }
                if (!offline && activeChat && settings.showChatPaneHeaderAsChatTab.indexOf("mobile_active") !== -1) {
                    return true;
                }
            } else {
                if (offline === true && settings.showChatPaneHeaderAsChatTab.indexOf("desktop_offline") !== -1) {
                    return true;
                }
                if (!offline && !activeChat && settings.showChatPaneHeaderAsChatTab.indexOf("desktop") !== -1) {
                    return true;
                }
                if (!offline && activeChat && settings.showChatPaneHeaderAsChatTab.indexOf("desktop_active") !== -1) {
                    return true;
                }
            }
        }
        return false;
    }

    function removeHeaderFromTab() {
        $("#inside_liveChatTab").removeClass("usingChatHeader").removeClass("noAutoHide");
        insideFrontInterface.setTabPosition();
        $("#inside_liveChatTab").css("background", "");
        addTabContents();
    }

    var hideChatTab = false;
    var showTabForActive = false;
    var showPaneForActive = false;
    var activeChat = false;

    insideFrontInterface.chat.getHideChatTab = function() { return hideChatTab; }

   /* return the url for the custom image, appending the imageCacheVersion if available */
    function customImage(_url) {
        customImageUrl = _insideCDN + "custom/";
        return customImageUrl + _url + "?" + ($.inside.front.settings.imageCacheVersion || "");
    }

    /* returns false if noCookies and no opt in settings configured for the visitor.*/
    function checkPrivacyOptIn() {
        if(_insideGraph.current.noCookie === true && chatSettings && chatSettings.version == "2") {
            if(typeof chatSettings.privacy == "undefined" || !chatSettings.privacy || chatSettings.privacy.enabled === false) {
                //noCookies mode and no opt in defined
                return false;
            }
            /*
            if(chatSettings.privacy.requriesConsentFrom === "") {
                //noCookies mode and no opt in allowed
                return false;
            }
            */

            /*
            if(chatSettings.privacy.requriesConsentFrom === "eu" && $.inside.front.settingsData.subjectToEuPrivacyRules !== true) {
                // opt in configured for EU only.
                return false;
            }
            */
        }
        return true;
    }

    insideFrontInterface.chat.setOnlineChatTab = setOnlineChatTab;
    function setOnlineChatTab(t) {
        chatSettings = _insideGraph.jQuery.inside.front.settings.chatSettings || _insideGraph.jQuery.inside.front.settings;
        settings = $.inside.front.settings;

        if (settings.enable3dAvatars != false && insideFrontInterface.showAvatarsAlways && (typeof insideChatPane == "undefined" || !insideChatPane?.avatarsDisabled)) {
            //return;
        }

        $("#inside_holder").removeClass("offline");
        device = $.inside.front.device;
        

        if (chatSettings && chatSettings.version == "2") {
            usingChatPanev2 = true;
            if (typeof insideChatPane != "undefined" && typeof insideChatPane.activeChat != "undefined") {
                activeChat = insideChatPane.activeChat;
            }
        } else { 
            activeChat = insideFrontInterface.chat.activeChat;
        }
        
        if(!checkPrivacyOptIn()) {
            $("#inside_liveChatTab").hide();
            return;
        }

        try {
            if (hasSessionStorage && sessionStorage.getItem("insideChatClosed") === "True") {
                return;
            }
        } catch (e) { }

        //for chat tab hiding
        if ($("#inside_liveChatTab").length == 0) {
            addChatTab();
            $("#inside_liveChatTab").hide();
        }
        if ($(".inside_chatPane, #inside_chatPane_custom").is(":visible")) {
            // If avatars are enabled and pane is minimised, keep showing the chat tab
            var avatarMinimised = false;
            try {
                avatarMinimised = chatSettings && chatSettings.chatPane && chatSettings.chatPane.showChatTabWithAvatars === true &&
                    ((typeof insideChatPane != "undefined" && insideChatPane.frame && insideChatPane.frame.classList && insideChatPane.frame.classList.contains("minimised")) ||
                     ($("#insideChatPane").length && $("#insideChatPane").hasClass("minimised")));
            } catch(e) { avatarMinimised = false; }

            if (!avatarMinimised) {
                $("#inside_liveChatTab").hide();
            }
        }
        $("#inside_liveChatTab").removeClass("inside_chat_offline").addClass("inside_chat_online");

        chatTabMode = "online";
        insideFrontInterface.chatTabMode = chatTabMode;

        if (activeChat) {
            $("#inside_liveChatTab, #inside_tabs").addClass("inside_active_chat");
        } else {
            $("#inside_liveChatTab, #inside_tabs").removeClass("inside_active_chat");
        }

        $("#inside_liveChatTab .chatHeaderIcons").remove();

        if (usingChatPanev2 && showChatPaneHeaderForDevice()) return;

        if (typeof (settings) != "undefined" && settings != null) {
            //set the custom tab images
            if (!usingChatPanev2 && settings.showChatPaneHeaderAsChatTab && showChatPaneHeaderForDevice()) {
                addChatPaneHeaderToTab();
                addCloseToChatTab();
            } else {
                if ($("#inside_liveChatTab").hasClass("usingChatHeader")) {
                    removeHeaderFromTab();
                }
                prevTabImage = $("#inside_liveChatTab .inside_chatTabImage").attr("src");

                if (!usingChatPanev2) {
                    var chatTabImageUrl;

                    if (device === 1) {
                        //desktop
                        if ($("#inside_liveChatTab .inside_chatTabImage").length == 0)
                            addTabContents();

                        if (activeChat && chatSettings && chatSettings.chatTab && typeof (chatSettings.chatTab.activeChatTab) != "undefined" && chatSettings.chatTab.activeChatTab != "") {
                            chatTabImageUrl = customImage(chatSettings.chatTab.activeChatTab);
                        } else if (chatSettings && chatSettings.chatTab && typeof (chatSettings.chatTab.onlineChatTab) != "undefined" && chatSettings.chatTab.onlineChatTab != "") {
                            chatTabImageUrl = customImage(chatSettings.chatTab.onlineChatTab);
                        } else if (activeChat && settings.activeChatTabImage) {
                            chatTabImageUrl = customImage(settings.activeChatTabImage);
                        } else if (typeof (settings.customTabImage) != "undefined" && settings.customTabImage != "") {
                            chatTabImageUrl = customImage(settings.customTabImage);
                        } else {
                            if (!usingChatPanev2) {
                                chatTabImageUrl = $.inside.front.imageurl + "livechaticon.png";
                            }
                        }
                    } else {
                        //set mobile chat tab image
                        if (activeChat && settings.activeChatTabMobileImage) {
                            chatTabImageUrl = customImage(settings.activeChatTabMobileImage);
                        } else if (typeof (settings.customMobileTabImage) != "undefined" && settings.customMobileTabImage != "") {
                            chatTabImageUrl = customImage(settings.customMobileTabImage);
                        } else {
                            if (!usingChatPanev2) {
                                chatTabImageUrl = $.inside.front.imageurl + "livechaticon_mobile.png";
                            }
                        }
                    }

                    updateChatTabImage(chatTabImageUrl);
                }


                if (device == 1) {
                    if ($.inside.front.settings.showCloseOnTab) {
                        if (activeChat && $.inside.front.settings.showCloseOnTab.indexOf("desktop_active") != -1) {
                            addCloseToChatTab();
                        } else if (!activeChat && $.inside.front.settings.showCloseOnTab.indexOf("desktop") != -1) {
                            addCloseToChatTab();
                        }
                    }
                } else {
                    if ($.inside.front.settings.showCloseOnTab) {
                        if (activeChat && $.inside.front.settings.showCloseOnTab.indexOf("mobile_active") != -1) {
                            addCloseToChatTab();
                        } else if (!activeChat && $.inside.front.settings.showCloseOnTab.indexOf("mobile") != -1) {
                            addCloseToChatTab();
                        }
                    }
                }


                if (usingChatPanev2 && chatSettings && chatSettings.chatTab) {
                    var chatTabImageUrl;
                    if ($("#inside_liveChatTab .inside_chatTabImage").length == 0 && $("#inside_liveChatTab svg").length == 0) addTabContents();
                    if (device == 1 && activeChat && chatSettings && chatSettings.chatTab && chatSettings.chatTab.useAvatar && chatSettings.chatTab.useAvatar.indexOf("desktop_active") != -1 && chatSettings.chatTab.avatarChatTab) {
                        chatTabImageUrl = customImage(chatSettings.chatTab.avatarChatTab);
                    } else if (device == 1 && !activeChat && chatSettings && chatSettings.chatTab && chatSettings.chatTab.useAvatar && chatSettings.chatTab.useAvatar.indexOf("desktop") != -1 && chatSettings.chatTab.avatarChatTab) {
                        chatTabImageUrl = customImage(chatSettings.chatTab.avatarChatTab);
                    } else if (device >= 2 && activeChat && chatSettings && chatSettings.chatTab && chatSettings.chatTab.useAvatar && chatSettings.chatTab.useAvatar.indexOf("mobile_active") != -1 && chatSettings.chatTab.avatarChatTab) {
                        chatTabImageUrl = customImage(chatSettings.chatTab.avatarChatTab);
                    } else if (device >=2 && !activeChat && chatSettings && chatSettings.chatTab && chatSettings.chatTab.useAvatar && chatSettings.chatTab.useAvatar.indexOf("mobile") != -1 && chatSettings.chatTab.avatarChatTab) {
                        chatTabImageUrl = customImage(chatSettings.chatTab.avatarChatTab);
                    } else if (device >= 2 && activeChat && chatSettings && chatSettings.chatTab && typeof (chatSettings.chatTab.activeChatTabMobile) != "undefined" && chatSettings.chatTab.activeChatTabMobile != "") {
                        chatTabImageUrl = customImage(chatSettings.chatTab.activeChatTabMobile);
                    } else if (device >= 2 && !activeChat && chatSettings && chatSettings.chatTab && typeof (chatSettings.chatTab.onlineChatTabMobile) != "undefined" && chatSettings.chatTab.onlineChatTabMobile != "") {
                        chatTabImageUrl = customImage(chatSettings.chatTab.onlineChatTabMobile);
                    } else if (device == 1 && typeof insideChatPane != "undefined" && insideChatPane.activeChat && chatSettings && chatSettings.chatTab && typeof (chatSettings.chatTab.activeChatTab) != "undefined" && chatSettings.chatTab.activeChatTab != "") {
                        //use custom
                        chatTabImageUrl = customImage(chatSettings.chatTab.activeChatTab);
                    } else if (device == 1 && chatSettings && chatSettings.chatTab && typeof (chatSettings.chatTab.onlineChatTab) != "undefined" && chatSettings.chatTab.onlineChatTab != "" && typeof chatSettings.chatTab.onlineChatTab != "object") {
                        //use custom
                        chatTabImageUrl = customImage(chatSettings.chatTab.onlineChatTab);
                    } else {
                        var headerIcons = $("#inside_liveChatTab .chatHeaderIcons");
                        var notifIcon = $("#inside_liveChatTab .inside_chatNotification");
                        $("#inside_liveChatTab").html(defaultOnlineSVGs[insideFrontInterface.getLanguageValue(chatSettings.chatTab.onlineChatTabDefault)]);
                        $("#inside_liveChatTab").width($("#inside_liveChatTab svg").width());
                        scaleChatTab();
                        if (headerIcons) {
                            $("#inside_liveChatTab").append(headerIcons);
                        }
                        if (notifIcon) {
                            $("#inside_liveChatTab").append(notifIcon);
                        }
                        insideFrontInterface.positionTabs();
                    }                    

                    updateChatTabImage(chatTabImageUrl);
                }

                if (prevTabImage == $("#inside_liveChatTab .inside_chatTabImage").attr("src")) {
                    //no image change
                    setTabAutohide();
                }
            }
        } else {
            //no settings defined, use default tab image.
            $("#inside_liveChatTab .inside_chatTabImage").attr("src", $.inside.front.imageurl + "livechaticon.png");
        }

        hideChatTab = insideFrontInterface.chat.isTabHiddenOnThisDevice();
        if (typeof (settings) != "undefined" && settings != null && typeof (settings.hideChatTab) != "undefined" && settings.hideChatTab) {            
            if (hideChatTab) {
                $("#inside_liveChatTab").hide();
            } else {
                //make sure opacity is set to 1 (it is set to 0 when chat pane is opened)
                $("#inside_liveChatTab").css("opacity", 1).show();
            }
            //setOfflineChatTab();
        } else {
            if (!hideChatTab && tabPosition != "bottomright" || (tabPosition == "bottomright" && $(".inside-notification:visible").length == 0)) {
                $("#inside_liveChatTab").show().css("opacity", 1);
            }
        }

        if (typeof (settings) != "undefined" && settings != null && typeof settings.hideChatTabOnDevices != "undefined" && settings.hideChatTabOnDevices != null) {
            hideChatTab = false;
            if (settings.hideChatTab == true && settings.hideChatTabOnDevices.indexOf(device.toString()) != -1) {
                hideChatTab = true;
            }
        }

        if (typeof (settings) != "undefined" && settings != null && typeof (settings.showTabForActive) != "undefined" && settings.showTabForActive == true) {
            showTabForActive = true;
            //if true, chat tab should show for active chats, even if hideChatTab
            if (insideFrontInterface.currentChatId > 0) {
                if (usingChatPanev2 && typeof insideChatPane.isOpen != "undefined" && !insideChatPane.isOpen()) {
                    $("#inside_liveChatTab").show();
                    insideFrontInterface.positionTabs();
                } else if (!insideFrontInterface.chat.chatPaneOpen) {
                    if ($(".inside-notification:visible").length == 0) {
                        $("#inside_liveChatTab").show();
                        insideFrontInterface.positionTabs();
                    }
                }
                checkMessageReceived = false;
            }
            if (typeof insideLegacyChat != "undefined" && insideLegacyChat.messageReceived && !checkMessageReceived && $(".inside_chatPane, #inside_chatPane_custom").is(":visible") && typeof (t) != "undefined" && !t) {
                $("#inside_liveChatTab").hide();
                checkMessageReceived = false;
            }
        }
        if (hideChatTab && settings.showPaneForActive == true) {
            showPaneForActive = true;
            showTabForActive = false;
            //if true, chat pane should show for active chats, even if hideChatTab
            // if (insideFrontInterface.currentChatId > 0 && !chatEndedByCustomer && !chatMinimizedByCustomer) {
            //     if (!insideFrontInterface.chat.chatPaneOpen) {
            //         insideFrontInterface.openChatPane();
            //     }
            // }
        }
        if (hideChatTab && insideFrontInterface.currentChatId > 0 && device == 2 && insideFrontInterface.chat.num) {
            if ($("#inside_liveChatTab").length == 0) {
                const isChatV2Open = usingChatPanev2 && typeof insideChatPane != "undefined" && typeof insideChatPane.isOpen != "undefined" && insideChatPane.isOpen();
                if(!isChatV2Open) {
                    insideFrontInterface.openChatPane();
                    insideFrontInterface.chat.num = 0;
                }
            } else {
                $("#inside_liveChatTab").show();
            }
        }

        if ($("#inside_liveChatTab img").length > 0) {
            $("#inside_liveChatTab img").css("width", "auto");
            $("#inside_liveChatTab").css("width", "auto");
        }
        if ($("#inside_liveChatTab").hasClass('usingChatHeader')) {
            $("#inside_liveChatTab").outerWidth(settings.width || '');
        }

        scaleChatTab();
        if (settings.autohideTabs == true) {
            //$.inside.front.autohideTabs(0);
        } else {
            insideFrontInterface.positionTabs();
        }

        if (usingChatPanev2 && typeof insideChatPane != "undefined" && typeof insideChatPane.isOpen != "undefined" && insideChatPane.isOpen()) {
            // If avatars mode is minimised and theme wants chat tab shown, don't hide it
            var avatarMinimisedOpen = false;
            try {
                avatarMinimisedOpen = chatSettings && chatSettings.chatPane && chatSettings.chatPane.showChatTabWithAvatars === true &&
                    ((insideChatPane.frame && insideChatPane.frame.classList && insideChatPane.frame.classList.contains("minimised")) ||
                     ($("#insideChatPane").length && $("#insideChatPane").hasClass("minimised")));
            } catch(e) { avatarMinimisedOpen = false; }

            if (!avatarMinimisedOpen) {
                $("#inside_liveChatTab").hide();
            }
        } else if (insideFrontInterface.chat.chatPaneOpen) {
            $("#inside_liveChatTab").hide();
        }
        if (usingChatPanev2 && chatSettings) {
            if (chatSettings.chatTab.shadowOnTab == true || chatSettings.chatTab.shadowOnTab == "true") {
                $("#inside_liveChatTab").addClass("insideDropShadow");
            } else {
                $("#inside_liveChatTab").removeClass("insideDropShadow");
            }
        }

        $("#inside_tabs").css('display', 'block');

        if (insideFrontInterface.getAvailableAssistants().length == 0 && activeChat !== true) {
            $("#inside_liveChatTab").hide();
            insideFrontInterface.positionTabs();
        }
    }

    function updateChatTabImage(chatTabImageUrl) {
        if(!chatTabImageUrl) {
            return;
        }

        $("#inside_liveChatTab svg").remove();
        if($("#inside_liveChatTab .inside_chatTabImage").length === 0) {
            addTabContents();
        }
        const chatTabElement = $("#inside_liveChatTab .inside_chatTabImage");
        if(chatTabElement.attr("src") !== chatTabImageUrl) {
            chatTabElement.attr("src", chatTabImageUrl);
        }
    }

    insideFrontInterface.chat.isTabHiddenOnThisDevice = isTabHiddenOnThisDevice;
    function isTabHiddenOnThisDevice() {
        device = $.inside.front.device;
        hideChatTab = false;
        // If theme setting explicitly enables showing the chat tab, never hide it
        try {
            if (chatSettings && chatSettings.chatPane && chatSettings.chatPane.showChatTabWithAvatars === true) {
                return false;
            }
        } catch (e) {}
        if (usingChatPanev2 && chatSettings && chatSettings.chatTab.hideChatTab) {
            if (chatSettings.chatTab.hideChatTabOnDevices.indexOf(device.toString()) != -1) {
                hideChatTab = true;
            }
        } else if ($.inside.front.settings.hideChatTab == true && typeof $.inside.front.settings.hideChatTabOnDevices != "undefined" && $.inside.front.settings.hideChatTabOnDevices != null) {
            if ($.inside.front.settings.hideChatTabOnDevices.indexOf(device.toString()) != -1) {
                hideChatTab = true;
            }
        } else {
            if ($.inside.front.settings.hideChatTab == true) {
                //not specified per device
                hideChatTab = true;
            }
        }
        return hideChatTab;
    }

    insideFrontInterface.chat.isOfflineTabHiddenOnThisDevice = isOfflineTabHiddenOnThisDevice;        
    function isOfflineTabHiddenOnThisDevice() {
        device = $.inside.front.device;
        if (typeof settings.offlineChat.hideOfflineChatTabOnDevices != "undefined" && settings.offlineChat.hideOfflineChatTabOnDevices != null) {
            if (settings.offlineChat.hideOfflineChatTabOnDevices.indexOf(device.toString()) != -1) {
                return true;
            }
        } else {
            if (settings.offlineChat.hideOfflineChatTab == true) {
                //not specified per device
                return true;
            }
        }
        return false;
    }

    function addCloseToChatTab(tab) {
        if(typeof tab == "undefined") {
            tab = $("#inside_liveChatTab");
        }
        $(tab).find(".chatHeaderIcons").remove();
        $(tab).append("<div class='chatHeaderIcons'></div>");

        var headerIcons =  $(tab).find(".chatHeaderIcons");
        var customCSS = "";

        var expandIcon = '<svg xmlns="http://www.w3.org/2000/svg" width="15" height="9" viewBox="0 0 15 9"><path fill="currentColor" fill-rule="nonzero" d="M5.996 1.5L0 7.494l1.5 1.5 5.995-5.997 5.997 5.996 1.499-1.499L7.495 0 5.996 1.5z"/></svg>';
        var closeIcon = '<svg xmlns="http://www.w3.org/2000/svg" width="15" height="15" viewBox="0 0 15 15"><path fill="currentColor" fill-rule="nonzero" d="M6.085 7.5L0 1.415 1.415 0 7.5 6.085 13.585 0 15 1.415 8.915 7.5 15 13.585 13.585 15 7.5 8.915 1.415 15 0 13.585 6.085 7.5z"/></svg>';

        if (settings.expandChatTabIcon && settings.expandChatTabIcon.length > 0) {
            expandIcon = "<img src='" + (customImage(settings.expandChatTabIcon)) + "' />";
        }
        if (!usingChatPanev2) {
            headerIcons.append("<div " + getAriaButtonAttribute(translate("Open")) + " class='inside_icon_image_holder icon-expand-image' title-data='" + translate("Open") + "'>" + expandIcon + "</div>");
        }

        if (!usingChatPanev2 && settings.closeButtonImage && settings.closeButtonImage.length > 0) {
            closeIcon = "<img src='" + (customImage(settings.closeButtonImage)) + "' />";
        }

        setTimeout(function () {
            headerIcons.find(".inside_closeCross").remove();
            headerIcons.append("<div " + getAriaButtonAttribute(translate("Close")) + " class='inside_icon_image_holder inside_closeCross' title-data='" + translate("Close Chat Tab") + "'>" + closeIcon + "</div>");

            if (usingChatPanev2 && headerIcons.length > 0) {
                headerIcons.addClass("chatV2");
            }

            if(tab.attr("id") == "inside_liveChatTab") {
                $(tab).find(".inside_closeCross").click(closeChatTab);
            } else {
                $(tab).find(".inside_closeCross").click(function() {
                    $(tab).hide();
                    windowScale();
                });
            }
        }, 0);

        setupTitleOnHover(headerIcons);

        $.inside.front.addStyleString(customCSS, "InsideChatTabCloseButton");
    }

    function closeChatTab(e) {
        e.stopPropagation();
        if(insideFrontInterface && insideFrontInterface.chat && insideFrontInterface.chat.doCloseAndHideChat) {
            insideFrontInterface.chat.doCloseAndHideChat();
        } 
        $("#inside_liveChatTab").hide();
        _insideGraph.doEvent("tabclosed");
        windowScale();
    }

    insideFrontInterface.chat.setupTitleOnHover = setupTitleOnHover;
    function setupTitleOnHover(selector) {
        $(selector).find('[title-data]').hover(function () {
            $(this).attr('title', $(this).attr('title-data'));
        }, function () {
            $(this).removeAttr('title');
        });
    }

    function addChatPaneHeaderToTab() {
        if ($("#inside_liveChatTab.usingChatHeader:visible").length > 0) {
            return;
        }

        if (usingChatPanev2) return;

        $("#inside_liveChatTab").empty();

        if (usingChatPanev2) return;
        $("#inside_liveChatTab").append("<div class='chatTab_header'><div class='chatTab_siteLogo'></div></div>");
        if (typeof (settings.siteLogo) != "undefined" && settings.siteLogo != "" && settings.siteLogo != null) {
            $(".chatTab_siteLogo").html("<img src='" + _insideCDN + settings.siteLogo + "' />");
        }

        if (typeof (settings.headerColour) != "undefined") {
            $("#inside_liveChatTab").css("background", settings.headerColour);
        }
        if (typeof (settings.chatBorderColour) != "undefined") {
            $("#inside_liveChatTab").css("border", "1px solid " + settings.chatBorderColour);
        }
        if (typeof (settings.width) != "undefined") {
            $("#inside_liveChatTab").css("width", settings.width + "px");
        }
        $("#inside_liveChatTab").addClass("usingChatHeader").addClass("noAutoHide");
        insideFrontInterface.setTabPosition();
        $("#inside_tabs").css('display', 'block');
        if (tabPosition.indexOf("bottom") != -1) {
            $("#inside_liveChatTab").appendTo("#inside_tabs");
        }

        if(insideFrontInterface.chat && insideFrontInterface.chat.setupChatPane) {
            insideFrontInterface.chat.setupChatPane();
        }

        if (insideFrontInterface.getAvailableAssistants().length == 0) {
            if(typeof insideOfflineForm != "undefined") insideOfflineForm.setOfflineFormStyles();
            if (settings.offlineChat && settings.offlineChat.headerImage) {
                $(".chatTab_siteLogo img").attr("src", customImage(settings.offlineChat.headerImage));
            }
        }

        insideFrontInterface.positionTabs();
    }

    insideFrontInterface.chat.setOfflineChatTab = setOfflineChatTab;
    function setOfflineChatTab() {
        chatSettings = _insideGraph.jQuery.inside.front.settings.chatSettings || _insideGraph.jQuery.inside.front.settings;
        settings = $.inside.front.settings;

        if (settings.enable3dAvatars != false && 
            insideFrontInterface.showAvatarsAlways && 
            (typeof insideChatPane != "undefined" && insideChatPane?.chatPane?.classList.contains("showAvatars")) && 
            (typeof insideChatPane == "undefined" || !insideChatPane?.avatarsDisabled)  ) {
            return;
        }

        $("#inside_holder").addClass("offline");
        device = $.inside.front.device;

        if (chatSettings && chatSettings.version == "2") {
            usingChatPanev2 = true;
            if (typeof insideChatPane != "undefined" && insideChatPane.showHeaderForTab) return;
            if (chatSettings.offline.enabled != true && !insideFrontInterface.chatInProgress && !activeChat) {
                $("#inside_liveChatTab").hide();
                return;
            }
        }

        if(!checkPrivacyOptIn()) {
            $("#inside_liveChatTab").hide();
            return;
        }

        if (settings && settings.useMinimiseButton === true) {
            useMinimiseButton = true;
        }
        if (!useMinimiseButton) {
            try {
                if (hasSessionStorage && sessionStorage.getItem("insideChatClosed") === "True") {
                    return;
                }
            } catch (e) { }
        }
        $(".inside-notification").remove();
        $("#inside_liveChatTab .chatHeaderIcons").remove();

        chatTabMode = "offline";
        insideFrontInterface.chatTabMode = chatTabMode;

        $("#inside_liveChatTab").removeClass("inside_chat_online").addClass("inside_chat_offline");

        var hideOfflineChatTab = (settings.offlineChat && settings.offlineChat.hideOfflineChatTab) && isOfflineTabHiddenOnThisDevice();
        if (hideOfflineChatTab) {
            $("#inside_liveChatTab").hide();
        }
        if (activeChat == true && settings.showTabForActive) {
            $("#inside_liveChatTab").show().css("opacity", "1");
        }

        if (!usingChatPanev2 && activeChat == false && $(".inside_dept_selector.selected").length == 0 && typeof insideWebApp == "undefined" && !$(".inside_chatPane").hasClass("offline")  && !$(".inside_chatPane").hasClass("clicktocall") ) {
            /* don't close if a department has been selected */
            if (typeof insideFrontInterface.chat.closeChatPane != "undefined")
                insideFrontInterface.chat.closeChatPane();
            if (!hideOfflineChatTab && settings && settings.offlineChat && settings.offlineChat.enabled) {
                $("#inside_liveChatTab").show().css("opacity", "1");
            }
        }

        if (usingChatPanev2) {
            var chatPaneIsOpen = (typeof insideChatPane != "undefined" && insideChatPane.isOpen && insideChatPane.isOpen());
            if (typeof chatSettings == "undefined" || typeof chatSettings.chatTab == "undefined" || chatPaneIsOpen) {
                return;
            }
            
            // Allow showing the tab when avatars mode is minimised and the theme flag is enabled
            var avatarMinimisedWhenOpen = false;
            try {
                avatarMinimisedWhenOpen = chatSettings && chatSettings.chatPane && chatSettings.chatPane.showChatTabWithAvatars === true &&
                    ((typeof insideChatPane != "undefined" && insideChatPane.frame && insideChatPane.frame.classList && insideChatPane.frame.classList.contains("minimised")) ||
                        (($("#insideChatPane").length) && $("#insideChatPane").hasClass("minimised")));
            } catch(e) { avatarMinimisedWhenOpen = false; }
            if (typeof chatSettings == "undefined" || typeof chatSettings.chatTab == "undefined" || (chatPaneIsOpen && !avatarMinimisedWhenOpen)) {
                return;
            }

            if ($("#inside_liveChatTab").length == 0) {
                addChatTab();
            } else if ($("#inside_liveChatTab .inside_chatTabImage").length == 0) {
                addTabContents();
            }

            if (typeof chatSettings.chatTab.offlineDesktopTab == 'undefined') { chatSettings.chatTab.offlineDesktopTab = ''; }
            if (typeof chatSettings.chatTab.offlineMobileTab == 'undefined') { chatSettings.chatTab.offlineMobileTab = ''; }

            var chatTabImageUrl;
            if (device === 1 && chatSettings.chatTab.offlineDesktopTab != "") {
                chatTabImageUrl = customImage(chatSettings.chatTab.offlineDesktopTab);
            } else if (chatSettings.chatTab.offlineMobileTab != "") {
                chatTabImageUrl = customImage(chatSettings.chatTab.offlineMobileTab);
            }

            //check for avatar tab
            if (device == 1 && chatSettings && chatSettings.chatTab && chatSettings.chatTab.useAvatar && chatSettings.chatTab.useAvatar.indexOf("desktop_offline") != -1 && chatSettings.chatTab.avatarChatTab) {
                chatTabImageUrl = customImage(chatSettings.chatTab.avatarChatTab);
            } else if (device >= 2 && chatSettings && chatSettings.chatTab && chatSettings.chatTab.useAvatar && chatSettings.chatTab.useAvatar.indexOf("mobile_offline") != -1 && chatSettings.chatTab.avatarChatTab) {
                chatTabImageUrl = customImage(chatSettings.chatTab.avatarChatTab);
            }

            updateChatTabImage(chatTabImageUrl);

            if (chatSettings.offline.hideTab != true) {
                $("#inside_liveChatTab").css("width", $("#inside_liveChatTab").find("img, svg").width() + "px").css("opacity", 1).show();
            }

            if (chatSettings.chatTab.shadowOnOfflineTab == true || chatSettings.chatTab.shadowOnOfflineTab == "true") {
                $("#inside_liveChatTab").addClass("insideDropShadow");
            } else {
                $("#inside_liveChatTab").removeClass("insideDropShadow");
            }

            if (chatSettings.chatTab.offlineChatTabDefault && chatSettings.chatTab.offlineChatTabDefault != "" && ((device != 2 && chatSettings.chatTab.offlineDesktopTab == "") || (device == 2 && chatSettings.chatTab.offlineMobileTab == ""))) {
                if (defaultOfflineSVGs) {
                    $("#inside_liveChatTab").html(defaultOfflineSVGs[chatSettings.chatTab.offlineChatTabDefault]);
                    $("#inside_liveChatTab").width($("#inside_liveChatTab svg").width());
                    scaleChatTab();
                    insideFrontInterface.positionTabs();
                } else {
                    return;
                }
            }

            if (chatSettings.offline.hideTab == true && chatSettings.offline?.hideOnDevices?.indexOf(device.toString()) != -1) {
                $("#inside_liveChatTab").hide();
            } else {
                $("#inside_liveChatTab").show();
            }

            if (chatSettings.chatTab.showCloseOnTab) {
                if (device == 1 && chatSettings.chatTab.showCloseOnTab.indexOf("desktop_offline") != -1) {
                    addCloseToChatTab();
                } else if (device == 2 && chatSettings.chatTab.showCloseOnTab.indexOf("mobile_offline") != -1) {
                    addCloseToChatTab();
                }
            }

            scaleChatTab();

            return;
        }

        if (!usingChatPanev2) {
            if (!usingChatPanev2 && settings != null && settings && settings.offlineChat && settings.offlineChat.enabled === true && !hideOfflineChatTab || (activeChat === true && settings && settings.showTabForActive)) {
                if ($("#inside_liveChatTab").length == 0) {
                    addChatTab();
                }

                //offline tab use chat pane header check
                if (!usingChatPanev2 && settings.showChatPaneHeaderAsChatTab && showChatPaneHeaderForDevice(true)) {
                    //use the chat pane header as the chat tab.
                    addChatPaneHeaderToTab();
                    addCloseToChatTab();

                } else {
                    $("#inside_liveChatTab").removeClass("usingChatHeader").removeClass("noAutoHide");
                    insideFrontInterface.setTabPosition();
                    //show the 'leave a message' tab and form
                    if (!$(".inside_chatPane, #inside_chatPane_custom, .inside-notification, #insideChatFrame.notificationMode").is(":visible")) {
                        $("#inside_liveChatTab").show();
                    }

                    if (hideOfflineChatTab) {
                        $("#inside_liveChatTab").hide();
                    }
                    if (activeChat == true && settings.showTabForActive && (!settings.offlineChat || !settings.offlineChat.hideOfflineChatTab)) {
                        $("#inside_liveChatTab").show().css("opacity", "1");
                    }

                    var prevTabImage = $("#inside_liveChatTab .inside_chatTabImage").attr("src");
                    var chatTabImageUrl;
                    if (device === 1) {
                        if (typeof (settings.offlineChat.chatTab) != "undefined" && settings.offlineChat.chatTab != null && settings.offlineChat.chatTab != "") {
                            chatTabImageUrl = customImage("/" + settings.offlineChat.chatTab);
                        } else {
                            if (tabPosition == "topright" || tabPosition == "right" || tabPosition == "bottomright") {
                                chatTabImageUrl = imageurl + "livechat_offline.png";
                            } else {
                                chatTabImageUrl = imageurl + "livechat_offline_left.png";
                            }
                        }
                    } else {
                        if (typeof (settings.offlineChat.chatTabMobile) != "undefined" && settings.offlineChat.chatTabMobile != null && settings.offlineChat.chatTabMobile != "") {
                            chatTabImageUrl = customImage("/" + settings.offlineChat.chatTabMobile);
                        } else {
                            chatTabImageUrl = imageurl + "livechaticon_mobile.png";
                        }
                    }

                    updateChatTabImage(chatTabImageUrl);

                    if (prevTabImage == $("#inside_liveChatTab .inside_chatTabImage").attr("src")) {
                        //no image change
                        setTabAutohide();
                    }
                }
            } else {
                //if there is a current chat, show the chat tab
                if (insideFrontInterface.chatInProgress) {
                    $(".inside-notification").remove();
                    setOnlineChatTab();
                }
                if (activeChat == false) {
                    $("#inside_holder #inside_liveChatTab").hide();
                }
            }
        }

        if (!hideOfflineChatTab && settings && settings.offlineChat && settings.offlineChat.enabled) {
            $("#inside_liveChatTab img").css("width", "auto");
            $("#inside_liveChatTab").css("width", "auto").css("opacity", 1).show();
            if ($("#inside_liveChatTab").hasClass('usingChatHeader')) {
                $("#inside_liveChatTab").outerWidth(settings.width || '');
            }
            scaleChatTab();
            setTimeout(scaleChatTab, 0);
        }

        if (!settings.autohideTabs) {
            insideFrontInterface.positionTabs();
        }
        if (activeChat && settings.autohideTabs == true) {
            setTimeout(function () { $.inside.front.autohideTabs(0); }, 1);
            setTimeout(function () { $.inside.front.autohideTabs(0); }, 250);
        }
        if (chatTabMode == "offline" && insideFrontInterface.chat.chatPaneOpen) {
            $("#inside_liveChatTab").hide();
        }
    }

    function addTabContents() {
        $("#inside_liveChatTab").html("<img class='inside_chatTabImage' src='data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==' alt='" + translate("Live chat icon, click to open the live chat pane.") + "' />");
         try {
            if($("img.inside_chatTabImage").length > 0) {
                $("img.inside_chatTabImage")[0].addEventListener("load", onChatTabImageLoad);
            }
        } catch(e){}
    }

    insideFrontInterface.addChatTab = addChatTab;
    function addChatTab() {
        if (settings && settings.useMinimiseButton === true) {
            useMinimiseButton = true;
        }

        if (useMinimiseButton) {
            try {
                if (hasSessionStorage && sessionStorage.getItem("insideChatClosed") === "True") {
                    return;
                }
            } catch (e) { }
        }

        if ($("#inside_tabs").length == 0) {
            $.inside.front.showTabs();
        }
        var addTab = true;
        hideChatTab = insideFrontInterface.chat.isTabHiddenOnThisDevice();
        if (hideChatTab && settings.showTabForActive != true) {
            addTab = false;
        }
        if (hideChatTab && settings.showTabForActive == true) {
            addTab = true;
        }
        if(settings.offlineChat && settings.offlineChat.enabled && !settings.offlineChat.hideOfflineChatTab && !isOfflineTabHiddenOnThisDevice()) {
            addTab = true;
        }
        var offlineV2Settings = chatSettings.offline || {};
        var offlineV2Hidden = offlineV2Settings.hideTab && offlineV2Settings.hideOnDevices && offlineV2Settings.hideOnDevices.indexOf(device.toString()) != -1;
        if(offlineV2Settings.enabled && !offlineV2Hidden) {
            addTab = true;
        }
        if (addTab) {
            $("#inside_tabs").hide();
            $("#inside_tabs").prepend("<div id='inside_liveChatTab' " + getAriaButtonAttribute(translate("Chat")) + "></div>");
            addTabContents();
        }


        $("#inside_liveChatTab").hide();
        $("#inside_liveChatTab").on("click enter", chatTabClick);
        $("#inside_liveChatTab").on('keypress', function (e) {
            if (e.which === 13) {
                $(this).trigger('enter');
            }
        });

        const liveChatTab = document.getElementById('inside_liveChatTab');
        if(liveChatTab) {
            liveChatTab.addEventListener('click', function() {
                if(typeof Notification !== 'undefined' && Notification.permission !== 'granted') {
                    Notification.requestPermission();
                }
            });
        }

        try {
            if($("img.inside_chatTabImage").length > 0) {
                $("img.inside_chatTabImage")[0].addEventListener("load", onChatTabImageLoad);
            }
        } catch(e){}

        if (insideFrontInterface.chatPaneVersion() == 1 && settings != null && typeof (settings.tabCSSMargins) != "undefined") {
            var marginArr = settings.tabCSSMargins.split(" ");
            //(top, right, bottom, left)
            //$(".inside_chatTabImage").css("margin", settings.tabCSSMargins);
            if (marginArr[0]) {
                $("#inside_tabs").css("margin-bottom", + (-parseInt(marginArr[0])) + "px");
            }
            if (marginArr[1]) {
                $("#inside_tabs").css("margin-right", marginArr[1]);
            }
            if (marginArr[2]) {
                $("#inside_tabs").css("margin-top", + (-parseInt(marginArr[2])) + "px");
            }
            if (marginArr[3]) {
                $("#inside_tabs").css("margin-left", marginArr[3]);
            }
        } else {
            if(usingChatPanev2) {
                setTabOffsetPosition();
            }
        }
        var touchPosX;
        var moveXpos;
        if (device == 2) {
            var mobileTabPosition = chatSettings.chatTab ? chatSettings.chatTab.mobileTabPosition : "";
            $("#inside_liveChatTab").on("touchstart", function (e) {
                touchPosX = (e.originalEvent && e.originalEvent.touches && e.originalEvent.touches.length > 0 ? e.originalEvent.touches[0].pageX : e.pageX);
                moveXpos = null;
            });
            
            $("#inside_liveChatTab").on("touchmove", function (e) {
                moveXpos = (e.originalEvent && e.originalEvent.touches && e.originalEvent.touches.length > 0 ? e.originalEvent.touches[0].pageX : e.pageX);
            });

            $("#inside_liveChatTab").on("touchend", function (e) {
                if(moveXpos != null && $("#inside_liveChatTab").attr("tabHidden") !== "true") {
                    if(Math.abs(touchPosX - moveXpos) > 20) {
                        if(["3", "6", "9"].indexOf(mobileTabPosition) != -1 && touchPosX < moveXpos) {
                            //swipe right
                            $.inside.front.autohideTabs();
                        } else if(["1", "4", "7"].indexOf(mobileTabPosition) != -1 && touchPosX < moveXpos) {
                            //swipe left
                            $.inside.front.autohideTabs();
                        }
                    }
                }
            });
        }

        if($.inside.front.settingsData.chatlinkvisitor && $.inside.front.settingsData.chatlinkvisitor.autoOpened != true) {
            insideFrontInterface.openChatPane();
            $.inside.front.settingsData.chatlinkvisitor.autoOpened = true; //prevent reopening
        }

        /* option to force open the chat pane when loading the page */
        if(window.location.search.indexOf("inside_openchat") != -1) {
            insideFrontInterface.openChatPane();
        }
    }

    //chatv2 tab offsets
    insideFrontInterface.chat.setTabOffsetPosition = setTabOffsetPosition;
    function setTabOffsetPosition() {
        if(!usingChatPanev2 || typeof chatSettings.chatTab === 'undefined') return;

        var tabSideOffset = chatSettings.chatTab.offset.side || '';
        if (device >= 2) {
            tabSideOffset = chatSettings.chatTab.mobileOffset.side || '';
        }

        if(!tabSideOffset) return;

        const holderStyle = document.getElementById('inside_holder').style;
        if (tabSideOffset != "") {
            try {
                var inside_tabs = document.querySelector("#inside_tabs");
                $("#inside_tabs").stop();
                var tabPosition = chatSettings.chatTab.position || "6";
                if (device >= 2) {
                    tabPosition = chatSettings.chatTab.mobileTabPosition || "9";
                }
                if (!tabPosition || tabPosition == "3" || tabPosition == "6" || tabPosition == "9") {
                    holderStyle.setProperty(`--inside-tab-left`, 'auto');
                    holderStyle.setProperty(`--inside-tab-right`, tabSideOffset + 'px');
                } else {
                    holderStyle.setProperty(`--inside-tab-right`, 'auto');
                    holderStyle.setProperty(`--inside-tab-left`, tabSideOffset + 'px');
                }
            } catch (e) { }
        }

        var tabVerticalOffset = chatSettings.chatTab.offset.vertical || '';
        if (device >= 2) {
            tabVerticalOffset = chatSettings.chatTab.mobileOffset.vertical || '';
        }

        if (tabVerticalOffset != "") {
            try {
                var inside_tabs = document.querySelector("#inside_tabs")
                var bottomOrMiddle = ["4", "6", "7", "9"];
                if (bottomOrMiddle.indexOf(chatSettings.chatTab[device === 1 ? 'position' : 'mobileTabPosition']) != -1) { //bottom or middle
                    holderStyle.setProperty(`--inside-tab-marginBottom`, parseInt(tabVerticalOffset) + 'px');
                } else {
                    holderStyle.setProperty(`--inside-tab-marginBottom`, -parseInt(tabVerticalOffset) + 'px');
                }
            } catch (e) { }
        }
    }

    function j2cTabClick() {
        if (device == 2 && $("#inside_joinTheCallChatTab").attr("autohide")) {
            insideFrontInterface.hoverShowTabs($("#inside_joinTheCallChatTab"));
            return;
        }
    }

    insideFrontInterface.chat.chatTabClick = chatTabClick;
    function chatTabClick(force) {
        if (insideFrontInterface.chat.preventTabClick) {
            insideFrontInterface.chat.preventTabClick = false;
            return;
        }

        insideFrontInterface.chat.num = 0;

        if (device > 1 && force !== true && $("#inside_liveChatTab").attr("tabHidden") === "true") {
            insideFrontInterface.hoverShowTabs($("#inside_liveChatTab"));
            return;
        }

        if (chatSettings && chatSettings.version == "2" && typeof insideChatPane == "undefined") {
            console.log("--- tabs add loading class");
            $('#inside_holder').addClass('loading tabClicked');
        }        

        $.inside.front.loadInsideChat(function () {
            if (usingChatPanev2 || insideFrontInterface.chatPaneVersion() == 2) {
                if (typeof insideChatPane == "undefined" || typeof insideChatPane.open == "undefined") {
                    if (typeof insideFrontInterface.chatPaneFrameReadyCallbacks == "undefined") {
                        insideFrontInterface.chatPaneFrameReadyCallbacks = [];
                    }
                    insideFrontInterface.chatPaneFrameReadyCallbacks.push(function () { chatTabClick(true) });
                    return;
                }

                try {
                	if(!insideChatPane.isOpen()) {
                        insideChatPane.frame.contentWindow.insideVideos.backToChat(true);
                    }
                } catch(e) {}

                insideChatPane.open(); //call to new v2 chat pane

                /* this is a message sent to the parent window for dashboard integration */
                if (window != window.top) {
                    window.parent.postMessage({
                        'func': 'openChat',
                        'message': 'Message text from iframe.'
                    }, "*");
                }

                return;
            }

            if(typeof insideLegacyChat != "undefined") {
                insideLegacyChat.chatTabClick(force);
            }
            
        });

        try {
            if(force !== true) {
                var chatSettingsId = chatSettings && chatSettings.chatSettingsId;
                var tabValue = insideFrontInterface.getAvailableAssistants().length ? 'Online' : 'Offline';
                $.inside.ga({ category: "Inside : Chat Tab", action: "Clicked", value: chatSettingsId, label: tabValue });
                _insideGraph.doEvent("tabclicked");
            }
        } catch (e) {
            console.log(e);
        }
    }

    function setTabAutohide() {
        if ($.inside.front.settings.autohideTabs) {
            if (device == 2 && $.inside.front.settings.autohideOnMobile == false) {
                //don't autohide on mobile
            } else if ($.inside.front.settings.autoHideTabOnLoad == true || $("#inside_liveChatTab").attr("tabHidden") == "true") {
                $("#inside_liveChatTab").attr("autohide", $.inside.front.settings.autoHideAmount || 20);
                $.inside.front.autohideTabs(0);
            } else {
                $("#inside_liveChatTab").attr("autohide", $.inside.front.settings.autoHideAmount || 20);
                insideFrontInterface.positionTabs();
                setTimeout(function() {
                    $.inside.front.autohideTabs(0);
                }, 1000);
            }
        } else {
            insideFrontInterface.positionTabs();
        }
    }

    insideFrontInterface.chat.onChatTabImageLoad = onChatTabImageLoad;
    function onChatTabImageLoad() {
        if (!settings.autohideTabs) {
            setTimeout(function() {
                insideFrontInterface.positionTabs();
            }, 0);
        }
        $("#inside_tabs").css('display', 'block');
        try {
            var img = new Image();
            img.onload = function() {
                if(this.width == 1) scaleChatTab();
                else scaleChatTab(this.width, this.height);
            }
            img.src = this.src;
        } catch (e) {
            scaleChatTab();
        }
        setTabAutohide();
        $.inside.front.windowScale();

        _insideGraph.doEvent("chatTabReady");
    }

    insideFrontInterface.chat.onJoinTheCallChatTabImageLoad = onJoinTheCallChatTabImageLoad;
    function onJoinTheCallChatTabImageLoad() {
        var hideAmount = 23;
        if (insideFrontInterface.chat.joinTheCallSettings.autohideAmount) {
            hideAmount = parseInt(insideFrontInterface.chat.joinTheCallSettings.autohideAmount);
            $("#inside_joinTheCallChatTab").attr("autohide", hideAmount);
        } else {
            hideAmount = 23;
            if (settings.autohideTabs == true) {
                $("#inside_joinTheCallChatTab").attr("autohide", hideAmount);
            }
        }

        setTimeout(function () {
            $("#inside_tabs").css('display', 'block');
            insideFrontInterface.windowScale();
            insideFrontInterface.positionTabs();
            if (insideFrontInterface.chat.joinTheCallSettings.autohideAmount && settings.autohideTabs != true) {
                $.inside.front.autohideTab($("#inside_joinTheCallChatTab"));
            }
        }, 500);

        if (insideFrontInterface.chat.joinTheCallSettings.tabSize == "" && !insideFrontInterface.chat.joinTheCallSettings.tabImage) {
            //default settings
            $("#inside_joinTheCallChatTab, #inside_joinTheCallImage").css({ width: 181, height: 115 });
            $("#inside_joinTheCallPasscode").css("padding-left", 23);
        } else {
            if (insideFrontInterface.chat.joinTheCallSettings.tabSize) {
                var size = insideFrontInterface.chat.joinTheCallSettings.tabSize.split(",");
                $("#inside_joinTheCallChatTab, #inside_joinTheCallImage").css("width", parseInt(size[0]) || this.width);
                $("#inside_joinTheCallChatTab, #inside_joinTheCallImage").css("height", parseInt(size[1]) || this.height);
            } else {
                $("#inside_joinTheCallChatTab").css("width", this.width);
                $("#inside_joinTheCallChatTab").css("height", this.height);
            }
            $("#inside_joinTheCallPasscode").css("padding-left", hideAmount);

        }
    }

    insideFrontInterface.scaleChatTab = scaleChatTab;
    function scaleChatTab(width, height) {
        settings = $.inside.front.settings;
        if (!$("#inside_liveChatTab").is(":visible")) {
            return;
        }

        if ($("#inside_liveChatTab img").length == 0 && $("#inside_liveChatTab svg").length == 0) return;

        if ($("#inside_liveChatTab svg").length == 0) {
            $("#inside_liveChatTab").css("width", "");
        }

        if ($("#inside_liveChatTab").hasClass("usingChatHeader")) {
            $("#inside_liveChatTab.usingChatHeader").css("width", settings.width + "px");
        } else {
            var w;
            if ($("#inside_liveChatTab img").length > 0) {
                w = width || $("#inside_liveChatTab img")[0].naturalWidth || $("#inside_liveChatTab img")[0].width || 100;
            }
            if ($("#inside_liveChatTab > svg").length > 0) {
                var attrWidth = parseInt($("#inside_liveChatTab > svg")[0].getAttribute("width"));
                if(width <= 1 && attrWidth > 1) {
                    w = attrWidth;
                } else {
                    w = width || $("#inside_liveChatTab > svg")[0].naturalWidth || attrWidth || 100;
                }                
            }
            var pr = 1;
            try {
                pr = window.devicePixelRatio;
            } catch (e) { }

            if (device > 1 && pr > 1) {
                var viewport = $.inside.front.getViewPortSize();

                if(usingChatPanev2 && typeof insideFrontInterface.chatSettings != "undefined" && typeof insideFrontInterface.chatSettings.chatTab.mobileTabWidth == "undefined") {
                    //width is set to "auto" in chat theme
                } else {
                    if (settings != null && typeof (settings.mobileTabWidth) != "undefined" && settings.mobileTabWidth != "") {
                        var widthType = typeof settings.mobileTabWidthType != 'undefined' ? settings.mobileTabWidthType : '%';
                        w = widthType == '%' ? (viewport.width * settings.mobileTabWidth * 0.01) : settings.mobileTabWidth;
                    } else {
                        if (w > viewport.width) {
                            w = viewport.width;
                        }
                        if (w < viewport.width * 0.1) {
                            w = viewport.width * 0.1;
                        }
                    }
                }

                $("#inside_liveChatTab").width(w);
                $("#inside_liveChatTab img, #inside_liveChatTab > svg").css("width", "100%");
                $("#inside_liveChatTab > svg").css("height", "100%");
                $("#inside_liveChatTab img").css("height", "auto");
            } else {
                $("#inside_liveChatTab").width(w);
            }
            if($("#inside_liveChatTab img").height() || height) {
                const naturalHeight = $("#inside_liveChatTab img")[0].naturalHeight;
                $("#inside_liveChatTab img").attr({ 'width': w, 'height': height || naturalHeight });
            }
            if(typeof insideChatPane !== 'undefined' && insideChatPane.frame) {
                insideChatPane.frame.contentDocument.querySelector(':root').style.setProperty("--chatTabWidth", w + 'px');
            }
        }

        $.inside.front.windowScale();
        insideFrontInterface.positionTabs();

        const $insideTabs = $("#inside_tabs");
        const bottom = parseInt($insideTabs.css("bottom"), 10);
        const marginBottom = parseInt($insideTabs.css("margin-bottom"), 10);
        const viewportHeight = window.visualViewport ? window.visualViewport.height : $(window).height();

        if (bottom + marginBottom > viewportHeight) {
            $insideTabs.css("margin-bottom", viewportHeight - bottom - $insideTabs.outerHeight());
        }
    }

    insideFrontInterface.setChatTabPosition = setChatTabPosition;
    function setChatTabPosition(pos) {
        tabPosition = pos;
        insideFrontInterface.tabPosition = tabPosition;
        if (settings != null && (typeof (settings.customTabImage) == "undefined" || settings.customTabImage == "")) {
            if (pos == "left" || pos == "middleleft" || pos == "bottomleft" || pos == "topleft") {

                $(".inside_chatPane, #inside_chatPane_custom").css("left", "0px").css("right", "auto");
                $("#inside_liveChatTab .inside_chatTabImage").attr("src", $.inside.front.imageurl + "livechaticon_left.png");
            }
        }
    }

    function fixChatTabImageInSafari() {
        var isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
        if (isSafari && device == 1) {
            // Safari-specific: Force image reload on resize to trigger cache-busting   
            let resizeTimeout;
            const handleResize = function() {
                clearTimeout(resizeTimeout);
                resizeTimeout = setTimeout(function() {
                    const $chatTabImage = $("#inside_liveChatTab .inside_chatTabImage");
                    if ($chatTabImage.length && $chatTabImage[0]) {
                        const originalSrc = $chatTabImage.attr('src');
                        if (originalSrc && originalSrc !== 'data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==') {
                            const baseSrc = originalSrc.split('?')[0];
                            const bustedSrc = baseSrc + '?cachebust=' + Math.random();
                            $chatTabImage.attr('src', bustedSrc);
                            
                            // Ensure it's fully decoded before using dimensions
                            try {
                                $chatTabImage[0].decode().then(function() {
                                    scaleChatTab();
                                }).catch(function() {
                                    // Fallback if decode fails
                                    scaleChatTab();
                                });
                            } catch (e) {
                                // Fallback for browsers that don't support decode()
                                scaleChatTab();
                            }
                        }
                    }
                }, 100); // Debounce resize events
            };
            
            window.visualViewport.addEventListener("resize", handleResize);
        }
    }

    insideFrontInterface.chat.clearUnreadChatNotifications = clearUnreadChatNotifications;
    function clearUnreadChatNotifications() {
        $("#inside_liveChatTab .inside_chatNotification").remove();
    }

    //shows a red number on the chat tab
    insideFrontInterface.chat.showChatTabNotification = showChatNotification;
    function showChatNotification(target, setUnreadMessages, message, getLastMessageFromOperator) {

        if (typeof (target) == "undefined" || target == null) {
            target = "#inside_liveChatTab";
        }
        var $target = $(target);
        var chatNotif;
        var num = 0;
        if (typeof setUnreadMessages === "function") {
            num = setUnreadMessages();
        }
        if (num == 0) {
            $target.find(".inside_chatNotification").remove();
            return;
        }
        if ($target.find(".inside_chatNotification").length > 0) {
            chatNotif = $target.find(".inside_chatNotification").text(num);
        } else {
            chatNotif = $("<div class='inside_chatNotification'>" + num + "</div>").appendTo(target);
        }

        if (usingChatPanev2 && chatSettings.chatPane.notifications.numberBgColor) {
            chatNotif.css("background-color", chatSettings.chatPane.notifications.numberBgColor);
            if (chatSettings.chatPane.notifications.numberColor)
                chatNotif.css("color", chatSettings.chatPane.notifications.numberColor);
        }

        //insideTween.TweenLite.to([chatNotif], 0, { scaleX: 0, scaleY: 0, ease: insideTween.Elastic.easeOut });
        //insideTween.TweenLite.to([chatNotif], 1, { scaleX: 1, scaleY: 1, ease: insideTween.Elastic.easeOut });
        chatNotif.addClass("notransition");
        chatNotif.css("transform", "scale(0)");
        setTimeout(function () {
            chatNotif.removeClass("notransition");
            chatNotif.css("transform", "scale(1)");
        }, 0);

        insideFrontInterface.chat.num = num;

        var msg = $.extend({}, ((typeof getLastMessageFromOperator == 'function' && getLastMessageFromOperator()) || message || null));
        if (msg && msg.text) {
            if (msg.contentType == "text/inside.legacy" || msg.text.indexOf("&lt;") != -1) {
                /* legacy chat will always be escaped html - this comes from proactive chat events still. */
                msg.text = $("<span></span>").html(msg.text).text();
                
            }
        }
        //notification text will have all html stripped
        msg.text = htmlToPlainText(msg.text);

        _insideGraph.doEvent("chatnotification", { message: msg, unreadMessageCount: num });

        insideFrontInterface.chat.setOnlineChatTab();
    }

    function htmlToPlainText(str) {
        var p = document.createElement("p"); p.innerHTML = str;
        return p.innerText;
    }

});;
var insideAPI = {};

(function (window, $) {

    $.xhrPool = [];
    $.xhrPool.abortAll = function () {
        $(this).each(function (idx, jqXHR) {
            jqXHR.abort();
        });
        $.xhrPool = [];
    };

    $.ajaxSetup({
        beforeSend: function (jqXHR) {
            $.xhrPool.push(jqXHR);
        },
        complete: function (jqXHR) {
            var index = $.xhrPool.indexOf(jqXHR);
            if (index > -1) {
                $.xhrPool.splice(index, 1);
            }
        }
    });

    function call(callName, args, success, error, async, type, dataType, contentType) {
        if (typeof (async) == "undefined") {
            async = true;
        }
        if (typeof (type) == "undefined") {
            type = "POST";
        }
        if (typeof (dataType) == "undefined") {
            dataType = "json";
        }
        if (typeof (contentType) == "undefined") {
            contentType = "application/json";
        }
        var urlVariables = "";
        if (typeof (_insideGraph) != "undefined") {
            var accesskey = _insideGraph.current.account + ":" + _insideGraph.pid + ":" + _insideGraph.accessKey;
            var accesscheck = _insideGraph.accessCheck;
            args.accesskey = accesskey;
            args.accesscheck = accesscheck;

            var ob = {};
            ob.accesskey = accesskey;
            ob.accesscheck = accesscheck;
            urlVariables = $.param(ob);
        }


        //var urlVariables = $.param(args);

        var urlpath;
        if (typeof (_insideSocialUrl) != "undefined") {
            urlpath = _insideSocialUrl;
        } else {
            urlpath = _insideLive;
        }

        var _preIE10 = (function () {
            if (navigator.appVersion.indexOf("MSIE") != -1) {
                var v = parseFloat(navigator.appVersion.split("MSIE")[1]);
                if (v < 10)
                    return true;
            }
            return false;
        })();

        // IE8 & 9 only Cross domain JSON GET request
        if (_preIE10 && 'XDomainRequest' in window && window.XDomainRequest !== null) {

            var xdr = new XDomainRequest(); // Use Microsoft XDR
            xdr.open('post', urlpath + "api/api_call.aspx?call=" + callName + ((urlVariables != "") ? "&" + urlVariables : ""));
            xdr.onload = function () {
                var dom = new ActiveXObject('Microsoft.XMLDOM');
                var response = $.parseJSON(xdr.responseText);

                dom.async = async;

                if (response == null || typeof (response) == 'undefined') {
                    response = $.parseJSON(data.firstChild.textContent);
                }

                if (typeof (success) == "function") {
                    success(response);
                }
            };

            xdr.onerror = function () {
                _result = false;
            };

            //args is a js object
            args = JSON.stringify(args);
            /*xdr.contentType = "application/json";*/

            xdr.onprogress = function () { };
            xdr.ontimeout = function () { };
            setTimeout(function () {
                xdr.send(args);
            }, 0);
            return xdr;
        }

        // IE7 and lower can't do cross domain
        else if (navigator.userAgent.indexOf('MSIE') != -1 &&
            parseInt(navigator.userAgent.match(/MSIE ([\d.]+)/)[1], 10) < 8) {
            return false;
        }

        // Do normal jQuery AJAX for everything else
        else {
            if (type == "POST") {
                args = JSON.stringify(args);
            }

            var headers = {};
            if (typeof (_insideCsrfToken) != "undefined" && _insideCsrfToken != null)
                headers['RequestVerificationToken'] = _insideCsrfToken;


            var sessionid = getInsideSessionId() || "";
            if (sessionid !== "") {
                headers.stoken = sessionid;
            }

            var apiCall = $.ajax({
                type: type,
                url: urlpath + "api/api_call.aspx?call=" + callName + ((urlVariables != "") ? "&" + urlVariables : ""),
                dataType: dataType,
                data: args,
                contentType: contentType,
                async: async,
                headers: headers,
                success: function (response) {
					/*
					if(response.status == "Error" && response.errorMessage == "Invalid access credentials") {
						//operator is logged out.
					}
					*/
                    if (!_insideIsLive) {
                        if (typeof ($.inside) != "undefined" && $.inside.logging == true) {
                            try {
                                console.info("API CALL '" + callName + "' success");
                                console.info("API args: ", args);
                                console.info(response);
                            } catch (e) {
                                console.log("API CALL '" + callName + "' success");
                                console.log("API args: ", args);
                                console.log(response);
                            }
                        }
                    }
                    if (typeof (success) == "function") {
                        success(response);
                    }
                },
                error: function (response) {
                    if (!_insideIsLive) {
                        console.log(response);
                    }
                    if (typeof (error) == "function") {
                        try {
                            console.log("API CALL '" + callName + "' error");
                            console.log("API args: ", urlVariables);
                            error(response);
                        } catch (e) { }
                    }
                }
            });
            return apiCall;
        }
    }
    /** returns the root path for API calls */
    function getApiPath() {
        var path = _insideLive;
        if ( typeof ( _insideLive ) == "boolean" && _insideSocialUrl ) {
            path = _insideSocialUrl;
        }
        return path;
    }

    insideAPI.prepareApiUrl = prepareApiUrl;
    function prepareApiUrl(call) {

        var url = new URL(call.indexOf("http") == 0 ? call : getApiPath() + call);
        url.pathname = url.pathname.replace(/^\/\//, "/");
        return url;
    }

    function setRequestHeaders(request) {
        if (typeof _insideGraph !== "undefined") {
            request.setRequestHeader("accesskey", _insideGraph.current.account + ":" + _insideGraph.pid + ":" + _insideGraph.accessKey);
            request.setRequestHeader("accesscheck", _insideGraph.accessCheck);
        } else if (typeof assistantData !== "undefined" && assistantData && assistantData.sessionId) {
            request.setRequestHeader("stoken", assistantData.sessionId);
        }
    }

     function setFetchRequestHeaders(headers) {
        if (typeof _insideGraph !== "undefined") {
            headers.append("accesskey", _insideGraph.current.account + ":" + _insideGraph.pid + ":" + _insideGraph.accessKey);
            headers.append("accesscheck", _insideGraph.accessCheck);
        } else if (typeof assistantData !== "undefined" && assistantData && assistantData.sessionId) {
            headers.append("stoken", assistantData.sessionId);
        }
        
        return headers;
    }

    function parseJSONResponse(response) {
        return new Promise((resolve, reject) => {
            const contentType = response?.headers?.get('Content-Type');
            
            // First try to get the text content
            response?.clone?.()?.text?.()
                .then(textContent => {
                    // If we have text content, try to parse it as JSON
                    if (textContent) {
                        try {
                            // Try to parse the text as JSON
                            const jsonData = JSON.parse(textContent);
                            resolve(jsonData);
                        } catch (e) {
                            // If parsing fails but response is OK, return the text or a success object
                            if (response.ok) {
                                // If content type indicates JSON but parsing failed, return the raw text
                                if (contentType && (contentType.includes('application/json') || contentType.includes("text/json"))) {
                                    resolve(textContent);
                                } else {
                                    resolve({success: true, status: 200, text: textContent});
                                }
                            } else {
                                reject(response);
                            }
                        }
                    } else if (response.ok) {
                        // Empty but successful response
                        resolve({success: true, status: 200});
                    } else {
                        reject(response);
                    }
                })
                .catch(error => {
                    // If we can't even get the text, fall back to the original method
                    if (contentType && (contentType.includes('application/json') || contentType.includes("text/json"))) {
                        response?.clone?.()?.json?.()
                            .then(resolve)
                            .catch(() => {
                                if(response.ok) resolve({success: true, status: 200});
                                else reject(response);
                            });
                    } else {
                        reject(response);
                    }
                });
        });
    }

    class AbortError extends Error {
        constructor(message, reason) {
            super(message);
            this.name = "AbortError";
            this.reason = reason;
        }
    }

    // post to the new API structure, eg "api/live/teams/update"
    function post(call, data, success, error, abortController, forceIgnoreFetch = false, timeout = null, ignoreAsyncAwait=false) {
        if (typeof (error) === "undefined") {
            error = null;
        }

        var url = prepareApiUrl(call);

        if (window.fetch && !forceIgnoreFetch) {
            const headers = new Headers();
            headers.append("Content-Type", "application/json");
            setFetchRequestHeaders(headers);

            const controller = abortController || new AbortController();
            const signal = controller.signal;

            const fetchOptions = {
                method: "POST",
                headers: headers,
                body: JSON.stringify(data),
                signal: signal,
            };

            let timeoutId;
            let timeoutPromise;
            let abortReason = null;

            // Set up the timeout if provided
            if (timeout !== null) {
                timeoutPromise = new Promise((_, reject) => {
                    timeoutId = setTimeout(() => {
                        abortReason = 'timeout';
                        controller.abort();
                        reject(new AbortError('Fetch request timed out', abortReason));
                    }, timeout);
                });
            }
            const fetchPromise = fetch(url, fetchOptions)
                .then(response => {
                    if (timeoutId) {
                        clearTimeout(timeoutId);
                    }
                    response.requestData = data;
                    response.usingFetch = true;
                    if (response.ok) {
                        return parseJSONResponse(response);
                    } else {
                        throw response;
                    }
                })
                .catch(async err => {
                    if (timeoutId) {
                        clearTimeout(timeoutId);
                    }
                    let errorText;

                    if (err instanceof Response) {
                        // Check if the error is an instance of Response
                        const responseJson = await parseJSONResponse(err);
                        err.responseJSON = err.responseJSON ? err.responseJSON : responseJson;
                    } else if (err instanceof AbortError) {
                        // Handle custom AbortError for fetch timeout and manual abort separately
                        if (err.reason === 'timeout') {
                            errorText = 'Fetch request timed out';
                            err.errorCode = "1";
                        } else if (err.reason === 'cancelled') {
                            errorText = 'Fetch request was manually aborted';
                            err.errorCode = "2";
                        }
                    } else if (err.name === 'AbortError') {
                        // Handle native AbortController errors (e.g., manual abort)
                        errorText = abortReason === 'timeout' ? 'Fetch request timed out' : 'Fetch request was aborted';
                        err.errorCode = abortReason === 'timeout' ? "1" : "2";
                    } else {
                        // Handle other types of errors (e.g., network errors)
                        errorText = err.message || 'An unknown error occurred';
                    }

                    // Handle errors
                    var path = getApiPath();
                    if (window.top != window) return;

                    if (path == _insideLive && err && err.status === 403 && (!$.inside || !insideHub || $.inside.isDisconnected())) {
                        connected = false;
                        if (typeof (virtualStore) != "undefined" && virtualStore && typeof (virtualStore.showLoadingDialog) == "function") {
                            virtualStore.showLoadingDialog(insideLanguage.translatePhrase("You have been disconnected from INSIDE, redirecting to the login screen...") + "<span class='loadingIcon'></span>");
                        }
                        setTimeout(() => {
                            window.location.href = _insideLive + 'login';
                        }, 4000);
                    } else if (err.errorCode !== "2") { // Don't return error for cancelled requests.
                        throw err;
                    }
                });

            const promiseToReturn = timeoutPromise ? Promise.race([fetchPromise, timeoutPromise]) : fetchPromise;
            
            if (success) {
                fetchPromise.then(success).catch(err => { if (error) error(err); });
                return {
                    promise: promiseToReturn,
                    usingFetch: true,
                    requestData: data,
                    abort: (reason = 'cancelled') => {
                        abortReason = reason;
                        controller.abort();
                    }
                };
            } else {
                return promiseToReturn;
            }
        } else {
            if(ignoreAsyncAwait) {
                return $.ajax({
                    type: "post",
                    url: url,
                    beforeSend: function (request) {
                        setRequestHeaders(request);
                    },
                    dataType: "json",
                    data: JSON.stringify(data),
                    contentType: "application/json",
                    async: true,
                    success: success,
                    error: function (jqXhr, textStatus, errorThrown) {
                        var path = getApiPath();
                        if (path == _insideLive && jqXhr && jqXhr.status === 403 && (!$.connection || !$.connection.hub || $.connection.hub.state === $.signalR.connectionState.disconnected)) {
                            connected = false;
                            if (typeof (virtualStore) != "undefined" && virtualStore && typeof (virtualStore.showLoadingDialog) == "function") {
                                virtualStore.showLoadingDialog(insideLanguage.translatePhrase("You have been disconnected from INSIDE, redirecting to the login screen...") + "<span class='loadingIcon'></span>");
                            }
                            setTimeout(() => {
                                window.location.reload();
                            }, 4000);
                        } else if (error) {
                            error(jqXhr, textStatus, errorThrown);
                        }
                    },
                });
            }
            // Fallback to using jQuery.ajax if fetch is not supported
            const ajaxPromise = new Promise((resolve, reject) => {
                $.ajax({
                    type: "post",
                    url: url,
                    beforeSend: function (request) {
                        setRequestHeaders(request);
                    },
                    dataType: "json",
                    data: JSON.stringify(data),
                    contentType: "application/json",
                    async: true,
                    success: function (responseData) {
                        if (success) {
                            success(responseData);
                        } else {
                            resolve(responseData);
                        }
                    },
                    error: function (jqXhr, textStatus, errorThrown) {
                        if (window.top != window) return;

                        var path = getApiPath();
                        if (path == _insideLive && jqXhr && jqXhr.status === 403 && (!$.inside || $.inside.isDisconnected())) {
                            connected = false;
                            if (typeof (virtualStore) != "undefined" && virtualStore && typeof (virtualStore.showLoadingDialog) == "function") {
                                virtualStore.showLoadingDialog(insideLanguage.translatePhrase("You have been disconnected from INSIDE, redirecting to the login screen...") + "<span class='loadingIcon'></span>");
                            }
                            setTimeout(() => {
                                window.location.href = _insideLive + 'login';
                            }, 4000);
                        } else if (error) {
                            error(jqXhr, textStatus, errorThrown);
                        }

                        reject({ jqXhr, textStatus, errorThrown });
                    },
                });
            });

            return ajaxPromise;
        }

    }

	function get(call, data, success, error) {
		if (typeof (error) == "undefined") {
			error = null;
		}

		var url = prepareApiUrl( call);

		// Check if fetch is supported by the browser
		if (window.fetch) {  
			const headers = new Headers();
			headers.append("Content-Type", "application/json");
			setFetchRequestHeaders(headers);

			return fetch(url, {
				method: "GET",
				headers: headers,
				//body: JSON.stringify(data), //fetch GET can't have a body
			}).then(response => {
				if (response.ok) {
					return response.json().then(success);
				} else {
					throw response;
				}
			}).catch(err => {
				// Handle errors
				var path = getApiPath();
				if (path == _insideLive && err && err.status === 403 && (!insideHub || $.inside.isDisconnected())) {
					connected = false;
					if (typeof (virtualStore) != "undefined" && virtualStore && typeof (virtualStore.showLoadingDialog) == "function") {
						virtualStore.showLoadingDialog(insideLanguage.translatePhrase("You have been disconnected from INSIDE, redirecting to login screen...") + "<span class='loadingIcon'></span>");
					}
					setTimeout(() => {
                        window.location.href = _insideLive + 'login';
                    }, 4000);
				} else if (error) {
					error(err, err.message, err.name);
				} 
			});
		} else {
			// Fallback to using jQuery.ajax if fetch is not supported
			return $.ajax({
				type: "get",
				url: url,
				dataType: "json",
				data: JSON.stringify(data),
				contentType: "application/json",
				async: true,
				success: success,
				error: function (jqXhr, textStatus, errorThrown) {
					var path = getApiPath();
					if (path == _insideLive && jqXhr && jqXhr.status === 403 && (!insideHub || $.inside.isDisconnected())) {
						connected = false;
						if (typeof (virtualStore) != "undefined" && virtualStore && typeof (virtualStore.showLoadingDialog) == "function") {
							virtualStore.showLoadingDialog(insideLanguage.translatePhrase("You have been disconnected from INSIDE, redirecting to login screen...") + "<span class='loadingIcon'></span>");
						}
						setTimeout(() => {
                            window.location.href = _insideLive + 'login';
                        }, 4000);
					}
					else if (error) error(jqXhr, textStatus, errorThrown);
				}
			});
		}
	}

    insideAPI.handlePostError = handlePostError;
    function handlePostError(xhr, textStatus, errorThrown, alertTitle) {
        if (textStatus === "abort") {
            return;
        }
        
        if (!alertTitle) {
            alertTitle = "";
        }
        
        if (xhr.status === 403) {
            // if AWS WAF security rule triggered, we display appropriate message
            if(xhr.getResponseHeader("server") === "awselb/2.0"){
                insidePopup.showAlert("This action cannot be performed as it failed to satisfy security rules.", "ok", null, true, {
                    title: (alertTitle ? alertTitle : "Denied"),
                    anim: false
                });
            }else {
                insidePopup.showAlert("Access denied", "ok", null, true, {
                    title: (alertTitle ? alertTitle : "Forbidden"),
                    anim: false
                });
                setTimeout(location.reload.bind(location), 5000);
            }
            return;
        }
        
        // Handle both fetch Response objects and jQuery AJAX jqXHR objects
        function processErrorResponse(responseText) {
            var responseJson;
            try {
                responseJson = JSON.parse(responseText);
            } catch (e) {
                responseJson = "";
            }

            var errorMessage;
            
            if (responseJson && responseJson.msg && responseJson.msg !== "") {
                errorMessage = responseJson.msg;
            }else if (responseText && responseText !== "") {
                errorMessage = responseText;
            }else if (errorThrown){
                errorMessage = errorThrown;
            }else if (!window.navigator.onLine || (!$.inside || $.inside.isDisconnected())) {
                errorMessage = insideLanguage.translatePhrase("There has been an unexpected connection issue. Please try again.");
            } else {
                errorMessage = insideLanguage.translatePhrase("Invalid data provided");
            }
            
            insidePopup.showAlert(errorMessage, "ok", null, true, {title: alertTitle || 'Error', anim: false});
        }
        
        // Check if xhr has .text() method (fetch Response) or .responseText property (jQuery AJAX)
        if (typeof xhr.text === 'function') {
            xhr.text().then(processErrorResponse);
        } else if (xhr.responseText !== undefined) {
            processErrorResponse(xhr.responseText);
        } else {
            processErrorResponse("");
        }
    }

    function ajax(ajaxData) {
        return $.ajax(ajaxData);
    }

    insideAPI.call = call;
    insideAPI.post = post;
    insideAPI.get = get;
    insideAPI.ajax = ajax;
})(window, typeof (_insideGraph) != "undefined" ? _insideGraph.jQuery : $);;
/* checks if streaming is enabled and browser support exists then loads in the streaming bundle.*/

//------------------------------------------------------------------------------

// MH 16/10/2020
// For testing injection of streams into a container.
// Create a container, add to website, and set this to inject the shows list to.
// Comment out to disable and use the tab.
// This 'insideStreamingContainerId' variable will be added in the integration script for production.


if (document.location.href.indexOf("dev.powerfront.com") != -1 || document.location.href.indexOf("staging.powerfront.com") != -1 || document.location.href.indexOf("staging2012.powerfront.com") != -1 || document.location.href.indexOf("inside-local/localtest")) {
	if(document.title.indexOf(" | ") == -1 && document.querySelector(".cell45, .cell34")) { // on homepage of dev ecommerce site this is front and centre.
		var holder = document.createElement("div");
		document.body.appendChild(holder);
		//document.querySelector(".cell45, .cell34").innerHTML = "";
		document.querySelector(".cell45, .cell34").prepend(holder);
		holder.id = "insideStreamContainer";
		holder.style.height = "600px";
		window.insideStreamingContainerId = "insideStreamContainer";
	}
	
}


//------------------------------------------------------------------------------

var insideStreamingCheck = new function() {
	var _this = this;
	this.bundleLoaded = false;
	this.init = init;
	function init() {
		if(document.location.href.indexOf("insideshowid") != -1 || window.insideStreamingContainerId) {
			if(typeof insideStreaming == "undefined") {
				loadStreamingBundle();
			}
		}
	}

	function browserSupports() {
		if(isIE() || 
			(browserType[0] == "Chrome" && parseInt(browserType[1]) < 40) ||
			(browserType[0] == "Firefox" && parseInt(browserType[1]) < 34) ||
			(browserType[0] == "Safari" && parseFloat(browserType[1]) < 9.1) ||
			(browserType[0] == "Opera" && parseFloat(browserType[1]) < 29) ||
			(browserType[0] == "Edge" && parseFloat(browserType[1]) < 13)
		) {
			return false;
		}		
		return true && !!window.WebSocket;
	}

	var browserType = (function(){
		var ua = navigator.userAgent, tem, 
		M = ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
		if(/trident/i.test(M[1])){
		    tem =  /\brv[ :]+(\d+)/g.exec(ua) || [];
		    return 'IE '+(tem[1] || '');
		}
		if(M[1]=== 'Chrome'){
		    tem = ua.match(/\b(OPR|Edge)\/(\d+)/);
		    if(tem!= null) return tem.slice(1).join(' ').replace('OPR', 'Opera');
		}
		M= M[2]? [M[1], M[2]]: [navigator.appName, navigator.appVersion, '-?'];
		if((tem= ua.match(/version\/(\d+)/i))!= null) M.splice(1, 1, tem[1]);
		return M
	})();

	function isIE() {
		var ua = navigator.userAgent;
		return ua.indexOf('MSIE') > -1 || ua.indexOf('Trident') > -1;
	}

	var streamingBundleLoading = false;
	var bundleLoadedCallbacks = [];
	this.loadStreamingBundle = loadStreamingBundle;
	function loadStreamingBundle(callback) {
		if(typeof insideStreaming != "undefined") {
			//already loaded
			if(typeof callback == "function") {
				callback();
			}
			return;
		}		
		if(typeof callback == "function") {
			bundleLoadedCallbacks.push(callback);
		}
		if(streamingBundleLoading) return;
		streamingBundleLoading = true;

		if(!browserSupports()) {
			alert(getAlertMessage());
			return;
		}
		var $ = _insideGraph.jQuery;
		if (location.href.indexOf("dev.powerfront") != -1 || location.href.indexOf("localhost") != -1 || location.href.indexOf("inside-local") != -1 || (new RegExp("dev*.-live.inside-graph.com")).test(location.href)) {
			_insideGraph.loadJS($.inside.insideScript + "/streaming/inside.front.streaming.js?v=" + _insideScriptVersion, function() {return typeof insideStreaming != 'undefined'}, function() {
				_insideGraph.loadJS($.inside.insideScript + "/streaming/inside.front.showcase.js?v=" + _insideScriptVersion, function() {return typeof insideShowcase != 'undefined'}, bundleLoaded);
			});
			_insideGraph.jQuery.inside.front.loadCssFile($.inside.insideScript + "/streaming/inside.front.streaming.css?v=" + _insideScriptVersion, function () {
				console.log("streaming css loaded");
			});
		}
		else {
			_insideGraph.loadJS($.inside.insideScript + "streaming_min.js?v=" + _insideScriptVersion, function() {return typeof insideStreaming != 'undefined'}, bundleLoaded);
			_insideGraph.jQuery.inside.front.loadCssFile($.inside.insideScript + "streaming_min.css?v=" + _insideScriptVersion, function () {
				console.log("streaming css loaded");
			});
			console.log('from streaming.check.js');
		}
	}

	function bundleLoaded() {
		//streaming bundle has loaded
		insideStreaming.init(_insideGraph.jQuery);
		_this.bundleLoaded = true;
		for(var i=0;i<bundleLoadedCallbacks.length;i++) {
			if(typeof bundleLoadedCallbacks[i] == "function") {
				bundleLoadedCallbacks[i]();
			}
		}
		bundleLoadedCallbacks = [];
	}

	function getAlertMessage() {
		var iosMessage = "" + 
		"Apologies, but the Show could not start.\n" + 
		"Your current iOS version is not supported.\n" + 
		"Please upgrade to iOS 13 (or above) or please join on another device.";

		var macMessage = "" + 
		"Apologies, but the Show could not start.\n" +
		"Your current web browser is not supported.\n" +
		"Please try one of the following web browsers:\n" +
		"Chrome (version 81 or above)\n" +
		"Safari (version 12 or above)\n" +
		"Firefox (version 77 or above)"

		var windowsMessage = "" + 
		"Apologies, but the Show could not start.\n" + 
		"Your current web browser is not supported.\n" + 
		"Please try one of the following web browsers:\n" + 
		"Chrome (version 81 or above)\n" + 
		"Edge (version 81 or above)\n" + 
		"Firefox (version 77 or above)";

		var androidMessage = "" + 
		"Apologies, but the Show could not start.\n" + 
		"Your current web browser is not supported.\n" + 
		"Please try one of the following web browsers:\n" + 
		"Chrome (version 81 or above)\n" + 
		"Android Browser (version 81 or above)\n" + 
		"Firefox (version 77 or above)\n" + 
		"QQ Browser (version 10.4 or above)\n" + 
		"Baidu (version 7.12 or above)";

		var defaultMessage = windowsMessage;

		if(iOS()) {
			return iosMessage;
		} else if (navigator.appVersion.indexOf("Win") != -1) {
			return windowsMessage; 
		} else if (navigator.appVersion.indexOf("Mac") != -1) {
			return macMessage;
		} else if(userAgent.indexOf("android") > -1) {
			return androidMessage;
		} else {
			return windowsMessage;
		}

	}

	function iOS() {
		if(navigator.platform.indexOf("iPhone") != -1 || navigator.platform.indexOf("iPod") != -1 || 
			navigator.platform.indexOf("iPhone") != -1 || navigator.platform.indexOf("iPad") != -1) {
			return true;
		}
		return false;
	}
};
var insideCreditCard = new function () {
    //if the str contains a credit card number/s, replace it with *s.
    var CreditCardData = [];
    insideFrontInterface.chat.checkForCreditCardNumbers = checkForCreditCardNumbers;
    //https://jsfiddle.net/remyburney_powerfront/eo8d5u7g/
    function checkForCreditCardNumbers(str, settings) {
        
        //var regex = "\\b(([0-9]){4}(.?)\\s*){3}(([0-9]){2,4}(.?))\\b";
        var regex = "(\\d(\\D){0,4}){13,19}"; //detect a number which may contain separators of any character or length.
        
        var ccReg = new RegExp(regex, "g"); //rough check for 13-25 (or 99) digit number with any character in between

        var matches = str.match(ccReg);

        if (matches == null || matches.length <= 0) {
            return str;
        }
        
        // check for exclusions using the whole message
        if(matchExclusions(str,settings)) return str;

        var justNumber = str.replace(/(\D*)/g, "");
        var numbersArr = getPossibleCardNumbers(justNumber);
        numbersArr = numbersArr.sort((a, b) => b.length - a.length);
        
        for (var j = 0; j < numbersArr.length; j++) {
            var val = numbersArr[j];
            //603528 matches STAPLES Canada Enterprise Credit Card (issued by Citi Cards Canada)
            if (!valid_credit_card(val) || !IsValidCard(val)) {
                continue;
            }
            //matches[j] = matches[j].replace(/[0-9]/g, "*");
            if (settings.pciCreditMasking) {
                val = val.substring(0, val.length - 4);
            }
            var reg = new RegExp(val.split("").join("(\\D{0,4})"), "g");
            var ccmatches = str.match(reg, val);
            if (ccmatches != null && ccmatches.length > 0) {
                mainloop: for (var i = 0; i < ccmatches.length; i++) {
                    var match = ccmatches[i];

                    // Check exclusion list for the matched value
                    if (settings.ccMaskExclusionsEnabled === true && settings.ccMaskExclusions) {
                        //check against exceptions
                        for (var k = 0; k < settings.ccMaskExclusions.length; k++) {
                            var regexExclusion = new RegExp(settings.ccMaskExclusions[k], "gi");
                            if (match.match(regexExclusion)) {
                                continue mainloop; //matches an exception
                            }
                        }
                    }
                    
                    str = str.replace(match, match.replace(/\d/g, "*"));
                }
            }

        }

        return str;
    }

    insideFrontInterface.chat.checkForCreditCardExclusions = matchExclusions;
    function matchExclusions(str, settings){
        if (!(settings.ccMaskExclusionsEnabled === true && settings.ccMaskExclusions)) {
            return false
        } 
        //check against exceptions
        for (var k = 0; k < settings.ccMaskExclusions.length; k++) {
            var regexExclusion = new RegExp(settings.ccMaskExclusions[k], "gi");
            if (str.match(regexExclusion)) {
                return true;
            }
        }
        return false
    }

    function getPossibleCardNumbers(number)
    {
        var result = [];

        if (number.length < 13) return result;

        for (var i = 13; i <= 19; i++)
        {
            for (var j = 0; j <= number.length - i; j++)
            {
                result.push(number.substring(j, i+j));
            }
        }

        return result;
    }

    insideFrontInterface.chat.strictReplaceNumbers = strictReplaceNumbers;
    function strictReplaceNumbers(str, settings) {
        if(matchExclusions(str, settings)) {
            return str;
        }
        var ccReg = /\b([0-9](.?)){4,99}\b/g; //rough check for 4-99 digit number
        var matches = str.match(ccReg);
        if (matches != null && matches.length > 0) {
            for (var i = 0; i < matches.length; i++) {
                var val = matches[i];
                matches[i] = matches[i].replace(/[0-9]/g, "*");
                str = str.replace(val, matches[i]);
            }
        }
        return str;
    }

    insideFrontInterface.chat.valid_credit_card = valid_credit_card;
    function valid_credit_card(value) {
        // accept only digits, dashes or spaces (or '.'s 08-03-2017)
        //if (/[^0-9-\s\.]+/.test(value)) return false;
        // 16-3-2018 CCs can have any characters between numbers

        // The Luhn Algorithm. It's so pretty.
        var nCheck = 0, nDigit = 0, bEven = false;
        value = value.replace(/\D/g, "");

        for (var n = value.length - 1; n >= 0; n--) {
            var cDigit = value.charAt(n),
                nDigit = parseInt(cDigit, 10);

            if (bEven) {
                if ((nDigit *= 2) > 9) nDigit -= 9;
            }

            nCheck += nDigit;
            bEven = !bEven;
        }

        return (nCheck % 10) == 0;
    }

    function IsValidCard(number)
    {
        var foundCardType = false;
        brandloop: for (var brandData of CreditCardData)
        {
            // CardInfo from one brand.
            var brandInfo = brandData.BrandInfo;

            for (var rule of brandInfo.Rules)
            {
                if (!rule.Lengths.includes(number.length) || typeof(rule.Prefixes.find(el => number.startsWith(el))) == "undefined") continue;
                foundCardType = true;
                break brandloop;
            }
        }

        return foundCardType;
    }

    var IssuerIdentificationNumbers = [
        "30", // Diners
        "3746010", // HSBC Retail
        "35", // JBC
        "36", // Diners Club International
        "37", // American Express
        "38", //  Hipercard by Itaú Unibanco
        "4", // "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", // Visa
        "50", "51", "52", "53", "54", "55", "56", "57", "58", // Mastercard
        "60" // other banking/financial
    ];

    const CardIssuer = {
        AmericanExpress: 0,
        ChinaUnionPay: 1,
        Dankort: 2,
        DinersClub: 3,
        Discover: 4,
        Hipercard: 5,
        JCB: 6,
        Laser: 7,
        Maestro: 8,
        MasterCard: 9,
        RuPay: 10,
        Switch: 11,
        Visa: 12,
        Unknown: 13
    };

    var BrandInfo = function (rules, brandName, skipLuhn) {
        var _this = this;
        _this.Rules = rules;
        _this.BrandName = brandName;
        if (typeof (skipLuhn) == "undefined" || typeof (skipLuhn) != "boolean" || typeof (skipLuhn) == null)
            skipLuhn = false;
        _this.SkipLuhn = skipLuhn;
    }

    var Rule =  function (lengths, prefixes) {
        var _this = this;
        _this.Lengths = lengths;
        _this.Prefixes = prefixes;

    }

    var BrandData = function (cardIssuer, brandInfo) {
        var _this = this;
        _this.CardIssuer = cardIssuer;
        _this.BrandInfo = brandInfo;
    }

    function generateRange(start,  end)
    {
        var ret = [];
        for (var i = start; i <= end; i++)
        {
            ret.push(i.toString());
        }

        return ret;
    }

    this.init = init;
    function init() {

        CreditCardData = [];
        CreditCardData.push(
            new BrandData(CardIssuer.Visa, new BrandInfo
                (
                    [new Rule([13, 16, 19], ["4"])]
                    , "Visa"
                )
            )
        );       

        var prefixes = [];
        prefixes =  prefixes.concat(generateRange(51, 55));
        prefixes =  prefixes.concat(generateRange(2221, 2720));

        var masterCardRule1 = [new Rule([16], prefixes)];

        var masterCard = new BrandInfo(masterCardRule1, "MasterCard");
        var brandData = new BrandData(CardIssuer.MasterCard, masterCard);
        CreditCardData.push(brandData);

        CreditCardData.push(
            new BrandData(CardIssuer.AmericanExpress, new BrandInfo
                (
                    [new Rule([15], ["34", "37"])]
                    , "American Express"
                )
            )
        );

        CreditCardData.push(
            new BrandData(CardIssuer.Discover, new BrandInfo
                (
                    [new Rule([16], ["6011", "644", "645", "646", "647", "648", "649", "65"])]
                    , "Discover"
                )
            )
        );

        CreditCardData.push(
            new BrandData(CardIssuer.DinersClub, new BrandInfo
                (
                    [new Rule([14, 16], ["300", "301", "302", "303", "304", "305", "3095", "36", "38"])]
                    , "Diners Club"
                )
            )
        );

        CreditCardData.push(
            new BrandData(CardIssuer.JCB, new BrandInfo
                (
                    [
                        new Rule([15, 16], ["3528", "3529", "353", "354", "355", "356", "357", "358"]),
                        new Rule([15], ["1800", "2131"]),
                        new Rule([19], ["1800", "357266"])
                    ]
                    , "JCB"
                )
            )
        );

        CreditCardData.push(
            new BrandData(CardIssuer.Laser, new BrandInfo
                (
                    [
                        new Rule([16, 17, 18, 19], ["6304"])
                    ]
                    , "Laser"
                )
            )
        );

        CreditCardData.push(
            new BrandData(CardIssuer.Switch, new BrandInfo
                (
                    [
                        new Rule([16, 18, 19], ["633110", "633312", "633304", "633303", "633301", "633300"])
                    ]
                    , "Switch"
                )
            )
        );

        var maestroPrefixes = [];
        maestroPrefixes = maestroPrefixes.concat(generateRange(56, 58));
        maestroPrefixes = maestroPrefixes.concat(generateRange(500, 500));
        maestroPrefixes = maestroPrefixes.concat(generateRange(502, 509));
        maestroPrefixes = maestroPrefixes.concat(generateRange(602, 605));
        maestroPrefixes = maestroPrefixes.concat(generateRange(670, 679));
        maestroPrefixes = maestroPrefixes.concat(generateRange(5010, 5018));
        maestroPrefixes = maestroPrefixes.concat(generateRange(6000, 6060));
        maestroPrefixes = maestroPrefixes.concat(generateRange(6760, 6769));
        var maestroRules = [new Rule([12, 13, 14, 15, 16, 17, 18, 19], maestroPrefixes)];

        var maestro = new BrandInfo(maestroRules, "MasterCard");
        brandData = new BrandData(CardIssuer.Maestro, maestro);
        CreditCardData.push(brandData);

        CreditCardData.push(
            new BrandData(CardIssuer.ChinaUnionPay, new BrandInfo
                (
                    [
                        new Rule([16, 17, 18, 19], ["62"])
                    ]
                    , "China UnionPay"
                )
            )
        );

        CreditCardData.push(
            new BrandData(CardIssuer.Dankort, new BrandInfo
                (
                    [
                        new Rule([16], ["5019"])
                    ]
                    , "Dankort"
                )
            )
        );

        CreditCardData.push(
            new BrandData(CardIssuer.RuPay, new BrandInfo
                (
                    [
                        new Rule([16], ["6061",
                            "6062",
                            "6063",
                            "6064",
                            "6065",
                            "6066",
                            "6067",
                            "6068",
                            "6069",
                            "607",
                            "608"])
                    ]
                    , "RuPay"
                )
            )
        );

        CreditCardData.push(
            new BrandData(CardIssuer.Hipercard, new BrandInfo
                (
                    [
                        new Rule([19], ["384"])
                    ]
                    , "Hipercard"
                )
            )
        );

        CreditCardData.push(
            new BrandData(CardIssuer.Unknown, new BrandInfo
                (
                    [
                        new Rule([15], ["7", "80", "90"])
                    ]
                    , "Unknown"
                )
            )
        );
    }




    
}
;
_insideGraph.registerModule("framework", function () {
    _insideGraph.initModule("realtime");
    _insideGraph.initModule("front");
});;
