var pushPath = "/util/push-dt6";
var confPush = {
    siteLang: false,    
    serverUrl: "https://instant-popup-live-chat.com/js.aspx", // URI to push-external
    serverPathExternal: "/util/push-external-dt6/?",

    confirmImgUrl: pushPath + "/images/icon_default.png",
    confirmTitle: "You Win!",
    confirmMessage: "Claim your bonus",
    confirmBtnClose: "Cancel",
    confirmBtnAllow: "Agree",
    confirmPositionX: "left",
    confirmStyle: "",
    extNameAge: "",
    extImageUrl: "",
    extTpl: 1,

    iconType: 1,
    iconImgUrl: pushPath + "/images/icon_default.png",
    iconPositionX: "right",
    iconPositionY: "bottom",
    iconNoMargin: false,
    iconNoShadow: false,
    iconColor: "yellow",
    iconFormType: "circle",
    iconSize: "",
    iconAutoOpen: true,
    iconTitle: "Johny Cash Now",
    iconSubTitle: "Hit Jackpot",
    iconUserImgUrl: pushPath + "/images/icon_default.png",
    iconTitleOnHover: false,
    iconBtnTextOn: true,
    iconBtnText: "Spin Now",
    iconBtnOpenWindow: false, // open popup or immediately new window
    iconBtnShowDelay: 0, // time delay in sec to show icon
    iconBtnTextDelay: 5, // time delay in sec to show tooltip text
    iconBtnTextDelayRepeat: 0, // time interval to show tooltip multiple times
    iconOpenTime: 4000,
    onlyLangs: "",
};
var confPushTrls = {
    source: {
        iconTitle: "Johny Cash Now",
        iconSubTitle: "Hit Jackpot",
        iconBtnText: "Spin Now",
    },
    en: {
        iconTitle: "Johny Cash Now",
        iconSubTitle: "Hit Jackpot",
        iconBtnText: "Spin Now",
    },
    de: {
        iconTitle: "Neue Nachricht"
    },
    ru: {
        iconTitle: "новое сообщение"
    },
    cs: {
        iconTitle: "nová zpráva"
    },
    da: {
        iconTitle: "Ny besked"
    },
    es: {
        iconTitle: "Mensaje nuevo"
    },
    fi: {
        iconTitle: "Uusi viesti"
    },
    fr: {
        iconTitle: "new message"
    },
    it: {
        iconTitle: "nuovo messaggio"
    },
    nl: {
        iconTitle: "nieuw bericht"
    },
    no: {
        iconTitle: "Ny melding"
    },
    pl: {
        iconTitle: "nowa wiadomość"
    },
    pt: {
        iconTitle: "nova mensagem"
    },
    sv: {
        iconTitle: "nytt meddelande"
    },
    tr: {
        iconTitle: "yeni Mesaj"
    },
    el: {
        iconTitle: "νέο μήνυμα"
    },
    hu: {
        iconTitle: "új üzenet"
    },
    sl: {
        iconTitle: "novo sporočilo"
    },
    sk: {
        iconTitle: "nová správa"
    },
    hr: {
        iconTitle: "nova poruka"
    },
    he: {
        iconTitle: "הודעה חדשה"
    },
    ro: {
        iconTitle: "mesaj nou"
    },
};

var subscribeMethod = optPushMethod ? optPushMethod : "icon_button_ext_subscribe";
var subscribeSite = optPushSite ? optPushSite : "unknown";
var vertical = "prelandIGaming";
var isShowedPushCookie = "push_showed_" + subscribeMethod;
var forceLang = getParameterByName("lang");
var detectedLang = forceLang && forceLang.length ? forceLang : detect_language();

if (typeof optPush !== "undefined") {
    $.extend(true, confPush, optPush);
}

if (typeof optPushTrls !== "undefined" && !optPush.siteLang) {
    var availableLang = translation_available(optPushTrls);
    $.extend(true, confPush, optPushTrls[availableLang]);
} else if (typeof optPushTrls === "undefined" && !optPush.siteLang) {
    var availableLang = translation_available(confPushTrls);
    $.extend(true, confPush, confPushTrls[availableLang]);
} else {
    var availableLang = translation_available(confPushTrls, optPush.siteLang);
    $.extend(true, confPush, confPushTrls[availableLang]);
}

function translation_available(objTrls, lang) {
    var curLang = lang ? lang : detectedLang;
    if (objTrls[curLang]) {
        return curLang;
    } else {
        console.log("translation not Found: " + curLang);
        return "source";
    }
}

if(confPush.onlyLangs && confPush.onlyLangs.length && confPush.onlyLangs.indexOf(detectedLang) == -1) {
    detectedLang = 'en';
}

