var pushWrap = {
    wrapObj: function (service) {
        for (var fn in service){
            if (service.hasOwnProperty(fn) && typeof(service[fn]) === 'function') pushWrap.safeWrap(service, fn);
        }
    },
    safeWrap: function(service, fn) {
        var pushFn = service[fn];
        service[fn] = function (a, b, c, d, e, f, g, h, i, j, k, l) {
            try { return pushFn.call(service, a, b, c, d, e, f, g, h, i, j, k, l); }
            catch (err) {
                pushWrap.report(err);
            }
        };
    },
    report: function(err){
        var opts = {
            event: 'webpush-error-generic',
            scope: 'Website',
            scopeId: "5d80f4599f82e900129c614a",
            l: encodeURIComponent(location.href),
            e: JSON.stringify(err, Object.getOwnPropertyNames(err))
        };

        var uri = 'event=' + opts.event
            + '&scope=' + opts.scope
            + '&scopeId=' + opts.scopeId
            + ((navigator && navigator.userAgent) ? '&ua=' + navigator.userAgent : '')
            + ((opts.l) ? "&l=" + opts.l : "")
            + ((opts.e) ? "&e=" + opts.e : "");

        if (typeof fetch === 'function')
            fetch('https://trc.pushnami.com/api/push/track', {
                method: 'POST',
                body: encodeURI(uri),
                mode: 'cors',
                redirect: 'follow',
                headers: new Headers({
                    'Accept': 'application/json, text/plain, */*',
                    'Content-Type': 'application/x-www-form-urlencoded',
                    'key': '5d80f4599f82e900129c614b'
                })
            });
    }
};