if (confPush.siteLang && confPush.siteLang.length) {
    detectedLang = confPush.siteLang;
}

document.head.innerHTML += '<link rel="stylesheet" href="'+ pushPath +'/style.css?v=1.1" type="text/css" />';

var pushConfirmHtml = '<div id="lp-confirm" class="lp-confirm ' + confPush.confirmStyle + ' ' + confPush.confirmPositionX + '"><div class="lp-confirm-wrap"><div class="lp-confirm-logo"><img src="' + confPush.confirmImgUrl + '" alt="" class="lp-confirm-img"></div><div class="lp-confirm-content"><div class="lp-confirm-title">' + confPush.confirmTitle + '</div><p class="lp-confirm-text">' + confPush.confirmMessage + '</p></div><div class="lp-confirm-btns"><span id="lp-confirm-close" class="lp-confirm-btn lp-confirm-btn-close">' + confPush.confirmBtnClose + '</span><span id="lp-confirm-subscribe" class="lp-confirm-btn lp-confirm-btn-allow">' + confPush.confirmBtnAllow + '</span></div></div></div>';

var pushLabelTextClass = confPush.iconBtnTextOn ? "lp-label-text-on " : "";
var pushLabelTitleClass = confPush.iconTitleOnHover ? "lp-label-push-open " : "";
var pushLabelMarginClass = confPush.iconNoMargin ? "lp-label-no-margin " : "";
var pushLabelShadowClass = confPush.iconNoShadow ? "lp-label-no-shadow " : "";
var pushLabelHtml = '<div id="lp-label" class="lp-label lp-label-type-' + confPush.iconType + ' ' + pushLabelTextClass + pushLabelTitleClass + confPush.iconColor + ' ' + confPush.iconPositionX + ' ' + confPush.iconPositionY + ' ' + confPush.iconFormType + ' ' + confPush.iconSize + ' ' + pushLabelMarginClass + pushLabelShadowClass + '"><div class="lp-label-inner"><div class="lp-label-content-left"><img src="' + confPush.iconImgUrl + '" alt="" class="lp-wheel-image"></div><div class="lp-label-content-right"><div class="lp-label-content-wrap"><div class="lp-label-text">'+ confPush.iconTitle +'</div><div class="lp-label-subtitle">'+ confPush.iconSubTitle +'</div></div><div class="lp-label-btn"><span>'+ confPush.iconBtnText +'</span></div></div></div></div>';

function openChildWindow(width, height) {
    var url = confPush.serverUrl + "?encodedPath=" + btoa(confPush.serverPathExternal) + "&ext=1&" + getAllParams();
    var l, d = void 0 !== window.screenLeft ? window.screenLeft : screen.left,
        h = void 0 !== window.screenTop ? window.screenTop : screen.top,
        f = window.innerWidth ? window.innerWidth : document.documentElement.clientWidth ? document.documentElement.clientWidth : screen.width,
        g = window.innerHeight ? window.innerHeight : document.documentElement.clientHeight ? document.documentElement.clientHeight : screen.height,
        left = f / 2 - width / 2 + d, top = g / 2 - height / 2 + h;
    var a = window.open(url, "_blank", "scrollbars=yes, width=" + width + ", height=" + height + ", top=" + top + ", left=" + left);
    a.focus();
}

function showPushConfirm() {
    if (!getCookie(isShowedPushCookie)) {
        var popup = $(pushConfirmHtml);
        popup.appendTo('body');

        $(document).on("click", "#lp-confirm-close", function () {
            if (!confPush.confirmStyle) {
                popup.remove();
            } else {
                popup.addClass('removing');

                setTimeout(function () {
                    popup.remove();
                }, 500);
            }
        });

        $(document).on("click", "#lp-confirm-subscribe", function () {
            if (!confPush.confirmStyle) {
                popup.remove();
                subscribe();
            } else {
                popup.addClass('removing');

                setTimeout(function () {
                    popup.remove();
                    subscribe();
                }, 500);
            }
        });
    } else {
        console.log("Notification already showed.");
    }
}