try {
    var pnFirebaseModuleInterfaceInstantiator = (function() {
    return function(rootConfiguration) {
        var moduleInterface = {
            getMessagingDeviceToken: function() { return Promise.resolve(null); },
        };

        if (rootConfiguration) {
            var loadingPromise = new Promise(function(resolve, reject) {
                var script = document.createElement('script');
                script.type = "text/javascript";
                script.src = rootConfiguration.moduleBundleUrl;
                document.getElementsByTagName("head")[0].appendChild(script);
                script.onerror = function() {
                    reject(new Error('Failed to load FCM module bundle'));
                };
                script.onload = function() {
                    window.pnFirebaseImpl.setConfiguration(rootConfiguration);
                    resolve();
                };
            });

            /*
               FIXME: If possible (due to compatibility reasons) we should use a Proxy so that any property access is passed
                      directly through to the window.pnFirebaseImpl script that is loaded.  This would allow us to NEVER need
                      to update this script to add to new functions.
                      https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy
            */
            moduleInterface.getMessagingDeviceToken = function(serviceWorkerRegistration) {
                return loadingPromise.then(function() {
                    return window.pnFirebaseImpl.getMessagingDeviceToken(serviceWorkerRegistration);
                });
            }
        }

        return moduleInterface;
    };
})();
;
    var pnFirebaseModuleInterface = pnFirebaseModuleInterfaceInstantiator(undefined);

    /* We will define the call to produce a socialpush opt-in now, and if the conditional below is truthy then it will
       get overwritten with the real thing.  We need to do this so that our script doesn't crash should the function be
       undefined at runtime. */
    var showFbChkOptIn = function() {};

    // start fbv2 

    // start osxSafari 

    // Only Target OSX Safari
    var isOSXSafari = ('safari' in window && 'pushNotification' in window.safari);

    if (isOSXSafari) {
        var safariScript = document.createElement("script");
        safariScript.type = "text/javascript";
        safariScript.src= "https://api.pushnami.com/scripts/v1/pushnami-apn/5d80f4599f82e900129c614b";
        document.getElementsByTagName("head")[0].appendChild(safariScript);
    }

    // End osxSafari 

    Pushnami = (function (window) {
        'use strict';

        // API Key for backend
        var key = "5d80f4599f82e900129c614b";
        var websiteId = "5d80f4599f82e900129c614a";
        var swPath = "/service-worker.js";

        var isOSXSafari = ('safari' in window && 'pushNotification' in window.safari);

        if ((!isOSXSafari && !navigator.serviceWorker) || !localStorage || (window.location.protocol !== 'https:' && Boolean(window.location.hostname !== 'localhost' && window.location.hostname !== '[::1]' && !window.location.hostname.match(/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/)))) {
            var o = {
                setVariables: function () {
                    return o
                },
                on: function () {
                    return o
                },
                fire: function () {
                    return o
                },
                convert: function () {
                    return o
                },
                update: function () {
                    return o
                },
                clear: function () {
                    return o
                },
                showOverlay: function () {
                    return o
                },
                prompt: function () {
                    return o
                },
                getPSID: function () {
                    return o
                },
                unsubscribe: function () {
                    return o
                }
            };

            if (window.location.protocol !== 'https:' && !(window.location.protocol === 'https:' || Boolean(window.location.hostname === 'localhost' || window.location.hostname === '[::1]' || window.location.hostname.match(/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/)))) {
                console.error("Pushnami - error not SSL");
                pushnamiTrack({
                    event: 'webpush-error-not-ssl',
                    scope: 'Website',
                    scopeId: websiteId,
                    l: encodeURIComponent(location.href)
                });
            }

            return o;
        }


        var vapidPublicKey = "BIAEs0K3jJs7wrqZgoTdaHnSDfxvAkKA02Iop1jXrpsps_Si3poVGJFxTXsGPkrwdxT1ZwwMMPdThfqBs5Dd0fk";
        var convertedVapidKey = vapidPublicKey && vapidPublicKey.length > 0 ? urlBase64ToUint8Array(vapidPublicKey) : undefined;

        // HELPERS
        // Read a page's GET URL variables and return them as an associative array.
        var getUrlParams = function () {
            // 

            var vars = {}, href = window.location.href.split('#')[0], hash;

            if (href.indexOf('?') > 0) {
                var hashes = href.slice(href.indexOf('?') + 1).split('&');
                for (var i = 0; i < hashes.length; i++) {
                    try {
                        hash = hashes[i].split('=');
                        if (hash && hash[0] && hash[1]) vars[hash[0]] = decodeURIComponent(hash[1]);
                    } catch (e) {
                        console.log('Failed to decode variable ' + e);
                    }
                }
            }

            var pushnamiVars = Pushnami.data;
            for (var key in pushnamiVars) {
                if (pushnamiVars.hasOwnProperty(key)) {
                    vars[key] = pushnamiVars[key];
                }
            }

            return vars;
        };

        function pushnamiTrack(details) {
            var ua = "0";

            var trackingBody = encodeURI('event=' + details.event + '&scope=' + details.scope + '&scopeId=' + details.scopeId + ((details.pstag) ? '&pstag=' + details.pstag : '') + ((ua === '1' && navigator && navigator.userAgent) ? '&ua=' + navigator.userAgent : '') + ((details.l) ? "&l=" + details.l : "") + ((details.e) ? "&e=" + details.e : ""));

            // TODO: Remove this hotfix to disable pstag overloading
            // 

            return fetch('https://trc.pushnami.com/api/push/track', {
                method: 'POST',
                body: trackingBody,
                mode: 'cors',
                redirect: 'follow',
                headers: new Headers({
                    'Accept': 'application/json, text/plain, */*',
                    'Content-Type': 'application/x-www-form-urlencoded',
                    'key': key
                })
            })
                .then(function (response) {
                    if (response.ok) {
                        console.log('Tracking OK', response);
                        return true;
                    } else {
                        console.error('Tracking error', response);
                        return false;
                    }
                })
                .catch(function (err) {
                    console.error(err);
                    return false;
                });
        }

        function urlBase64ToUint8Array(base64String) {
            // IE still doesn't support String.prototype.repeat
            var paddingLength = (4 - base64String.length % 4) % 4;
            var padding = '';
            for (var ji = 0; ji < paddingLength; ji++) padding += "=";
            var base64 = (base64String + padding)
                .replace(/\-/g, '+')
                .replace(/_/g, '/');

            var rawData = window.atob(base64);
            var outputArray = new Uint8Array(rawData.length);

            for (var i = 0; i < rawData.length; ++i) {
                outputArray[i] = rawData.charCodeAt(i);
            }
            return outputArray;
        }

        function detectOtherPush () {
            var vendorWindow = {
                upush: ['upushPermission', 'upushRequest'],
                accengage: ['AccengageWebSDKObject'],
                aimtell: ['aimtellDebugBox', '_aimtellVersion'],
                cleverpush: ['CleverPush'],
                foxpush: ['_foxpush'],
                frizbit: ['frizbit'],
                izooto: ['Izooto'],
                letreach: ['ltr'],
                letsocify: ['let_socify'],
                onesignal: ['OneSignal'],
                push_monkey: ['PushMonkey'],
                pushalert: ['PushAlertCo'],
                pushcrew: ['pushcrew'],
                pushe: ['PusheHttp'],
                pushflew: ['PushflewLibrary'],
                pushwoosh: ['Pushwoosh'],
                sendmsgs: ['sendMessageToSW'],
                shophero_io: ['SHOPHERO'],
                urban_airship:['UA'],
                wonderpush: ['WonderPush'],
                goroost: ['_roost']
            };
            var vendors = [];
            for (var k in vendorWindow) {
                if(!vendorWindow.hasOwnProperty(k)) continue;
                vendorWindow[k].forEach(function(_v) {
                    if (typeof window !==undefined && window[_v]) vendors.push(k);
                });
            }
            // Just considering one for now
            return vendors[0] || null;
        }

        function showPrompt(opts) {

            if ((getUrlParams()||{}).pnblock) {
                return;
            }

            // TODO: Remove hardcoding
            // Testing 2db19f42ae59126f34dd95b7c3485555
            // 

            if (localStorage.getItem("pushnamiSubscriptionBlock")) return Pushnami;
            Pushnami.fire('permissions-initializing');
            var isLocalhost = Boolean(window.location.hostname === 'localhost' || window.location.hostname === '[::1]' || window.location.hostname.match(/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/));
            if ('serviceWorker' in navigator && (window.location.protocol === 'https:' || isLocalhost)) {

                // start shopify 

                // start shopify 
                navigator.serviceWorker.register(swPath || '/service-worker.js').catch(function (error) {
                    console.error('Pushnami - error registering service-worker', error);
                    pushnamiTrack({
                        event: 'webpush-error-no-sw',
                        scope: 'Website',
                        scopeId: websiteId,
                        l: encodeURIComponent(location.href),
                        e: (error && error.message && error.message !== "Registration failed - permission denied") ? error.message : null
                    });
                });
                // End shopify 

                navigator.serviceWorker.ready.then(function (registration) {
                    console.log(JSON.stringify(registration));

                    if (detectOtherPush()) {
                        pushnamiTrack({
                            event: 'webpush-error-sw-conflict-detected',
                            scope: 'Website',
                            scopeId: websiteId,
                            l: encodeURIComponent(location.href),
                            e: null
                        });
                    }

                    var scriptUrl = registration && registration.active && registration.active.scriptURL || null;
                    // We have fired this function for the registration of a service worker that may not correspond to Pushnami
                    if (scriptUrl && !scriptUrl.indexOf(swPath || '/service-worker.js') === -1) {
                        pushnamiTrack({
                            event: 'webpush-error-unrecognized-sw',
                            scope: 'Website',
                            scopeId: websiteId,
                            l: encodeURIComponent(location.href),
                            e: null
                        });
                    }

                    var opts = {userVisibleOnly: true};
                    if (convertedVapidKey) opts.applicationServerKey = convertedVapidKey;
                    if (!registration || !registration.pushManager || !registration.pushManager.subscribe) return;

                    // Check the useragent and check if they are already subscribed as far as we can tell
                    var preemptSubscription = window && window.navigator && window.navigator.userAgent && /samsungbrowser/i.test(window.navigator.userAgent);

                    // start promptOncePerSession 

                    var createSubscriptionRequest = function() {
                        return pnFirebaseModuleInterface.getMessagingDeviceToken(registration)
                            .catch(function (err) {
                                pushnamiTrack({
                                    event: 'webpush-error-fcm-general',
                                    scope: 'Website',
                                    scopeId: websiteId,
                                    e: (err && err.message) ? err.message : null
                                });
                                // Allowing normal subscription without token
                                return Promise.resolve(null);
                            })
                            .then(function (deviceToken) {
                                var buildSubscriptionInfoPackage = function(sub) {
                                    return { sub: sub, token: deviceToken };
                                };
                                var createNewSubscription = function() {
                                    return registration.pushManager.subscribe(opts).then(buildSubscriptionInfoPackage);
                                };
                                if (preemptSubscription) {
                                    return registration.pushManager.getSubscription().then(function(sub) {
                                        return sub ? buildSubscriptionInfoPackage(sub) : createNewSubscription();
                                    });
                                }
                                return createNewSubscription();
                            });
                    };

                    var subscriptionRequest = createSubscriptionRequest();

                    subscriptionRequest.then(function (subscriptionInfoPackage) {
                        // console.log('endpoint:', JSON.stringify(subscriptionInfoPackage));
                        var sub = subscriptionInfoPackage && subscriptionInfoPackage.sub;
                        var token = subscriptionInfoPackage && subscriptionInfoPackage.token;
                        var data = {
                            sub: sub,
                            subscriberId: localStorage.getItem("pushnamiSubscriberId"),
                            urlParams: getUrlParams()
                        };
                        if (token) {
                            data.token = token;
                        }
                        if (websiteId) data.websiteId = websiteId;
                        if (Pushnami && Pushnami.psfp && Pushnami.psfp.data) {
                            data.psfp = Pushnami.psfp.data.toString();
                            localStorage.removeItem('pushnami-psp-status');
                        } else {
                            // Mark status as incomplete if it did not build in time
                            var psfpStatus = localStorage.getItem('pushnami-psp-status');
                            if (psfpStatus === 'pending') {
                                localStorage.setItem('pushnami-psp-status', 'incomplete');
                            }
                        }
                        if (Pushnami && Pushnami.psfpv2) data.psfpv2 = Pushnami.psfpv2;
                        var pkid = '';
                        var isCredentialV2 = pkid.startsWith("fcmV1:");
                        if (!token && isCredentialV2) {
                            pkid = '';
                        }
                        if (pkid) {
                            data.pkid = pkid;
                        }
                        return fetch('https://api.pushnami.com/api/push/subscribe', {
                            method: 'POST',
                            body: JSON.stringify(data),
                            mode: 'cors',
                            redirect: 'follow',
                            headers: new Headers({key: key})
                        })
                            .then(function (response) {
                                return response.json();
                            })
                            .then(function (data) {
                                var alreadySubscribed = (localStorage.getItem('pushnamiSubscriptionStatus') === "SUBSCRIBED");
                                localStorage.setItem("pushnamiSubscriberId", data.subscriberId);
                                localStorage.setItem("pushnamiSubscriptionStatus", "SUBSCRIBED");
                                Pushnami.fire('permissions-action-subscribed');
                                if (!alreadySubscribed) {
                                    Pushnami.fire('permissions-action-subscribed-new');
                                }
                                return data;
                            })

                            // start tbid 

                            .then(function (data) {

                                if (!window || !window.pushnamiStorage) return data;

                                return window.pushnamiStorage.onConnect()
                                    .then(function() {
                                        return window.pushnamiStorage.set('psfp:912d9bb34e32efdf34edc5e1d9fb1d55', data.subscriberId);
                                    })
                                    .then(function(res) {
                                        return data;
                                    })
                                    .catch(function(err) {
                                        pushWrap.report(err);
                                        return true;
                                    });

                            })
                            .catch(function (err) {
                                Pushnami.fire('permissions-failed');
                                pushnamiTrack({
                                    event: 'webpush-error-subscription',
                                    scope: 'Website',
                                    scopeId: websiteId,
                                    e: (err && err.message) ? err.message : null
                                });
                                console.error("Pushnami - Subscription Error", err);
                                return false;
                            });
                    }).catch(function (err) {
                        var notErrors = [
                            "Registration failed - permission denied",
                            "User denied permission to use the Push API.",
                            "Failed to register a ServiceWorker: The user denied permission to use Service Worker.",
                            "User denied permission to use the Push API"
                        ];
                        var notAnError = !!(err && err.message && notErrors.indexOf(err.message) > -1);

                        if (notAnError) {
                            Pushnami.fire('permissions-blocked-ignored');
                        } else {
                            Pushnami.fire('permissions-failed');
                        }
                        if (err.message && err.message === "Registration failed - missing applicationServerKey, and manifest empty or missing") {
                            var hasManifest = false;
                            if (document && document.head && document.head.childNodes)
                                document.head.childNodes.forEach(function (node) {
                                    if (node.rel === 'manifest') hasManifest = true;
                                });

                            if (hasManifest) {
                                console.error("Pushnami - error manifest not found");
                                pushnamiTrack({
                                    event: 'webpush-error-no-manifest',
                                    scope: 'Website',
                                    scopeId: websiteId,
                                    l: encodeURIComponent(location.href)
                                });
                            } else {
                                console.error("Pushnami - error manifest tag not found");
                                pushnamiTrack({
                                    event: 'webpush-error-no-manifest-tag',
                                    scope: 'Website',
                                    scopeId: websiteId,
                                    l: encodeURIComponent(location.href)
                                });
                            }
                        } else if (!notAnError) {
                            console.error("Pushnami - error ", err);
                            pushnamiTrack({
                                event: 'webpush-error-general',
                                scope: 'Website',
                                scopeId: websiteId,
                                e: (err && err.message) ? err.message : null
                            });
                        }
                        return false;
                    });
                }).catch(function (e) {
                    Pushnami.fire('permissions-failed');
                    console.error('Error during service worker registration:', e);
                });

            } else {
                Pushnami.fire('permissions-not-showing');
                if (window.location.protocol !== 'https:' && !isLocalhost) {
                    console.error("Pushnami - error not SSL");
                    pushnamiTrack({
                        event: 'webpush-error-not-ssl',
                        scope: 'Website',
                        scopeId: websiteId,
                        l: encodeURIComponent(location.href)
                    });
                }
            }


            if ('permissions' in navigator) {
                navigator.permissions.query({name: 'notifications'}).then(function (notificationPerm) {
                    // notificationPerm.state is one of 'granted', 'denied', or 'prompt'.
                    // At this point you can compare notificationPerm.state to a previously
                    // cached value, and also listen for changes while the page is open via
                    // the onchange handler.

                    Pushnami.state = notificationPerm.state;
                    Pushnami.fire('permissions-prompt-' + notificationPerm.state);
                    if (notificationPerm && notificationPerm.state && notificationPerm.state == 'prompt') {
                        var _params = getUrlParams(),
                            opts = {
                                event: 'webpush-ssl-optin-shown',
                                scope: 'Website',
                                scopeId: websiteId
                            };

                        if (_params && _params['pstag']) opts.pstag = _params['pstag'];
                        pushnamiTrack(opts);
                    }
                    // console.log('Webpush permission state is ', notificationPerm.state);

                    notificationPerm.onchange = function () {
                        Pushnami.state = this.state;
                        // Permissions have changed while the page is open.
                        // console.log('Webpush permission state has changed to ', this.state);
                        // Do something based on the current notificationPerm.state value.
                        if (this.state === "denied") Pushnami.fire('permissions-prompt-action-deny');
                        var pushnamiSubscriberId = localStorage.getItem("pushnamiSubscriberId");
                        if (this.state !== 'granted' && pushnamiSubscriberId) {
                            var data = {
                                state: this.state,
                                subscriberId: pushnamiSubscriberId
                            };

                            return fetch('https://api.pushnami.com/api/push/unsubscribe', {
                                method: 'POST',
                                body: JSON.stringify(data),
                                mode: 'cors',
                                redirect: 'follow',
                                headers: new Headers({key: key})
                            })
                                .then(function (response) {
                                    if (response.ok) {
                                        Pushnami.fire('permissions-action-unsubscribed');
                                        localStorage.setItem("pushnamiSubscriptionStatus", "UNSUBSCRIBED");
                                        return true;
                                    } else {
                                        console.error(err);
                                        return false;
                                    }
                                })
                                .catch(function (err) {
                                    console.error(err);
                                    return false;
                                });
                        }
                    };
                });
            } else {
                Pushnami.fire('permissions-not-compatible');
                var _params = getUrlParams(),
                    opts = {
                        event: 'webpush-ssl-optin-not-compatible',
                        scope: 'Website',
                        scopeId: websiteId
                    };

                if (_params && _params['pstag']) opts.pstag = _params['pstag'];
                pushnamiTrack(opts);
            }
        }


        var o = {
            data: {},
            state: null,
            callbacks: {},
            setVariables: function (vars) {
                for (var key in vars) {
                    if (vars.hasOwnProperty(key) && vars[key] !== "" && vars[key] != null) {
                        Pushnami.data[key] = vars[key];
                    }
                }

                // start peoplefinder check  end peoplefinder check

                return Pushnami;
            },
            on: function (event, cb) {
                if (typeof event === 'string') {
                    if (Pushnami.callbacks[event]) {
                        Pushnami.callbacks[event].push(cb);
                    } else {
                        Pushnami.callbacks[event] = [cb];
                    }
                } else if (Object.prototype.toString.call(event) === '[object Array]') {
                    event.forEach(function (e) {
                        Pushnami.on(e, cb);
                    });
                }
                return Pushnami;
            },
            testError: function(){throw 'testing error'},
            fire: function (event) {
                if (Pushnami.callbacks[event]) {
                    Pushnami.callbacks[event].forEach(function (cb) {
                        try {
                            cb();
                        } catch (e) {
                            console.error("Callback Error ", e);
                        }
                    });
                }
            },
            convert: function(campaign){

                if (!/^[a-z0-9]{24}$/.test(campaign)) return false;

                var opts = {
                    event: 'webpush-conversion',
                    scope: 'Campaign',
                    scopeId: campaign,
                    l: encodeURIComponent(location.href),
                };

                var uri = 'event=' + opts.event
                    + '&scope=' + opts.scope
                    + '&scopeId=' + opts.scopeId
                    + ((opts.l) ? "&l=" + opts.l : "")
                    + ((opts.e) ? "&e=" + opts.e : "");

                if (typeof fetch === 'function')
                    fetch('https://trc.pushnami.com/api/push/track', {
                        method: 'POST',
                        body: encodeURI(uri),
                        mode: 'cors',
                        redirect: 'follow',
                        headers: new Headers({
                            'Accept': 'application/json, text/plain, */*',
                            'Content-Type': 'application/x-www-form-urlencoded',
                            'key': '5d80f4599f82e900129c614b'
                        })
                    });
            },
            update: function (vars) {
                if (!vars) vars = {};
                var href = window.location.href.split('#')[0];
                // 
                var hash;
                vars = vars || {};

                for (var _key in vars) {
                    if (vars.hasOwnProperty(_key) && vars[_key] === "") delete vars[_key];
                }

                if (href.indexOf('?') > 0) {
                    var hashes = href.slice(href.indexOf('?') + 1).split('&');
                    for (var i = 0; i < hashes.length; i++) {
                        try {
                            hash = hashes[i].split('=');
                            var decodedHash = decodeURIComponent(hash[1]);
                            if (decodedHash && hash && hash[0] && !vars[hash[0]]) vars[hash[0]] = decodedHash;
                        } catch (e) {
                            console.log('Pushnami - Failed to decode variable ' + e);
                        }
                    }
                }

                var pushnamiVars = Pushnami.data;
                // 
                for (var key in pushnamiVars) {
                    if (pushnamiVars.hasOwnProperty(key)) {
                        var value = pushnamiVars[key];
                        if (value) vars[key] = value;
                    }
                }

                var psid = localStorage.getItem('pushnamiSubscriberId');
                Pushnami.setVariables(vars); // Set Variables Either Way
                if (!psid) return Pushnami; // Return if not subscribed

                // TODO: Remove hardcoding
                // Deactivates any utm_source 'rrm' subscribers
                // Testing 2db19f42ae59126f34dd95b7c3485555
                // 

                // start peoplefinder check  end peoplefinder check

                vars.svu = true;	// Set subscriber variable update key
                var data = {sub: {}, urlParams: vars, subscriberId: psid};


                if (!!localStorage.getItem("pushnamiSubscriptionBlock")) return Pushnami;
                if ("5d80f4599f82e900129c614a") data.websiteId = "5d80f4599f82e900129c614a";

                fetch('https://api.pushnami.com/api/push/subscribe', {
                    method: 'POST',
                    body: JSON.stringify(data),
                    mode: 'cors',
                    redirect: 'follow',
                    headers: new Headers({key: '5d80f4599f82e900129c614b'})
                })
                    .catch(function (err) {
                        console.error("Pushnami - Error updating subscriber: ", err);
                    });
                return Pushnami;
            },
            clear: function () {
                Pushnami.callbacks = {};
            },


            showTwoStep: {
                init: function(){
                    if (/chrome/i.test(window.navigator.userAgent) && /android/i.test(window.navigator.userAgent)){
                        if (!localStorage.getItem("pushnamiSubscriptionBlock") && !localStorage.getItem("pushnamiSubscriberId")) {
                            Pushnami.showOverlay();
                            var optInCss = document.createElement("link");
                            optInCss.href = "https://api.pushnami.com/scripts/v1/pushnami-two-step-styles/5d80f4599f82e900129c614b";
                            optInCss.type = "text/css";
                            optInCss.rel = "stylesheet";
                            optInCss.media = "screen,print";
                            document.getElementsByTagName("head")[0].appendChild(optInCss);

                            var script = document.createElement("script");
                            script.src = "https://api.pushnami.com/scripts/v1/pushnami-two-step/5d80f4599f82e900129c614b";
                            script.type = "text/javascript";
                            document.getElementsByTagName("head")[0].appendChild(script);
                        }
                    } else {
                        Pushnami.showOverlay();
                        Pushnami.prompt();
                    }
                },

                block: function() {
                    localStorage.setItem("pushnamiSubscriptionBlock", "BLOCKED");
                    var push_container = document.getElementById("push-container");
                    if (push_container) push_container.style.display = "none";
                },

                allow: function() {
                    var push_container = document.getElementById("push-container");
                    if (push_container) push_container.style.display = "none";
                    Pushnami.showOverlay();
                    Pushnami.prompt();
                }
            },
            showOverlay: function (opts) {
                var aggressiveOpts = opts && opts.aggressive;
                var override = aggressiveOpts && aggressiveOpts.enabled || false;
                var aggressive = "false";
                if (!localStorage.getItem("pushnamiSubscriptionBlock") && aggressive !== 'false') {
                    // Load Aggressive resources
                    var aggressiveTitle = "";
                    var aggressiveMessage = "";
                    if (aggressiveTitle) Pushnami.aggressiveTitle = override && aggressiveOpts && aggressiveOpts.title || aggressiveTitle;
                    if (aggressiveMessage) Pushnami.aggressiveMessage = override && aggressiveOpts && aggressiveOpts.message || aggressiveMessage;

                    var optInCss = document.createElement("link");
                    optInCss.href = "https://cdn.pushnami.com/css/opt-in/opt-in.css";
                    optInCss.type = "text/css";
                    optInCss.rel = "stylesheet";
                    optInCss.media = "screen,print";
                    document.getElementsByTagName("head")[0].appendChild(optInCss);


                    var script = document.createElement("script");
                    script.src = "https://cdn.pushnami.com/js/opt-in/opt-in.js";
                    script.type = "text/javascript";
                    document.getElementsByTagName("head")[0].appendChild(script);
                }
                return Pushnami;
            },
            prompt: function (opts) {
                var show = function (opts) {
                    var cb = showPrompt.bind(showPrompt, opts || {});

                    // TODO: Remove hardcoding
                    // Prevents reactivation when the permission is already granted
                    // Testing 2db19f42ae59126f34dd95b7c3485555
                    // 

                    // start multi 

                    if (opts) {
                        if (opts.onClick && opts.delay) {
                            document.getElementById(opts.onClick).onclick = function () {
                                setTimeout(cb, opts.delay)
                            };
                        } else if (opts.onClick) {
                            document.getElementById(opts.onClick).onclick = cb;
                        } else if (opts.delay) {
                            setTimeout(cb, opts.delay)
                        } else {
                            cb()
                        }
                    } else {
                        cb();
                    }
                };

                // Start hide prompt override 

                // Start prevent duplicate override 
                // Start (else) prevent duplicate override 
                var shouldPreventDuplicates = opts && opts.preventDuplicate && Pushnami && Pushnami.psfp && Pushnami.psfp.done;
                // 

                if (shouldPreventDuplicates) {
                    // 5S timeout

                    Promise.race([
                        Pushnami.psfp.done,
                        new Promise(function(res, rej) {
                            window.setTimeout(function () {
                                res(true);
                            }, 5000);
                        })
                    ]).then(function(res){
                        if (res) return show(opts);

                        // Hide the opt-in (preventDuplicate)
                        return pushnamiTrack({
                            event: 'webpush-prevent-duplicate',
                            scope: 'Website',
                            scopeId: '5d80f4599f82e900129c614a',
                            l: encodeURIComponent(document.documentURI)
                        });
                    }).catch(function(err){
                        show(opts);
                        pushWrap.report(err);
                    });
                } else {
                    show(opts);
                }
                return Pushnami;
            },
            getPSID: function () {
                return localStorage.getItem("pushnamiSubscriberId")
            },
            unsubscribe: function (opts) {
                opts = opts || {};
                var isOSXSafari = ('safari' in window && 'pushNotification' in window.safari);

                if (isOSXSafari) {
                    Pushnami.unsubscribeAPN();
                } else {
                    Pushnami.unsubscribeSW(opts);
                }
            },
            unsubscribeAPN: function() {
                var apnAPIVersion = "v2";
                var websitePushID = "web.es.ahorroseguros";
                var deviceToken = window.safari.pushNotification.permission(websitePushID).deviceToken;

                var baseUrl = "https://api.pushnami.com";
                var endpoint = '/api/apn/' + apnAPIVersion + '/devices/' + deviceToken + '/registrations/' + websitePushID;

                fetch(baseUrl + endpoint, {
                    method: 'DELETE',
                    mode: 'cors',
                    redirect: 'follow',
                    // headers: new Headers({key: "5d80f4599f82e900129c614b"})
                })
                .then(function (response) {
                    if (response.ok) {
                        localStorage.setItem("pushnamiSubscriptionStatus", "UNSUBSCRIBED");
                        localStorage.setItem("pushnamiSubscriptionBlock", "BLOCKED");
                        console.log('Pushnami - unsubscribed');
                        return true;
                    } else {
                        console.error("Pushnami - unsubscribe [api] error: ", err);
                        return false;
                    }
                })
                .catch(function (err) {
                    console.error("Pushnami - unsubscribe [fetch] error: ", err);
                    return false;
                });
            },
            unsubscribeSW: function(opts) {
                var pushnamiSubscriberId = localStorage.getItem("pushnamiSubscriberId");
                if (navigator && navigator.serviceWorker && pushnamiSubscriberId) {
                    navigator.serviceWorker.ready.then(function (reg) {
                        return reg.pushManager.getSubscription().then(function (subscription) {
                            return subscription.unsubscribe().then(function (successful) {
                                var baseUrl = "https://api.pushnami.com";
                                var endpoint = '/api/push/unsubscribe';
                                return fetch(baseUrl + endpoint, {
                                    method: 'POST',
                                    body: JSON.stringify({
                                        state: "blocked",
                                        subscriberId: pushnamiSubscriberId,
                                        forget: opts.forget || false
                                    }),
                                    mode: 'cors',
                                    redirect: 'follow',
                                    headers: new Headers({key: "5d80f4599f82e900129c614b"})
                                })
                                    .then(function (response) {
                                        if (response.ok) {
                                            localStorage.setItem("pushnamiSubscriptionStatus", "UNSUBSCRIBED");
                                            localStorage.setItem("pushnamiSubscriptionBlock", "BLOCKED");
                                            return true;
                                        } else {
                                            console.error("Unsubscribe [api] error: ", err);
                                            return false;
                                        }
                                    })
                                    .catch(function (err) {
                                        console.error("Unsubscribe [fetch] error: ", err);
                                        return false;
                                    });

                            }).catch(function (err) {
                                console.error("Unsubscribe [sub] error: ", err);
                                return false;
                            })
                        })
                    });
                }
                return Pushnami;
            }
        };

        // start psfp 

        var psfp = {
            data: null,
            _checkPromise: null,
            build: function () {
                var pspStatus = localStorage.getItem('pushnami-psp-status');
                if (pspStatus !== 'incomplete') {
                    localStorage.setItem('pushnami-psp-status', 'pending');
                }

                // zendesk/cross-storage (client)
                // https://github.com/zendesk/cross-storage/blob/master/dist/client.min.js
                !function(e){function t(e,r){r=r||{},this._id=t._generateUUID(),this._promise=r.promise||Promise,this._frameId=r.frameId||"CrossStorageClient-"+this._id,this._origin=t._getOrigin(e),this._requests={},this._connected=!1,this._closed=!1,this._count=0,this._timeout=r.timeout||5e3,this._listener=null,this._installListener();var o;r.frameId&&(o=document.getElementById(r.frameId)),o&&this._poll(),o=o||this._createFrame(e),this._hub=o.contentWindow}t.frameStyle={display:"none",position:"absolute",top:"-999px",left:"-999px"},t._getOrigin=function(e){var t,r,o;return t=document.createElement("a"),t.href=e,t.host||(t=window.location),r=t.protocol&&":"!==t.protocol?t.protocol:window.location.protocol,o=r+"//"+t.host,o=o.replace(/:80$|:443$/,"")},t._generateUUID=function(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(e){var t=16*Math.random()|0,r="x"==e?t:3&t|8;return r.toString(16)})},t.prototype.onConnect=function(){var e=this;return this._connected?this._promise.resolve():this._closed?this._promise.reject(new Error("CrossStorageClient has closed")):(this._requests.connect||(this._requests.connect=[]),new this._promise(function(t,r){var o=setTimeout(function(){r(new Error("CrossStorageClient could not connect"))},e._timeout);e._requests.connect.push(function(e){return clearTimeout(o),e?r(e):(t(),void 0)})}))},t.prototype.set=function(e,t){return this._request("set",{key:e,value:t})},t.prototype.get=function(){var e=Array.prototype.slice.call(arguments);return this._request("get",{keys:e})},t.prototype.del=function(){var e=Array.prototype.slice.call(arguments);return this._request("del",{keys:e})},t.prototype.clear=function(){return this._request("clear")},t.prototype.getKeys=function(){return this._request("getKeys")},t.prototype.close=function(){var e=document.getElementById(this._frameId);e&&e.parentNode.removeChild(e),window.removeEventListener?window.removeEventListener("message",this._listener,!1):window.detachEvent("onmessage",this._listener),this._connected=!1,this._closed=!0},t.prototype._installListener=function(){var e=this;this._listener=function(t){var r,o,n,s;if(!e._closed&&t.data&&"string"==typeof t.data&&(o="null"===t.origin?"file://":t.origin,o===e._origin))if("cross-storage:unavailable"!==t.data){if(-1!==t.data.indexOf("cross-storage:")&&!e._connected){if(e._connected=!0,!e._requests.connect)return;for(r=0;r<e._requests.connect.length;r++)e._requests.connect[r](n);delete e._requests.connect}if("cross-storage:ready"!==t.data){try{s=JSON.parse(t.data)}catch(i){return}s.id&&e._requests[s.id]&&e._requests[s.id](s.error,s.result)}}else{if(e._closed||e.close(),!e._requests.connect)return;for(n=new Error("Closing client. Could not access localStorage in hub."),r=0;r<e._requests.connect.length;r++)e._requests.connect[r](n)}},window.addEventListener?window.addEventListener("message",this._listener,!1):window.attachEvent("onmessage",this._listener)},t.prototype._poll=function(){var e,t,r;e=this,r="file://"===e._origin?"*":e._origin,t=setInterval(function(){return e._connected?clearInterval(t):(e._hub&&e._hub.postMessage("cross-storage:poll",r),void 0)},1e3)},t.prototype._createFrame=function(e){var r,o;r=window.document.createElement("iframe"),r.id=this._frameId;for(o in t.frameStyle)t.frameStyle.hasOwnProperty(o)&&(r.style[o]=t.frameStyle[o]);return document.body.appendChild(r),r.src=e,r},t.prototype._request=function(e,t){var r,o;return this._closed?this._promise.reject(new Error("CrossStorageClient has closed")):(o=this,o._count++,r={id:this._id+":"+o._count,method:"cross-storage:"+e,params:t},new this._promise(function(e,t){var n,s,i;n=setTimeout(function(){o._requests[r.id]&&(delete o._requests[r.id],t(new Error("Timeout: could not perform "+r.method)))},o._timeout),o._requests[r.id]=function(s,i){return clearTimeout(n),delete o._requests[r.id],s?t(new Error(s)):(e(i),void 0)},Array.prototype.toJSON&&(s=Array.prototype.toJSON,Array.prototype.toJSON=null),i="file://"===o._origin?"*":o._origin,o._hub.postMessage(JSON.stringify(r),i),s&&(Array.prototype.toJSON=s)}))},e.CrossStorageClient=t}(window);

                window.pushnamiStorage = new window.CrossStorageClient('https://api.pushnami.com/scripts/v1/hub');

                // node-uuid
                // https://github.com/broofa/node-uuid
                !function(e){window.uuid=e()}(function(){return function e(n,r,o){function t(u,f){if(!r[u]){if(!n[u]){var a="function"==typeof require&&require;if(!f&&a)return a(u,!0);if(i)return i(u,!0);var s=new Error("Cannot find module '"+u+"'");throw s.code="MODULE_NOT_FOUND",s}var d=r[u]={exports:{}};n[u][0].call(d.exports,function(e){var r=n[u][1][e];return t(r?r:e)},d,d.exports,e,n,r,o)}return r[u].exports}for(var i="function"==typeof require&&require,u=0;u<o.length;u++)t(o[u]);return t}({1:[function(e,n,r){var o=e("./v1"),t=e("./v4"),i=t;i.v1=o,i.v4=t,n.exports=i},{"./v1":4,"./v4":5}],2:[function(e,n,r){function o(e,n){var r=n||0,o=t;return[o[e[r++]],o[e[r++]],o[e[r++]],o[e[r++]],"-",o[e[r++]],o[e[r++]],"-",o[e[r++]],o[e[r++]],"-",o[e[r++]],o[e[r++]],"-",o[e[r++]],o[e[r++]],o[e[r++]],o[e[r++]],o[e[r++]],o[e[r++]]].join("")}for(var t=[],i=0;i<256;++i)t[i]=(i+256).toString(16).substr(1);n.exports=o},{}],3:[function(e,n,r){var o="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||"undefined"!=typeof msCrypto&&"function"==typeof window.msCrypto.getRandomValues&&msCrypto.getRandomValues.bind(msCrypto);if(o){var t=new Uint8Array(16);n.exports=function(){return o(t),t}}else{var i=new Array(16);n.exports=function(){for(var e,n=0;n<16;n++)0===(3&n)&&(e=4294967296*Math.random()),i[n]=e>>>((3&n)<<3)&255;return i}}},{}],4:[function(e,n,r){function o(e,n,r){var o=n&&r||0,d=n||[];e=e||{};var l=e.node||t,c=void 0!==e.clockseq?e.clockseq:i;if(null==l||null==c){var v=u();null==l&&(l=t=[1|v[0],v[1],v[2],v[3],v[4],v[5]]),null==c&&(c=i=16383&(v[6]<<8|v[7]))}var p=void 0!==e.msecs?e.msecs:(new Date).getTime(),y=void 0!==e.nsecs?e.nsecs:s+1,b=p-a+(y-s)/1e4;if(b<0&&void 0===e.clockseq&&(c=c+1&16383),(b<0||p>a)&&void 0===e.nsecs&&(y=0),y>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");a=p,s=y,i=c,p+=122192928e5;var m=(1e4*(268435455&p)+y)%4294967296;d[o++]=m>>>24&255,d[o++]=m>>>16&255,d[o++]=m>>>8&255,d[o++]=255&m;var g=p/4294967296*1e4&268435455;d[o++]=g>>>8&255,d[o++]=255&g,d[o++]=g>>>24&15|16,d[o++]=g>>>16&255,d[o++]=c>>>8|128,d[o++]=255&c;for(var w=0;w<6;++w)d[o+w]=l[w];return n?n:f(d)}var t,i,u=e("./lib/rng"),f=e("./lib/bytesToUuid"),a=0,s=0;n.exports=o},{"./lib/bytesToUuid":2,"./lib/rng":3}],5:[function(e,n,r){function o(e,n,r){var o=n&&r||0;"string"==typeof e&&(n="binary"===e?new Array(16):null,e=null),e=e||{};var u=e.random||(e.rng||t)();if(u[6]=15&u[6]|64,u[8]=63&u[8]|128,n)for(var f=0;f<16;++f)n[o+f]=u[f];return n||i(u)}var t=e("./lib/rng"),i=e("./lib/bytesToUuid");n.exports=o},{"./lib/bytesToUuid":2,"./lib/rng":3}]},{},[1])(1)});

                var uuid_v4 = uuid.v4();

                // Grab PSFP or UUID (if it doesn't exist)
                var getUUID = window.pushnamiStorage.onConnect()
                    .then(function() {
                        // Retrieve keys
                        //   psfp: 912d9bb34e32efdf34edc5e1d9fb1d55 - psid for account-level subscriber
                        //   pdid: uuid

                        return window.pushnamiStorage.get('psfp:912d9bb34e32efdf34edc5e1d9fb1d55', 'pdid');
                    })
                    .then(function(res) {
                        // Process storage contents

                        var hidePrompt = res && res[0];
                        var pdid = res && res[1];

                        return {key: pdid, hidePrompt: !!hidePrompt}
                    })
                    .then(function(res) {
                        // Set the uuid for new subscribers

                        if (res.key) return res;
                        return window.pushnamiStorage.set('pdid', uuid_v4)
                            .then(function(){
                                res.key = uuid_v4;
                                return res;
                            });
                    })
                    .catch(function(err) {
                        pushWrap.report(err);
                        return null;
                    });

                // start psfpv2 

                if (typeof fetch !== 'function') return;

                getUUID.then(function(res) {
                    if (!res || !res.key) return null;

                    var tblaRegex = document.cookie && /trc_cookie_storage=taboola%2520global%253Auser-id%3D(.*?)(;|$)/.exec(document.cookie);
                    var tbla = tblaRegex && tblaRegex[1] || '';
                    var pspBody = 'psp='+res.key+'&tbla='+tbla;

                    // Check if we can report psid to maximize psfp coverage
                    var psfpStatus = localStorage.getItem('pushnami-psp-status');
                    if (psfpStatus === 'incomplete') {
                        var psid = localStorage.getItem("pushnamiSubscriberId");
                        if (psid) {
                            pspBody += '&psid='+psid;

                            // Remove the key for now
                            localStorage.removeItem('pushnami-psp-status');
                        }
                    }

                    // start tbid-visit 

                    return fetch('https://psp.pushnami.com/api/psp', {
                        method: 'POST',
                        body: encodeURI(pspBody),
                        mode: 'cors',
                        redirect: 'follow',
                        headers: new Headers({
                            'Accept': 'application/json, text/plain, */*',
                            'Content-Type': 'application/x-www-form-urlencoded',
                            'key': '5d80f4599f82e900129c614b'
                        })
                    }).then(function(){
                        return res
                    }).catch(function(err){
                        pushWrap.report({ msg: "PSP Error", err: err && err.toString() });
                    });
                });

                // End psfpv2 

                return getUUID.catch(function(err) {
                    pushWrap.report(err);
                    return null;
                });



            },
            check: function () {
                if (psfp._checkPromise) return psfp._checkPromise;
                psfp._checkPromise = psfp.build()
                    .then(function(res){
                        if (!res) return true;
                        var key = res.key;
                        var hidePrompt = res.hidePrompt;
                        psfp.data = key;
                        return !hidePrompt;
                    });
                return psfp._checkPromise;
            },
            done: null
        };

        // Start Running Immediately
        psfp.done = (function(){
            // Wait for document to be loaded
            if (document.readyState === "complete"){
                return psfp.check();
            } else {
                return (new Promise(function(resolve, reject){
                    window.addEventListener('load', resolve);

                })).then(psfp.check)
            }
        })();
        o.psfp = psfp;
        // End PSFP 
        pushWrap.wrapObj(o);
        return o;
    })(window);

    //Try and show the socialpush opt-in depending on the events that occur with the webpush opt-in
    Pushnami.on([
        'permissions-not-compatible',
        'permissions-not-showing'
    ], function () {
        showFbChkOptIn('webpush-optin-cannot-be-shown');
    });
    Pushnami.on('permissions-failed', function() {
        showFbChkOptIn('webpush-optin-failed');
    });
    Pushnami.on([
        'permissions-action-subscribed',
        'permissions-action-apn-subscribed'
    ], function () {
        showFbChkOptIn('webpush-optin-subscribed');
    });
} catch (err) {
    if (typeof Pushnami === "undefined"){
        var o = {setVariables: function () {return o},convert: function () {return o},on: function () {return o},fire: function () {return o},update: function () {return o},clear: function () {return o},showOverlay: function () {return o},prompt: function () {return o},getPSID: function () {return o},unsubscribe: function () {return o}};
        Pushnami = o;
    }
    pushWrap.report(err);
}