function showPushLabel() {
    if (!getCookie(isShowedPushCookie)) {
        var labelId = "#lp-label";
        $("body").append(pushLabelHtml).addClass('has-push');

        var showHideTooltip = function() {
            var isMobile = /Android|webOS|iPhone|iPad|iPod|pocket|psp|kindle|avantgo|blazer|midori|Tablet|Palm|maemo|plucker|phone|BlackBerry|symbian|IEMobile|mobile|ZuneWP7|Windows Phone|Opera Mini/i.test(navigator.userAgent);
            var screenWidth = $(window).width();

            if ($(labelId).length === 0)
                clearInterval(repeat);

            setTimeout(function(){
                $(labelId).addClass("lp-opened");
                setTimeout(function(){
                    $(labelId).removeClass("lp-opened");
                }, confPush.iconOpenTime);
            }, confPush.iconBtnTextDelay * 1000);

            if(isMobile) {
                $('#lp-label .lp-label-inner').addClass('is-Mobile-push');
            }
        };

        if (confPush.iconTitleOnHover) {
            if (confPush.iconBtnTextDelayRepeat && confPush.iconBtnTextDelayRepeat > 0 && confPush.iconBtnTextDelayRepeat >= confPush.iconBtnTextDelay) {
                showHideTooltip();

                var repeat = setInterval(function(){
                    showHideTooltip();
                }, confPush.iconBtnTextDelayRepeat * 1000 + confPush.iconOpenTime);
            } else {
                showHideTooltip();
            }
        }

        $(document).on("click", labelId, function () {
            if (confPush.iconBtnOpenWindow) {
                showPushConfirm();
            } else {
                subscribe();
            }
            $(this).remove();
        });
    } else {
        console.log("Notification already showed.");
    }
}

function subscribeUnder() {
    $('a[href="/web/"]').on("click", function(e){
        e.preventDefault();
        e.stopPropagation();

        var url = $(this).attr("href");

        showPushConfirm();

        setTimeout(function() {
             var a = window.open(url, "_blank");
            a.focus();
        }, 1000);
    });
}

window.addEventListener("load", function(){
    if ('Notification' in window) {
        runSubscribeMethod(subscribeMethod);
    }
});

if (!String.prototype.startsWith) {
    Object.defineProperty(String.prototype, 'startsWith', {
        enumerable: false,
        configurable: false,
        writable: false,
        value: function (searchString, position) {
            position = position || 0;
            return this.indexOf(searchString, position) === position;
        }
    });
}

function runSubscribeMethod(subscribeMethod) {
    if (subscribeMethod.startsWith("chat_popup_ext_subscribe")) {
        setTimeout(function() {
            showPushConfirm();
        }, 2000);
    } else if (subscribeMethod === "icon_button_ext_subscribe") {
        setTimeout(function() {
            showPushLabel();
        }, confPush.iconBtnShowDelay * 1000);
    } else if (subscribeMethod === "icon_button_tooltip_ext_subscribe") {
        setTimeout(function() {
            showPushLabel();
        }, confPush.iconBtnShowDelay * 1000);
    } else if (subscribeMethod === "chat_popup_ext_under_subscribe") {
        subscribeUnder();
    }
}

function subscribe() {
    openChildWindow(500, 600);
    setCookie(isShowedPushCookie, "true", 1);
}

function setCookie(name, value, i) {
    if (!i) i = 365;
    var d = new Date;
    d.setTime(d.getTime() + 24 * parseInt(i) * 3600);
    var expire = "expires=" + d.toUTCString();
    document.cookie = name + "=" + value + ";" + expire;
}

function getCookie(name) {
    for (var t = name + "=", n = document.cookie.split(";"), i = 0; i < n.length; i++) {
        for (var r = n[i]; " " === r.charAt(0);) r = r.substring(1);
        if (0 === r.indexOf(t)) return r.substring(t.length, r.length);
    }
    return !1;
}

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

function getAllParams() {
    var clientData = {
        affiliateId: getParameterByName("u"),
        site: window.location.href.split('?')[0] + subscribeSite,
        userAgent: navigator.userAgent,
        language: navigator.language || navigator.userLanguage,
        subscribeMethod: subscribeMethod,
        vertical: vertical,
        siteLang: detectedLang
    };

    if (confPush.extNameAge) {
        clientData.extNameAge = encodeURIComponent(confPush.extNameAge);
    }
    if (confPush.extImageUrl) {
        clientData.extImageUrl = confPush.extImageUrl;
    }
    if (confPush.extTpl) {
        clientData.extTpl = confPush.extTpl;
    }

    return $.param(clientData);
}

function detect_language() {
    var userLang = navigator.languages && navigator.languages[0] || navigator.language || navigator.userLanguage;
    if (userLang == "no" || userLang == "nb" || userLang == "nb-NO" || userLang == "nn-NO") {
        userLang = "no";
    } else if (userLang.length > 2) {
        userLang = userLang[0] + userLang[1];
    }
    return userLang;
}

jQuery(document).ready(function ($) {
    window.localStorage.setItem('subscribeMethod', subscribeMethod);
});