function ArkAbTestHelper() {

    var self = this;
    this.userExcludedCookieValue = "UserExcluded";
    this.gaCookieName = "_ga";

    this.RunAbTestIfAvailable = function() {
        if (typeof window.arkAbTestConfig === "object" && abTestConfigValid(window.arkAbTestConfig)) {
            var abTestCookieValue = window.ark_jQuery.cookie(window.arkAbTestConfig.AbTestCookieName);
            var variation;
            if (abTestCookieValue) {
                if (abTestCookieValue === self.userExcludedCookieValue) {
                    variation = getVariationByName(window.arkAbTestConfig.AbTestDefaultVariationName);
                    variation.AbTestVariationCookieValue = self.userExcludedCookieValue;
                } else {
                    variation = getVariationByName(abTestCookieValue);
                }
            } else {
                if (includeUserInAbTest()) {
                    variation = chooseVariation();
                } else {
                    variation = getVariationByName(window.arkAbTestConfig.AbTestDefaultVariationName);
                    variation.AbTestVariationCookieValue = self.userExcludedCookieValue;
                }
            }
            saveVariation(variation);
            showVariation(variation.AbTestVariationName);
            ark.triggerEvent("arkAbTestVariationReady", variation);
        }
    };

    function chooseVariation() {
        var variations = Object.keys(window.arkAbTestConfig.variations);
        for (var i = 0; i < variations.length; i++) {
            if (variations[i] === "Default") {
                variations.splice(i, 1);
            }
        }
        return window.arkAbTestConfig.variations[variations[variations.length * Math.random() << 0]];
    }

    function saveVariation(variation) {
        window.ark_jQuery.cookie(window.arkAbTestConfig.AbTestCookieName,
            variation.AbTestVariationCookieValue,
            { expires: 365, path: "/" });

        ark.addListener("arkGaReady", function () {
            window.ark_Ga.SetGlobalDimensions([
                { slot: window.arkAbTestConfig.AbTestCustomDimension, value: variation.AbTestVariationCookieValue }
            ]);
        });

    }

    function includeUserInAbTest() {
        if (window.arkAbTestConfig.AbTestSampleRate < "100") {
            var rand = Math.random();
            if (rand * 100 > window.arkAbTestConfig.AbTestSampleRate) {
                return false;
            }
        }
        if (window.arkAbTestConfig.AbTestPlatform.indexOf(getPlatformType()) >= 0 &&
            window.arkAbTestConfig.AbTestUsers.indexOf(getUserType()) >= 0) {
            return true;
        }
        return false;
    }

    function getUserType() {
        if (window.ark_jQuery.cookie(self.gaCookieName)) {
            return "existing";
        } else {
            return "new";
        }
    }

    function getPlatformType() {
        return window.arkPage.arena.device;
    }

    function getVariationByName(name) {
        if (typeof window.arkAbTestConfig.variations[name] === "object") {
            return window.arkAbTestConfig.variations[name];
        }
        return null;
    }

    function showVariation(name) {
        window.ark_jQuery("[ark-ab-test-variation='" + name + "']").show();
        window.ark_jQuery("html").addClass("ark-ab-test-variation-" + name);
        var variations = Object.keys(window.arkAbTestConfig.variations);
        for (var i = 0; i < variations.length; i++) {
            if (variations[i] !== name) {
                window.ark_jQuery("[ark-ab-test-variation='" + variations[i] + "']").remove();
            }
        }
    }

    function setCustomDimension() {

    }

    function abTestConfigValid(config) {
        return config.AbTestName &&
            config.AbTestCookieName &&
            config.AbTestCustomDimension &&
            config.AbTestDefaultVariationName &&
            config.variations[config.AbTestDefaultVariationName];
    }
}

new ArkAbTestHelper().RunAbTestIfAvailable();
// NEW 
ark_Search = {
    
    Initialize: function (items) {
        ark_jQuery("#searchfield").autocomplete({
            minLength: 3,
            appendTo: ark_jQuery('.arena-mb-li'),
            source: function (request, response) {
                var matcher = new RegExp(ark_jQuery.ui.autocomplete.escapeRegex(request.term), "i");
                arkArena.getItems().done(function (items) {
                    response(ark_jQuery.grep(items,
                        function (value) {
                            value.priority = matcher.test(value.name)
                                ? 1
                                : matcher.test(value.descryption) ? 2 : matcher.test(value.mechanic) ? 3 : 0;
                            return value.priority > 0 ? true : false;
                        }));
                });
            },
            select: function (event, ui) {
                ark_Search.TrackAdaptPageView(ui.item.key, ark_jQuery('#searchfield').val());
                if (arkPage.arena.inIframe) {
                    var substrPos = ui.item.url.indexOf("games/") > 0 ? ui.item.url.indexOf("games/") : ui.item.url.indexOf("QuizDetails");
                    var subUrl = "arkpath=/" + ui.item.url.substring(substrPos, ui.item.url.length);
                    var topUrl = removeParam("arkpath", document.referrer);
                    var separatop = topUrl.indexOf("?") > 0 ? "&" : "?";

                    parent.postMessage('event=changeUrl&url=' + encodeURIComponent(topUrl + separatop + subUrl), '*');
                } else {
                    document.location.href = ui.item.url;
                }
            },
            create: function () {
                
                ark_jQuery(this).data('ui-autocomplete')._renderMenu = function (ul, resultItems) {
                    var that = this;
                    if (ark_jQuery(".arena-wrapper").hasClass("arena-platform-narrow")) {
                        ark_jQuery(".ui-autocomplete").addClass("arena-platform-narrow");
                    }
                    resultItems.sort(function (a, b) {
                        if (a.priority > b.priority) {
                            return 1;
                        }
                        if (a.priority < b.priority) {
                            return -1;
                        }
                        return 0;
                    });

                    resultItems = ark_Search._distinct(resultItems);
                    ark_jQuery.each(resultItems, function (index, item) {
                        that._renderItemData(ul, item);
                    });
                };
                ark_jQuery(this).data('ui-autocomplete')._renderItemData = function (ul, item) {
                    return this._renderItem(ul, item).data("ui-autocomplete-item", item);
                };
                ark_jQuery(this).data('ui-autocomplete')._renderItem = function (ul, item) {
                    var res = ark_jQuery("<ark-li>")
                        .append(
                            ark_jQuery("<a>")
                            .attr('href', item.url)
                            .attr('search-item-key', item.key)
                            .attr('data-buttonname', 'SearchResult')
                            .append(
                                ark_jQuery("<ark-span>")
                                .attr('class', 'arena-autocmplt-img')
                                .append(
                                    ark_jQuery("<img>").attr('src', item.getImage('75x75'))
                                )
                            )
                            .append(
                                ark_jQuery("<ark-span>")
                                .attr('class', 'arena-autocmplt-txt')
                                .text(item.name)
                            )
                        )
                        .appendTo(ul);
                    if (arkGaEventsHandler && arkGaEventsHandler.init) {
                        arkGaEventsHandler.init(ul.context);
                    }
                    return res;
                };
            }

        });
    },
    _distinct: function(array) {
        var dist = [];
        var result = [];
        for (var i = 0; i < array.length; i++) {
            if (dist.indexOf(array[i].key) < 0) {
                dist.push(array[i].key);
                result.push(array[i]);
            }
        }
        return result;
    },
    TrackAdaptPageView: function (externalGameId, searchTerm) {
        var gaparams = 'OriginPage=' + arkPage.Params['Page'] + '&OriginModule=Search';
        if (typeof arkPage.game != "undefined" && typeof arkPage.game.externalGameId != "undefined" && arkPage.game.externalGameId.length > 0) {
            gaparams = gaparams + '&OriginGame=' + arkPage.game.externalGameId;
        }
        if (typeof searchTerm == "string" && searchTerm.length > 0) {
            gaparams = gaparams + '&SearchTearm=' + searchTerm;
        }
        var date = new Date();
        var minutes = 1;
        date.setTime(date.getTime() + (minutes * 60 * 1000));
        ark_jQuery.cookie("arkadaptparams", gaparams, { expires: date, path: '/' });
    }
};
ark_jQuery(document).ready(function () {
    ark_Search.Initialize();
});
function cutDescription() {
    ark_jQuery(".nodeHeight").each(function () {
        var height = ark_jQuery(this).height();
        var b = ark_jQuery(this).find('span').height();
        var text = ark_jQuery(this).find('span').text();
        var size = text.length;
        while ((b > height) && (size > 0)) {
            size--;
            ark_jQuery(this).find('span').text(text.slice(0, size) + '...');
            b = ark_jQuery(this).find('span').height();
        }
    });
}

    ark_jQuery(document).ready(function () {

        cutDescription();
    });

function GenerateRecaptcha(recaptchaDivID, tabIndex){
    Recaptcha.create('6LfxVwUAAAAAAA80DGEK6GZIXTkHx7usxrjQhxio', recaptchaDivID, {
        theme: 'clean',
        tabindex: tabIndex,
        lang: arkPage.arena.localization.substr(0, 2),
        callback: Recaptcha.focus_response_field
    });
}

function ReloadRecaptcha(param) {
    switch (param) {
        case "focusoff":
            Recaptcha.reload_internal("t");
            break;
        default:
            Recaptcha.reload();
    }
}

function DestroyRecaptcha() {
    Recaptcha.destroy();
}

(function (d) {
    var js, id = 'recaptcha-jssdk', ref = d.getElementsByTagName('script')[0];
    if (d.getElementById(id)) { return; }
    js = d.createElement('script'); js.id = id; js.async = true;
    js.src = "//www.google.com/recaptcha/api/js/recaptcha_ajax.js";
    ref.parentNode.insertBefore(js, ref);
}(document));
ark_jQuery(function() {
    if ( ark_jQuery(".arena-game-score").is(':visible')){
           ark_jQuery(".arena-title-block").css({'max-width': '100%'});
    } else {
         ark_jQuery(".arena-title-block").css({'max-width': '51%'});
    }
});
var ark_Popup = {
    settings: {
        autoClose: false,
        autoCloseTime: 10 * 60 * 1000,
        alignLeft: false,
        alignLeftElement: ".ark-container",
        alignTop: false
    },
    Initialize: function (nameOfPopUp) {
        if (arkPage.arena.isIPad) {
            ark_jQuery('html').addClass("arena-ipad");
        }
        if (arkPage.arena.isIOS) {
            ark_jQuery('html').addClass("arena-ios");
        }
    },
    close: function (name) {
        ark_jQuery('body').removeClass('body-modal-open');
        ark.triggerEvent('ARK_PopUp_' + name + ':EventClose');
        var thisPopup = ark_jQuery("#ARK_popup_" + name + ".ARK_popup");
        ark_jQuery("html, body").removeClass("ARK_popup_opened");
        if (+thisPopup.attr("data-scrolltop")) {
            ark_jQuery("body").scrollTop(+thisPopup.attr("data-scrolltop"));
        }
        thisPopup.removeClass("ARK_popup-active");
        thisPopup.attr("style", "");
        ark_jQuery("#gameBlock").removeClass("pop_up_active");
        var timer = parseInt(thisPopup.attr("data-close-timer"));
        if (!isNaN(timer)) {
            clearTimeout(ark_Popup.timer);
            thisPopup.attr("data-close-timer", "");
        }
        ark_jQuery('#flash_game').removeClass('game_hidden');
    },
    open: function (name, event) {
        var thisPopup = ark_jQuery("#ARK_popup_" + name);
        ark_jQuery('body').addClass('body-modal-open');
        ark_jQuery('body').on('click', function (event) {
            var target = event.target;
            if (ark_jQuery(target).hasClass('ARK_overlay') || ark_jQuery(target).hasClass('arena-popup-close')) {
                ark_Popup.close(name);
                console.log(target, name);
            }
            else { return }
        });
        if (thisPopup.length < 1) {
            ark.logging("ark_Popup: " + name + " not defined");
            return false;
        }
        if (thisPopup.hasClass("ARK_popup-active")) {
            ark.logging("ark_Popup: " + name + " already open");
            return false;
        }
        if (thisPopup.attr("data-place") != "body") {
            thisPopup.appendTo("body").attr("data-place", "body");
        }

        event = event || null;

        ark_Popup._show(name, thisPopup, event);

        if (!!(thisPopup.attr("data-auto-close") || ark_Popup.settings.autoClose)) {
            var timer = parseInt(thisPopup.attr("data-close-timer"));
            if (!isNaN(timer)) { clearTimeout(timer); }
            timer = setTimeout(function () {
                if (thisPopup.hasClass("ARK_popup-active")) {
                    thisPopup.attr("data-close-timer", "");
                    ark_Popup.close(name);
                }
            }, ark_Popup.settings.autoCloseTime);
            thisPopup.attr("data-close-timer", timer);
            ark.logging("ark_Popup: " + name + " autoClose timer started");
        }

        ark.logging("ark_Popup: " + name + " opened");
    },

    _show: function (name, thisPopup, event) {
        var isFrame = !!ark_jQuery(".arena-wrapper[class*=\"inIframe-\"]").length,
            isIPad = arkPage.arena.isIPad,
            popupRect;

        ark.triggerEvent('ARK_PopUp_' + name + ':EventOpen');
        if (isFrame) {
            thisPopup.addClass("ark_popup_iframe");
            ark_jQuery(".ARK_overlay").css({
                display: "none"
            });
            ark_Popup._alignInFrame(thisPopup, event);
        } else if (isIPad) {
            thisPopup.attr("data-scrolltop", ark_jQuery("body").scrollTop());
            fixScroll(thisPopup);
        } else {
            ark_jQuery("html, body").addClass("ARK_popup_opened");
        }

        thisPopup.addClass("ARK_popup-active");
        ark_jQuery("#gameBlock").addClass("pop_up_active");

        popupRect = thisPopup[0].getBoundingClientRect();

        if (isFrame) {
            if (popupRect.top < 0) {
                thisPopup.css({
                    top: 0
                });
            }
            if (popupRect.bottom > document.body.offsetHeight) {
                thisPopup.css({
                    bottom: 0
                });
            }
        }
    },
    load: function (name, content) {
        ark_jQuery("#ARK_popup_" + name + " .ARK_popup_custom_content").html(content);
    },
    showCustomContent: function (name, toggle) {
        if (toggle == undefined) {
            ark_jQuery("#ARK_popup_" + name).toggleClass("ARK_popup-custom");
        } else {
            ark_jQuery("#ARK_popup_" + name).toggleClass("ARK_popup-custom", toggle);
        }
    },
    _alignInFrame: function (popup, event) {
        var currentEvent = event ? event : {},
            styleObject = {
                left: "auto",
                right: "auto",
                top: "auto",
                bottom: "auto"
            },
            transformOrigin = {
                x: "50%",
                y: "50%"
            },
            ctrl = currentEvent.target,
            coord = getCoordinates(ctrl),
            timeout;
        if (!currentEvent) {
            styleObject.top = "0";
            styleObject.left = "0";
            styleObject.right = "0";

            transformOrigin.y = "0";
        } else {
            if (coord.availLeft < 300 && coord.availRight < 300) {
                styleObject.left = "0";
                styleObject.right = "0";

                transformOrigin.x = "50%";
            } else if (coord.availLeft >= 300) {
                styleObject.left = coord.left + "px";
                styleObject.right = coord.availLeft < 600 ? "0" : "auto";
                styleObject.textAlign = "left";

                transformOrigin.x = "0";
            } else if (coord.availRight >= 300) {
                styleObject.right = coord.right + "px";
                styleObject.left = coord.availRight < 600 ? "0" : "auto";
                styleObject.textAlign = "right";

                transformOrigin.x = "100%";
            }
            if (coord.availBottom <= coord.availTop) {
                styleObject.bottom = coord.bottom + "px";

                transformOrigin.y = "100%";
            } else {
                styleObject.top = coord.top + "px";

                transformOrigin.y = "0";
            }
        }

        popup.css(styleObject);

        popup.find(".ARK_popup_content").css({
            "transform-origin": transformOrigin.x + " " + transformOrigin.y,
            "transition-delay": "0s"
        });

        ark_jQuery(window).on("resize", function () {
            timeout = setTimeout(function () {
                if (!popup.hasClass("ARK_popup-active")) {
                    clearTimeout(timeout);
                    return false;
                }
                ark_Popup._alignInFrame(popup, currentEvent);
            }, 500);
            clearTimeout(timeout);
        });
        ark_jQuery(window)
            .on("orientationchange",
                function () {
                    if (!popup.hasClass("ARK_popup-active")) {
                        clearTimeout(timeout);
                        return false;
                    }
                    ark_Popup._alignInFrame(popup, currentEvent);
                });
    }
};

function getCoordinates(elem) {
    var rect = elem.getBoundingClientRect();

    return {
        width: rect.width,
        height: rect.height,
        top: rect.bottom,
        left: rect.left,
        bottom: document.body.offsetHeight - rect.top,
        right: document.body.offsetWidth - rect.right,
        availBottom: document.body.offsetHeight - rect.bottom,
        availTop: rect.top,
        availLeft: document.body.offsetWidth - rect.left,
        availRight: rect.right
    };
}

function fixScroll(popup) {
    var st = +popup.attr("data-scrolltop");
    ark_jQuery("html, body").addClass("ARK_popup_opened");
    // ark_jQuery("body").scrollTop(st);
    popup.css({
        top: st + 'px',
        bottom: -st + 'px'
    });
    popup[0].scrollIntoView();
}
ark_Rating = {
    CurrentRating: 0,
    UserReview: {
        ReviewObj: {},
        LoadUserReview: function (externalGameId, event) {
            var data1 = {};
            data1["userReview"] = true;
            data1["ExtGameId"] = externalGameId;
            ark_jQuery.ajax({
                url: "/Services/RatingHelper.ashx?r=" + Math.random(),
                data: data1,
                type: "POST",
                success: function (a) {
                    if (a) {
                        ark_Rating.UserReview.ReviewObj = JSON.parse(a);
                        if (ark_Rating.UserReview.ReviewObj.Feedback != null) {
                            var arrData = ark_Rating.UserReview.ReviewObj.Feedback.split("|||");
                            var title = arrData.length == 3 || arrData.length == 2 ? arrData[0] : "";
                            var rev = arrData.length == 3 || arrData.length == 2 ? arrData[1] : arrData[0];
                            ark_jQuery('#varTitle').val(title);
                            ark_jQuery('.Ark_UserFeedback').val(rev);
                        } else {
                            ark_jQuery('#varTitle').val('');
                            ark_jQuery('.Ark_UserFeedback').val('');
                        }
                        ark_Rating.UserRenderStars(externalGameId, ark_Rating.UserReview.ReviewObj.Value, 'arena-ratingForPopup');
                        ark_Popup.open('ReviewRating', event);
                    }
                }
            });
        },
        SaveUserReview: function (review) {
            ark_Rating.UserReview.ReviewObj.Feedback = review;
            ark_Rating.ReviewGame(ark_Rating.UserReview.ReviewObj.Value, ark_Rating.UserReview.ReviewObj.RatingKey, review);
        }
    },
    RenderStars: function (ratingKeeperObject, qualityNumber, maxquality, countRate) {
        var perc = 0;
        var parsedQuality = parseFloat(qualityNumber);
        if (parsedQuality !== 0) {
            perc = Math.round((parseFloat(parsedQuality) / 5) * 100);
        }

        ark_jQuery(ratingKeeperObject).find('.ark_rating_full2').css('width', perc + '%');
        ark_jQuery(ratingKeeperObject).find('.ark_rating_full2').attr("data-ark_quality_number", qualityNumber);
        ark_jQuery(ratingKeeperObject).find('.ark_rating_full2').attr("data-ark_max_quality", maxquality);
        ark_jQuery(ratingKeeperObject).find('.ark_rating_full2').attr("data-ark_coun_rate", countRate);

    },
    ReRenderStars: function (externalGameId, qualityNumber, maxquality, countRate) {
        var perc = 0;
        var parsedQuality = parseFloat(qualityNumber);
        if (parsedQuality !== 0) {
            perc = Math.round((parseFloat(parsedQuality) / 5) * 100);
        }
        ark_jQuery.each(ark_jQuery(".ark_rating_full2." + externalGameId), function () {
            if (typeof ark_jQuery(this).attr("data-ark_user_rate") == "undefined") {
                ark_jQuery(this).parent().parent().find('.ark_rating_full2.' + externalGameId).css('width', perc + '%');
                ark_jQuery(this).parent().parent().find('.ark_rating_full2.' + externalGameId).attr("data-ark_quality_number", qualityNumber);
                ark_jQuery(this).parent().parent().find('.ark_rating_full2.' + externalGameId).attr("data-ark_max_quality", maxquality);
                ark_jQuery(this).parent().parent().find('.ark_rating_full2.' + externalGameId).attr("data-ark_coun_rate", countRate);
                ark_jQuery(this).parent().parent().find(' .arena-count-rate').html('(' + countRate + ')');
            }
        });

    },
    UserRenderStars: function (externalGameId, qualityNumber, timeStamp) {
        var perc = 0;
        var parsedQuality = parseFloat(qualityNumber);
        if (parsedQuality !== 0) {
            perc = Math.round((parseFloat(parsedQuality) / 5) * 100);
        }
        ark_jQuery('.' + timeStamp + ' .ark_rating_full2.' + externalGameId).css('width', perc + '%');
        ark_jQuery('.' + timeStamp + ' .ark_rating_full2.' + externalGameId).attr("data-ark_quality_number", qualityNumber);
        ark_jQuery('.' + timeStamp + ' .ark_rating_full2.' + externalGameId).attr("data-ark_max_quality", 5);
        ark_jQuery('.' + timeStamp + ' .ark_rating_full2.' + externalGameId).attr("data-ark_coun_rate", 1);
        ark_jQuery('.' + timeStamp + ' .ark_rating_full2.' + externalGameId).attr("data-ark_user_rate", true);
        ark_jQuery('.' + timeStamp + ' .arena-count-rate').hide();
    },
    RateGame: function (rateValue, externalGameId, reviewText, timeStamp) {
        var data1 = {};
        data1["ExtGameId"] = externalGameId;
        data1["RateValue"] = rateValue;
        data1["ReviewText"] = reviewText;
        this.CurrentRating = rateValue;
        ark_jQuery.ajax({
            url: "/Services/RatingHelper.ashx?r=" + Math.random(),
            data: data1,
            type: "POST",
            success: function (a) {
                if (a) {
                    var obj = JSON.parse(a);
                    if (obj.SumRate == 0) {
                        ark_Rating.ReRenderStars(externalGameId, obj.AvgRate, 10, 0);
                    } else {
                        ark_Rating.UserRenderStars(externalGameId, rateValue, timeStamp);
                    }
                    ark.logging(a);
                    ark.triggerEvent("ark_rating_addedRating");
                    /*ark_Rating.UserReview.LoadUserReview(externalGameId);*/

                }
            }
        });
    },
    ReviewGame: function (rateValue, externalGameId, reviewText) {
        var data1 = {};
        data1["ExtGameId"] = externalGameId;
        data1["RateValue"] = rateValue;
        data1["ReviewText"] = reviewText;
        ark_jQuery.ajax({
            url: "/Services/RatingHelper.ashx?r=" + Math.random(),
            data: data1,
            type: "POST",
            success: function (a) {
                if (a) {
                    ark.triggerEvent("ark_rating_addedReview");
                    ark_Popup.close('ReviewRating');
                }
            }
        });
    },
    Initialize: function (externalGameId, timeStampHash, isLoginSystemEnabled, qualityNumber, maxQuality, countRate) {
        ark_jQuery(document).ready(function () {
            ark_Rating.ReRenderStars(externalGameId, qualityNumber, maxQuality, countRate);
            ark_jQuery('.ark_user_rate2.' + externalGameId).hide();
        });

    },
    ReviewInitialization: function (timeStamp) {
        ark_jQuery('#ReviewRatePopUp_' + timeStamp + ' .RateButton_submit_' + timeStamp).on('click', function () {
            var ratingValue = ark_Rating.CurrentRating == 0 ? parseInt(ark_jQuery(".arena-ratingForPopup .ark_rating_full2").data().ark_quality_number) : ark_Rating.CurrentRating;
            if (ratingValue <= 0) {
                //ark_jQuery(".arena-rating-popup-layer").toggle();
                return;
            }
            var title = ark_jQuery('#ReviewRatePopUp_' + timeStamp + ' input').val();
            var review = ark_jQuery('#ReviewRatePopUp_' + timeStamp + ' textarea').val();
            if (review != "") {
                if (title == "")title = "Review";
                ark_Rating.UserReview.SaveUserReview(title + '|||' + review);
            }

        });
        ark_jQuery('#ReviewRatePopUp_' + timeStamp + ' .RateButton_cancel_' + timeStamp).on('click', function () {
            ark_Popup.close("ReviewRating");
        });

        //ark_jQuery('#popupRatingStars').html(ark_jQuery('#userRatingStars > .arena-rate-block').html());
        ark_jQuery("#popUpReviewStars").appendTo("#popupRatingStars");
    }
}

function fbLogin(redirectTo) {
    loginLogic();
    ark.triggerEvent("login-click");
}

function fbLoginTopNav(redirectTo) {
    loginLogic();
    ark.triggerEvent("top-nav-login-click");
}

function loginLogic(){
    if (arkPage.arena.loginSystems !== "fb") {
        if (typeof window.DoCustomRegisterLogin === "function") {
            window.DoCustomRegisterLogin();
        }
    }
    else
    {
        var iframe = document.getElementById('arkIsolationIframe');
        if (iframe) {
            iframe.contentWindow.postMessage({ action: "arkLogin" }, "*");
        }
    }
}

ark.addListener("arkFbUpdateUserInfo", function (data) {
    arkPage.user.update(data.id, data.name, data.email, 'fb');
});


var 
    TK = {

        "encrypt": function (src, _sKey) {
            var
                v = TK.charsToLongs(TK.strToChars(src)),
                k = TK.charsToLongs(TK.strToChars(_sKey)),
                n = v.length;

            if (n == 0) return "";
            if (n == 1) v[n++] = 0;

            var 
                z = v[n - 1],
                y = v[0],
                delta = 0x9E3779B9,
                max32 = 4294967295,
                mx,
                e,
                q = Math.floor(6 + 52 / n),
                sum = 0,
                sum2 = 0;

            while (q-- > 0) {
                sum += delta;
                sum = sum >>> 0;
                e = sum >>> 2 & 3;
                for (var p = 0; p < n - 1; p++) {
                    y = v[p + 1];
                    mx = (z >>> 5 ^ y << 2) + (y >>> 3 ^ z << 4) ^ (sum ^ y) + (k[p & 3 ^ e] ^ z);
                    mx = mx >>> 0;
                    v[p] += mx;
                    v[p] = v[p] >>> 0;
                    z = v[p];
                }
                y = v[0];
                mx = (z >>> 5 ^ y << 2) + (y >>> 3 ^ z << 4) ^ (sum ^ y) + (k[p & 3 ^ e] ^ z);
                mx = mx >>> 0;
                v[n - 1] += mx;
                v[n - 1] = v[n - 1] >>> 0;
                z = v[n - 1];
            }
            return TK.charsToHex(TK.longsToChars(v));
        },

        "decrypt": function (src, _sKey) {
            var
                v = TK.charsToLongs(TK.hexToChars(src)),
                k = TK.charsToLongs(TK.strToChars(_sKey)),
                n = v.length;

            if (n == 0) return "";

            var 
                z = v[n - 1],
                y = v[0],
                delta = 0x9E3779B9,
                mx,
                e,
                q = Math.floor(6 + 52 / n),
                sum = q * delta;

            while (sum != 0) {
                e = sum >>> 2 & 3;
                for (var p = n - 1; p > 0; p--) {
                    z = v[p - 1];
                    mx = (z >>> 5 ^ y << 2) + (y >>> 3 ^ z << 4) ^ (sum ^ y) + (k[p & 3 ^ e] ^ z);
                    y = v[p] -= mx;
                }
                z = v[n - 1];
                mx = (z >>> 5 ^ y << 2) + (y >>> 3 ^ z << 4) ^ (sum ^ y) + (k[p & 3 ^ e] ^ z);
                y = v[0] -= mx;
                sum -= delta;
            }
            var aChars = TK.longsToChars(v);
            for (var i = aChars.length - 1; i >= 0; i--) {
                if (aChars[i] == 0) {
                    aChars.splice(i, 1);
                } else {
                    break;
                }
            }
            return TK.charsToStr(aChars);
        },

        "charsToLongs": function (chars) {
            var temp = new Array(Math.ceil(chars.length / 4));
            for (var i = 0; i < temp.length; i++) {
                temp[i] = chars[i * 4] + (chars[i * 4 + 1] << 8) + (chars[i * 4 + 2] << 16) + (chars[i * 4 + 3] << 24);
            }
            return temp;
        },

        "longsToChars": function (longs) {
            var codes = new Array();
            for (var i = 0; i < longs.length; i++) {
                codes.push(longs[i] & 0xFF, longs[i] >>> 8 & 0xFF, longs[i] >>> 16 & 0xFF, longs[i] >>> 24 & 0xFF);
            }
            return codes;
        },

        "charsToHex": function (chars) {
            var  
                result = new String(""),
                hexes = new Array("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f");
            for (var i = 0; i < chars.length; i++) {
                result += hexes[chars[i] >> 4] + hexes[chars[i] & 0xf];
            }
            return result;
        },

        "hexToChars": function (hex) {
            var codes = new Array();
            for (var i = (hex.substr(0, 2) == "0x") ? 2 : 0; i < hex.length; i += 2) {
                codes.push(parseInt(hex.substr(i, 2), 16));
            }
            return codes;
        },

        "charsToStr": function (chars) {
            var result = new String("");
            for (var i = 0; i < chars.length; i++) {
                result += String.fromCharCode(chars[i]);
            }
            return result;
        },

        "strToChars": function (str) {
            str = str ?str:'';
            var codes = new Array();
            for (var i = 0; i < str.length; i++) {
                codes.push(str.charCodeAt(i));
            }
            return codes;
        }
    };
// constructor of leaderboard object

function Leaderboard(options) {
    this.basePlayUrl = "";
    this.cdnBaseUrl = "";
    this.baseUrl = "";
    this.gameID = 0;
    this._updateInProgress = false;

    this.nTop = 10;
    this.type = "score";
    this.period = "day";

    this.cache = {};

    ark_jQuery.extend(this, options);

    this.period = ark_jQuery.cookie("lbTimePeriod") || this.period;
    delete ark.listeners['needUpdateLeaderboard'];
    ark.addListener('needUpdateLeaderboard', this._onUpdateLeaderboardHandler.bind(this));
}

Leaderboard.prototype._hasCache = function (period) {
    return !!this.cache[period];
};

Leaderboard.prototype._setCache = function (period, itemsArray) {
    this.cache[period] = {
        Items : itemsArray
    };
};

Leaderboard.prototype._getCache = function (period) {
    return this.cache[period];
};

Leaderboard.prototype._saveCookies = function () {
    ark_jQuery.cookie('lbTimePeriod', this.period, { expires: 300, path: "/" });
};

Leaderboard.prototype._retrieveData = function(period, useCache) {
    var _this = this,
        useCacheData = useCache ? "1" : "0",
        data =  "{" +
                    "\"leaderboardRequest\":{" +
                        "\"Period\":\"" + period + "\"," +
                        "\"Type\":\"" + _this.type + "\"," +
                        "\"ExternalGameId\":\"" + _this.gameID + "\"," +
                        "\"NTop\":\"" + _this.nTop + "\"," +
                        "\"UseCache\":\"" + useCacheData + "\"" +
                    "}" +
                "}";

    ark_jQuery(".arena-inner-tab-data").removeClass("active");
    ark_jQuery('.leaderboard_loader').show();

    if (!this._hasCache(period) || !useCache) {
        return ark_jQuery.ajax({
            url: _this.baseUrl + "/LB/GetLeaderboard?r=" + Math.random(),
            data: data,
            type: "POST",
            processData: true,
            contentType: "application/json; charset=utf-8",
            dataType: "json"
        })
            .done(function (data) {
                var itemsArray = data && data.Items ? data.Items : [];

                _this._setCache(period, itemsArray);
            });
    } else {
        return new ark_jQuery.Deferred().resolve();
    }
};

Leaderboard.prototype._onUpdateLeaderboardHandler = function() {
    var _this = this;
    _this._updateInProgress = true;
    ark_jQuery
        .when(
            _this._retrieveData("day", false),
            _this._retrieveData("week", false),
            _this._retrieveData("all", false)
        )
        .always(function () {
            _this._updateInProgress = false;
            _this._showTab(_this.period);
        });
};

Leaderboard.prototype._cleanContainer = function () {
    ark_jQuery("#LBData").empty();
};

Leaderboard.prototype._buildItem = function (rank, avatar, user_id, user_name, score) {
    var avatarLnk = "";

    score = ark.commafy(score);

    if ( avatar === "" || this.isKidsAuthSystem ) {
        avatarLnk = this.cdnBaseUrl + "Content/images/defAva.gif";
    } else {
        avatarLnk = avatar;
    }

    var profileHref = window.masterViewGlobals.supportProfile ? "href='/profile/" + user_id + "'" : "";
    
  return "<ark-li id=\"LBData-" + user_id + "\">"+
            "<ark-ul class=\"arena-tab-data\">"+
                "<ark-li ark-test-id=\"leaderboard-user-row\">"+
                    "<a "+ profileHref +"><table class=\"arena-leader-record\">"+
                        "<tr>"+
                            "<td class=\"rankNum\">"+
                                "<ark-span>"+
                                    rank+
                                "</ark-span>"+
                            "</td>"+
                            "<td>"+
                                "<figure class=\"arena-user-avatar repUserProfile_" + user_id + "\">"+
                                    "<img src=\"" + avatarLnk + "\"/>"+
                                "</figure>"+
                            "</td>"+
                            "<td>"+
                                "<ark-p class=\"arena-user-name repUserProfile_" + user_id + "\">"+
                                    decodeURI(user_name)+
                                "</ark-p>"+
                            "</td>"+
                            "<td class=\"leaderboard_score\">"+
                                "<ark-span class=\"arena-score\" title=\"" + score + "\">" + score + "</ark-span>"+
                            "</td>"+
                        "</tr>"+
                    "</table></a>"+
                "</ark-li>"+
            "</ark-ul>"+
          "</ark-li>";
};

Leaderboard.prototype._render = function(period) {
    var dataArray = this._getCache(period).Items,
        fragment = ark_jQuery(document.createDocumentFragment()),
        container;
    for (var i = 0, item, rankValue; i < dataArray.length; i++) {
        rankValue = dataArray[i].Rank || ( i + 1 );
        item = this._buildItem(rankValue, dataArray[i].Av, dataArray[i].UId, dataArray[i].UName, dataArray[i].Value);
        fragment.append(item);
    }
    this._cleanContainer();
    container = ark_jQuery("<ark-ul id=\"LBData-C\"></ark-ul>");
    container.append(fragment);
    ark_jQuery("#LBData").append(container).addClass("active");
    ark_jQuery("#LBData").customScrollbar();
};

Leaderboard.prototype._showTab = function (period) {
    ark_jQuery(".arena-inner-tab-data").removeClass("active");
    this.period = period;
    this._saveCookies();
    ark_jQuery('.leaderboard_loader').hide();
    if (this._hasCache(period) && this.cache[period].Items.length) {
        this._render(this.period);
    } else {
        if (arkPage.user.isActive) {
            ark_jQuery('#NoGamePlays').addClass("active");
        }
        else {
            if (arkPage.arena.loginSystems !== 'kids') {
                ark_jQuery('#NoAuthorized').addClass("active");
                ark.addListener('ark:login', function (e) {
                    ark.triggerEvent('needUpdateLeaderboard');
                });
            }
        }
    }
};

Leaderboard.prototype.changeTab = function(period) {
    var _this = this;
    _this.period = period;

    if (!_this._updateInProgress) {
        _this
            ._retrieveData(period, true)
            .done(function() {
                setTimeout(function () {
                    _this._showTab(period);
                }, 10);
            });
    }
};



md5 = function(string) {

    function RotateLeft(lValue, iShiftBits) {
        return (lValue << iShiftBits) | (lValue >>> (32 - iShiftBits));
    }

    function AddUnsigned(lX, lY) {
        var lX4, lY4, lX8, lY8, lResult;
        lX8 = (lX & 0x80000000);
        lY8 = (lY & 0x80000000);
        lX4 = (lX & 0x40000000);
        lY4 = (lY & 0x40000000);
        lResult = (lX & 0x3FFFFFFF) + (lY & 0x3FFFFFFF);
        if (lX4 & lY4) {
            return (lResult ^ 0x80000000 ^ lX8 ^ lY8);
        }
        if (lX4 | lY4) {
            if (lResult & 0x40000000) {
                return (lResult ^ 0xC0000000 ^ lX8 ^ lY8);
            } else {
                return (lResult ^ 0x40000000 ^ lX8 ^ lY8);
            }
        } else {
            return (lResult ^ lX8 ^ lY8);
        }
    }

    function F(x, y, z) { return (x & y) | ((~x) & z); }

    function G(x, y, z) { return (x & z) | (y & (~z)); }

    function H(x, y, z) { return (x ^ y ^ z); }

    function I(x, y, z) { return (y ^ (x | (~z))); }

    function FF(a, b, c, d, x, s, ac) {
        a = AddUnsigned(a, AddUnsigned(AddUnsigned(F(b, c, d), x), ac));
        return AddUnsigned(RotateLeft(a, s), b);
    }

    ;

    function GG(a, b, c, d, x, s, ac) {
        a = AddUnsigned(a, AddUnsigned(AddUnsigned(G(b, c, d), x), ac));
        return AddUnsigned(RotateLeft(a, s), b);
    }

    ;

    function HH(a, b, c, d, x, s, ac) {
        a = AddUnsigned(a, AddUnsigned(AddUnsigned(H(b, c, d), x), ac));
        return AddUnsigned(RotateLeft(a, s), b);
    }

    ;

    function II(a, b, c, d, x, s, ac) {
        a = AddUnsigned(a, AddUnsigned(AddUnsigned(I(b, c, d), x), ac));
        return AddUnsigned(RotateLeft(a, s), b);
    }

    ;

    function ConvertToWordArray(string) {
        var lWordCount;
        var lMessageLength = string.length;
        var lNumberOfWords_temp1 = lMessageLength + 8;
        var lNumberOfWords_temp2 = (lNumberOfWords_temp1 - (lNumberOfWords_temp1 % 64)) / 64;
        var lNumberOfWords = (lNumberOfWords_temp2 + 1) * 16;
        var lWordArray = Array(lNumberOfWords - 1);
        var lBytePosition = 0;
        var lByteCount = 0;
        while (lByteCount < lMessageLength) {
            lWordCount = (lByteCount - (lByteCount % 4)) / 4;
            lBytePosition = (lByteCount % 4) * 8;
            lWordArray[lWordCount] = (lWordArray[lWordCount] | (string.charCodeAt(lByteCount) << lBytePosition));
            lByteCount++;
        }
        lWordCount = (lByteCount - (lByteCount % 4)) / 4;
        lBytePosition = (lByteCount % 4) * 8;
        lWordArray[lWordCount] = lWordArray[lWordCount] | (0x80 << lBytePosition);
        lWordArray[lNumberOfWords - 2] = lMessageLength << 3;
        lWordArray[lNumberOfWords - 1] = lMessageLength >>> 29;
        return lWordArray;
    }

    ;

    function WordToHex(lValue) {
        var WordToHexValue = "", WordToHexValue_temp = "", lByte, lCount;
        for (lCount = 0; lCount <= 3; lCount++) {
            lByte = (lValue >>> (lCount * 8)) & 255;
            WordToHexValue_temp = "0" + lByte.toString(16);
            WordToHexValue = WordToHexValue + WordToHexValue_temp.substr(WordToHexValue_temp.length - 2, 2);
        }
        return WordToHexValue;
    }

    ;

    function Utf8Encode(string) {
        string = string.replace(/\r\n/g, "\n");
        var utftext = "";

        for (var n = 0; n < string.length; n++) {

            var c = string.charCodeAt(n);

            if (c < 128) {
                utftext += String.fromCharCode(c);
            } else if ((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            } else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }

        return utftext;
    }

    ;

    var x = Array();
    var k, AA, BB, CC, DD, a, b, c, d;
    var S11 = 7, S12 = 12, S13 = 17, S14 = 22;
    var S21 = 5, S22 = 9, S23 = 14, S24 = 20;
    var S31 = 4, S32 = 11, S33 = 16, S34 = 23;
    var S41 = 6, S42 = 10, S43 = 15, S44 = 21;

    string = Utf8Encode(string);

    x = ConvertToWordArray(string);

    a = 0x67452301;
    b = 0xEFCDAB89;
    c = 0x98BADCFE;
    d = 0x10325476;

    for (k = 0; k < x.length; k += 16) {
        AA = a;
        BB = b;
        CC = c;
        DD = d;
        a = FF(a, b, c, d, x[k + 0], S11, 0xD76AA478);
        d = FF(d, a, b, c, x[k + 1], S12, 0xE8C7B756);
        c = FF(c, d, a, b, x[k + 2], S13, 0x242070DB);
        b = FF(b, c, d, a, x[k + 3], S14, 0xC1BDCEEE);
        a = FF(a, b, c, d, x[k + 4], S11, 0xF57C0FAF);
        d = FF(d, a, b, c, x[k + 5], S12, 0x4787C62A);
        c = FF(c, d, a, b, x[k + 6], S13, 0xA8304613);
        b = FF(b, c, d, a, x[k + 7], S14, 0xFD469501);
        a = FF(a, b, c, d, x[k + 8], S11, 0x698098D8);
        d = FF(d, a, b, c, x[k + 9], S12, 0x8B44F7AF);
        c = FF(c, d, a, b, x[k + 10], S13, 0xFFFF5BB1);
        b = FF(b, c, d, a, x[k + 11], S14, 0x895CD7BE);
        a = FF(a, b, c, d, x[k + 12], S11, 0x6B901122);
        d = FF(d, a, b, c, x[k + 13], S12, 0xFD987193);
        c = FF(c, d, a, b, x[k + 14], S13, 0xA679438E);
        b = FF(b, c, d, a, x[k + 15], S14, 0x49B40821);
        a = GG(a, b, c, d, x[k + 1], S21, 0xF61E2562);
        d = GG(d, a, b, c, x[k + 6], S22, 0xC040B340);
        c = GG(c, d, a, b, x[k + 11], S23, 0x265E5A51);
        b = GG(b, c, d, a, x[k + 0], S24, 0xE9B6C7AA);
        a = GG(a, b, c, d, x[k + 5], S21, 0xD62F105D);
        d = GG(d, a, b, c, x[k + 10], S22, 0x2441453);
        c = GG(c, d, a, b, x[k + 15], S23, 0xD8A1E681);
        b = GG(b, c, d, a, x[k + 4], S24, 0xE7D3FBC8);
        a = GG(a, b, c, d, x[k + 9], S21, 0x21E1CDE6);
        d = GG(d, a, b, c, x[k + 14], S22, 0xC33707D6);
        c = GG(c, d, a, b, x[k + 3], S23, 0xF4D50D87);
        b = GG(b, c, d, a, x[k + 8], S24, 0x455A14ED);
        a = GG(a, b, c, d, x[k + 13], S21, 0xA9E3E905);
        d = GG(d, a, b, c, x[k + 2], S22, 0xFCEFA3F8);
        c = GG(c, d, a, b, x[k + 7], S23, 0x676F02D9);
        b = GG(b, c, d, a, x[k + 12], S24, 0x8D2A4C8A);
        a = HH(a, b, c, d, x[k + 5], S31, 0xFFFA3942);
        d = HH(d, a, b, c, x[k + 8], S32, 0x8771F681);
        c = HH(c, d, a, b, x[k + 11], S33, 0x6D9D6122);
        b = HH(b, c, d, a, x[k + 14], S34, 0xFDE5380C);
        a = HH(a, b, c, d, x[k + 1], S31, 0xA4BEEA44);
        d = HH(d, a, b, c, x[k + 4], S32, 0x4BDECFA9);
        c = HH(c, d, a, b, x[k + 7], S33, 0xF6BB4B60);
        b = HH(b, c, d, a, x[k + 10], S34, 0xBEBFBC70);
        a = HH(a, b, c, d, x[k + 13], S31, 0x289B7EC6);
        d = HH(d, a, b, c, x[k + 0], S32, 0xEAA127FA);
        c = HH(c, d, a, b, x[k + 3], S33, 0xD4EF3085);
        b = HH(b, c, d, a, x[k + 6], S34, 0x4881D05);
        a = HH(a, b, c, d, x[k + 9], S31, 0xD9D4D039);
        d = HH(d, a, b, c, x[k + 12], S32, 0xE6DB99E5);
        c = HH(c, d, a, b, x[k + 15], S33, 0x1FA27CF8);
        b = HH(b, c, d, a, x[k + 2], S34, 0xC4AC5665);
        a = II(a, b, c, d, x[k + 0], S41, 0xF4292244);
        d = II(d, a, b, c, x[k + 7], S42, 0x432AFF97);
        c = II(c, d, a, b, x[k + 14], S43, 0xAB9423A7);
        b = II(b, c, d, a, x[k + 5], S44, 0xFC93A039);
        a = II(a, b, c, d, x[k + 12], S41, 0x655B59C3);
        d = II(d, a, b, c, x[k + 3], S42, 0x8F0CCC92);
        c = II(c, d, a, b, x[k + 10], S43, 0xFFEFF47D);
        b = II(b, c, d, a, x[k + 1], S44, 0x85845DD1);
        a = II(a, b, c, d, x[k + 8], S41, 0x6FA87E4F);
        d = II(d, a, b, c, x[k + 15], S42, 0xFE2CE6E0);
        c = II(c, d, a, b, x[k + 6], S43, 0xA3014314);
        b = II(b, c, d, a, x[k + 13], S44, 0x4E0811A1);
        a = II(a, b, c, d, x[k + 4], S41, 0xF7537E82);
        d = II(d, a, b, c, x[k + 11], S42, 0xBD3AF235);
        c = II(c, d, a, b, x[k + 2], S43, 0x2AD7D2BB);
        b = II(b, c, d, a, x[k + 9], S44, 0xEB86D391);
        a = AddUnsigned(a, AA);
        b = AddUnsigned(b, BB);
        c = AddUnsigned(c, CC);
        d = AddUnsigned(d, DD);
    }

    var temp = WordToHex(a) + WordToHex(b) + WordToHex(c) + WordToHex(d);

    return temp.toLowerCase();
};
var arkArenaProtocol = {
    wrapperPlayId: '',
    callback: '',
    showGameEnd: true,
    arenaPlayId: '0',
    init: function () {
        if (this.isInIframe()) {
            this.iframeInit();
        }
        else {
            this.domInit();
        }
    },

    iframeInit: function () { this.parseData(document.location.search); },

    domInit: function () { arkPage.wrapperMessage = function (msg) { arkArenaProtocol.parseData(msg); } },

    searchQuery: function (qstr) {
        qstr = qstr.replace("?", "");
        var query = {};
        var a = qstr.split('&');
        for (var i = 0; i < a.length; i++) {
            var b = a[i].split('=');
            query[decodeURIComponent(b[0])] = decodeURIComponent(b[1] || '');
        }
        return query;
    },

    isInIframe: function () {
        try {
            return window.self !== window.top;
        } catch (e) {
            return true;
        }
    },

    parseData: function (str) {
        var events = this.searchQuery(str)["events"];
        if (events) {
            var eventsArray = events.split(",");
            for (var i = 0; i < eventsArray.length; i++) {
                this.registerEvent(eventsArray[i]);
            }
        }
        this.wrapperPlayId = this.searchQuery(str)["wrapper_play_id"];
        this.callback = this.searchQuery(str)["callback"];
        this.showGameEnd = this.searchQuery(str)["show_game_end"] != "false";
    },

    registerEvent: function (evt) {
        if (typeof (this.eventHandlers[evt]) == "function") {
            this.eventHandlers[evt]();
        } else {
            this.eventHandlers["def"](evt);
        }
    },

    eventHandlers: {
        game_game_end: function () {
            ark.addListener("game_game_end", function (args) {
                var obj = {};
                for (var i = 0; i < args.data.length; i++) {
                    obj[args.data[i].key] = args.data[i].value;
                }
                ark_jQuery.ajax({
                    url: '/arenaapi/GetGameEndScoreHash/',
                    type: "POST",
                    data: {
                        score: obj.score,
                        wrapperPlayId: arkArenaProtocol.wrapperPlayId,
                        externalGameId: arkPage.game.externalGameId,
                        arenaPlayId: arkArenaProtocol.arenaPlayId,
                        arenaHash: obj.score_hash
                    },
                    success: function (response) {
                        arkArenaProtocol.sentDataToClient('event=game_game_end&score=' + obj.score + '&score_hash=' + JSON.parse(response).hash);
                    },
                    error: function (response) { console.log(response); }
                });
            });
        },

        def: function (evt) {
            console.log("Event " + evt + "is not supported");
        }
    },

    sentDataToClient: function (message) {
        try {
            if (this.isInIframe()) {
                try {
                    if (window.opener) {
                        window.opener.postMessage(message, '*');
                    } else {
                        parent.postMessage(message, '*');
                    }
                } catch (e) { }
            } else {
                eval(this.callback + '("' + message + '");');
            }
        }
        catch (ex) { console.log(ex); }
    }
};
arkArenaProtocol.init();

//function test(msg) {
//    alert(msg);
//}

//arkPage.wrapperMessage("events=game_game_end&wrapperPlayId=10&callback=test");


var cookie = window.ark_jQuery.cookie('arkArenaAbTestVariationSelected');
if (cookie) {
    window.ark_jQuery.cookie('arkArenaAbTestVariationSelected', cookie, { path: "/", expires: 365 });
}

window.loginManager = {
    login: function() {
        masterViewGlobals.loginFunction();
    }
}

ark_jQuery(document).ready(function () {
    arkPage.user.updateUserInfoFromServer();
});

function parseGaParams(parameters) {
    var params = {};
    var keyvaluestring = parameters.split('&');
    for (var i = 0; i < keyvaluestring.length; i++) {
        var param = keyvaluestring[i].split('=');
        params[param[0]] = param[1];
    }
    return params;
}

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 () {
    var arknewgaparams = ark_jQuery.cookie("arkadaptparams");
    ark_jQuery.cookie("arkadaptparams", null, { expiry: -1000, path: '/' });
    if (arknewgaparams != null) {
        arkPage.Params = parseGaParams(arknewgaparams);
    }

    arkPage.Params = new Object();
    arkPage.Params['Page'] = masterViewGlobals.pageName;
    if (typeof (contentId) != "undefined")
    {
        arkPage.Params['Game'] = contentId;
        arkPage.Params['ContentSource'] = masterViewGlobals.contentSource || 'Arkadium';
    }

    arkPage.Params['ContentType'] = masterViewGlobals.contentType || 'game';

    var prevGame = ark_jQuery.cookie('arkseq')
    if (typeof prevGame == "string" && prevGame.length > 0) {
        arkPage.Params['PrevGame'] = prevGame;
    }
    var refUrl = document.location.href;
    if (document.referrer != "" && document.referrer.toLowerCase().indexOf("refsource") > 0) refUrl = document.referrer;
    arkPage.Params['Referral'] = refUrl;
    arkPage.Params['DeviceType'] = masterViewGlobals.deviceType;
})();

function setParentIframeHeight() {
    var height = ark_jQuery(document).height();
    parent.postMessage("event=changeHeight&height=" + height, "*");
}

function sleep(ms) {
    ms += new Date().getTime();
    while (new Date() < ms) {
    }
}

function removeParam(key, sourceURL) {
    var rtn = sourceURL.split("?")[0],
        param,
        params_arr = [],
        queryString = (sourceURL.indexOf("?") !== -1) ? sourceURL.split("?")[1] : "";
    if (queryString !== "") {
        params_arr = queryString.split("&");
        for (var i = params_arr.length - 1; i >= 0; i -= 1) {
            param = params_arr[i].split("=")[0];
            if (param === key) {
                params_arr.splice(i, 1);
            }
        }
        rtn = rtn + "?" + params_arr.join("&");
    }
    return rtn;
}

ark_jQuery(document).ready(
    function () {
        if (ark_jQuery.cookie("ark_begin_session") == null) {
            ark_jQuery.cookie("ark_begin_session", true, { path: '/' });
        }

        var modules = ark_jQuery('.ark-container').find('ark-grid[arkmodulekey]');
        var moduleVisualIndex = 0;
        for (var i = 0; i < modules.length; i++) {
            if (ark_jQuery(modules[i]).attr('arkmodulekey') != "Container") {
                moduleVisualIndex = moduleVisualIndex + 1;
                var links = ark_jQuery(modules[i]).find('a[href]');
                for (var index = 0; index < links.length; index++) {
                    var domHrefElement = ark_jQuery(links[index]);
                    domHrefElement.attr('parentarkmodulekey', ark_jQuery(modules[i]).attr('arkmodulekey'));
                    domHrefElement.attr('parentarkmodulesorttype', ark_jQuery(modules[i]).attr('arkmodulesorttype'));
                    domHrefElement.attr('parentarkmodulescreenposition', moduleVisualIndex);
                    domHrefElement.attr('originmodpos', index + 1);
                    domHrefElement.on("mousedown touch", function (e) {
                        var currentElementItem = ark_jQuery(this);
                        var modulekey = currentElementItem.attr('parentarkmodulekey');
                        var modulesorttype = currentElementItem.attr('parentarkmodulesorttype');
                        var modulescreenposition = currentElementItem.attr('parentarkmodulescreenposition');
                        var modulelinkposition = currentElementItem.attr('OriginModPos');
                        var buttonname = currentElementItem.attr('data-buttonname');
                        var gaparams = 'ModuleScreenPosition=' + modulescreenposition + '&' +
                            'OriginPage=' + masterViewGlobals.pageName + '&' +
                            'OriginModPos=' + modulelinkposition;

                        if (typeof arkPage.game != "undefined" && typeof arkPage.game.externalGameId != "undefined" && arkPage.game.externalGameId.length > 0) {
                            gaparams = gaparams + '&OriginGame=' + arkPage.game.externalGameId;
                        }
                        if (typeof buttonname == "string" && buttonname.length > 0) {
                            gaparams = gaparams + '&ButtonName=' + buttonname;
                        }
                        if (typeof modulesorttype == "string" && modulesorttype.length > 0) {
                            gaparams = gaparams + '&OriginModule=' + modulesorttype;
                        } else {
                            gaparams = gaparams + '&OriginModule=' + modulekey;
                        }

                        var date = new Date();
                        var minutes = 1;
                        date.setTime(date.getTime() + (minutes * 60 * 1000));
                        ark_jQuery.cookie("arkadaptparams", gaparams, { expires: date, path: '/' });
                    });
                }
            }
        }
        ark_jQuery('.change-width-block').parent().addClass('backColorGrid');
    });

ark_jQuery(document).ready(function () {
    if (arkPage.user.isActive) {
        ark_jQuery('.ark-logOut').show();
    } else {
        ark_jQuery('.ark-logOut').hide();
    }
    ark_jQuery('#bookmarkme').click(function () {
        var i = navigator.userAgent.toLowerCase();
        var r = { win: /windows/.test(i), xp: /windows nt 5.1/.test(i) || /windows nt 5.2/.test(i), osx: /os x/.test(i), chb: /chrome/.test(i) && parseInt(/chrome\/(.+?)\./.exec(i).pop(), 10) > 13, chr: /chrome/.test(i) && !/rockmelt/.test(i), cho: /chrome\/(1[2345678]|2\d)/.test(i), iph: /iphone/.test(i) || /ipod/.test(i), dro: /android/.test(i), wph: /windows phone/.test(i), ipa: /ipad/.test(i), saf: /safari/.test(i) && !/chrome/.test(i), opr: /opera/.test(i), ffx: /firefox/.test(i), ff2: /firefox\/2/.test(i), ffn: /firefox\/((3.[6789][0-9a-z]*)|(4.[0-9a-z]*))/.test(i), ie6: /msie 6.0/.test(i), ie7: /msie 7.0/.test(i), ie8: /msie 8.0/.test(i), ie9: /msie 9.0/.test(i), ie10: /msie 10.0/.test(i), ie11: /trident\/7.0/.test(i), msi: /msie/.test(i) && !/opera/.test(i), mob: /(iphone|ipod|ipad|android|mobi|blackberry|opera mini|silk)/.test(i) };
        var k = "Press <" + (r["win"] ? "Control" : "Command") + ">+D to bookmark in ";
        var v = location.href;
        var w = document.title;
        r["ipa"] ? alert("Tap the <plus> to bookmark in Safari") : r["saf"] || r["chr"] ? alert(k + (r["chr"] ? "Chrome" : "Safari")) : r["opr"] ? alert(k + "Opera") : r["ie11"] ? alert(k + "InternetExplorer") : r["ffx"] && !window.sidebar.addPanel ? alert(k + "Firefox") : document.all ? window.external.AddFavorite(v, w) : window.sidebar.addPanel(w, v, "");

    });

    ark_jQuery(".arena-wrapper img").each(
        function () {
            ark_jQuery(this).error(function () {
                var currentElement = ark_jQuery(this);
                currentElement.attr("oldsrc", currentElement.attr("src"));
                if (currentElement.attr("src").indexOf('150x150') > -1) {
                    currentElement.attr("src", arkPage.arena.siteBaseUrl + '/Content/Images/default/150x150_gameicon.jpg');
                } else {
                    if (currentElement.attr("src").indexOf('300x300') > -1) {
                        currentElement.attr("src", arkPage.arena.siteBaseUrl + '/Content/Images/default/300x300_gameicon.jpg');
                    } else {
                        if (currentElement.attr("src").indexOf('600x600') > -1 || currentElement.attr("src").indexOf('640x295') > -1) {
                            currentElement.attr("src", arkPage.arena.siteBaseUrl + '/Content/Images/default/600x600_gameicon.jpg');
                        } else {
                            currentElement.attr("src", arkPage.arena.siteBaseUrl + '/Content/Images/default/75x75_gameicon.jpg');
                        }
                    }
                }
                currentElement.attr("style", 'border:1px');
            }).attr("src", ark_jQuery(this).attr("src"));
        });

    if (arkPage.arena.inIframe) {
        setParentIframeHeight();

        var topUrl = removeParam("arkpath", document.referrer);
        var separatop = topUrl.indexOf("?") > 0 ? "&" : "?";
        ark_jQuery("#titleUrl").attr("href", "#");
        ark_jQuery("#titleUrl").attr("onclick", "parent.postMessage('event=changeUrl&url=" + encodeURIComponent(topUrl + separatop + "arkpath=/") + "', '*');");
        ark_jQuery(".arena-logo").attr("href", "#");
        ark_jQuery(".arena-logo").attr("onclick", "parent.postMessage('event=changeUrl&url=" + encodeURIComponent(topUrl + separatop + "arkpath=/") + "', '*');");

        ark_jQuery("a").each(
             function () {
                 try {
                     var currentElement = ark_jQuery(this);
                     if (currentElement.attr("data-buttonname") != "Twitter-twitt") {
                         var aHref = currentElement.attr("href");
                         var positionIndex = aHref.indexOf("category") > 0 ? aHref.indexOf("category") : aHref.indexOf("games/") > 0 ? aHref.indexOf("games/") : aHref.indexOf("gamedetails") > 0 ? aHref.indexOf("gamedetails") : aHref.indexOf("QuizDetails") > 0 ? aHref.indexOf("QuizDetails") : aHref.indexOf("quiz/") > 0 ? aHref.indexOf("quiz/") : aHref.indexOf("YouMayAlsoLike/") > 0 ? aHref.indexOf("YouMayAlsoLike/") : 0;
                         if (positionIndex > 0 || positionIndex > 0 || positionIndex > 0) {
                             var subUrl = "arkpath=/" + aHref.substring(positionIndex, aHref.length);

                             currentElement.attr("href", "#");
                             currentElement.attr("onclick", "parent.postMessage('event=changeUrl&url=" + encodeURIComponent(topUrl + separatop + subUrl) + "', '*');");
                         }
                     }
                 } catch (err) { }
             }
         );

        if (document.referrer.indexOf(arkPage.arena.siteBaseUrl) == 0) {
            document.location.href = 'http://comicskingdom.com/puzzlespalace';  //todo: move to settings
        }
    }

});

if (window.addEventListener) {
    window.addEventListener('load', function() {
        if (arkPage.arena.inIframe) {
            setParentIframeHeight();
        }
    }, false);

} else {
    window.attachEvent('onload', function() {
        if (arkPage.arena.inIframe) {
            setParentIframeHeight();
        }
    });
}


function hasRetinaDisplay() {
    return !!(isIOS() && window.devicePixelRatio && window.devicePixelRatio > 1);
}

function isIOS() {
    return (navigator.userAgent.match(/(iPad|iPhone|iPod)/i) ? true : false);
}

var cookieValHasRetinaDisplay = ark_jQuery.cookie('hasRetinaDisplay');
if (cookieValHasRetinaDisplay == null && cookieValHasRetinaDisplay == "") {
    var isHasRetinaDisplay = hasRetinaDisplay();
    ark_jQuery.cookie('hasRetinaDisplay', isHasRetinaDisplay);
}

if (window.addEventListener) {
    window.addEventListener('message', receiveMSG, false);
} else {
    window.attachEvent('onmessage', receiveMSG);
}

function receiveMSG(eventString) {
    var str = eventString.data;
    var data = str.toString().split('&');
    var event = data[0].split('=')[1];
    if (event == 'getHeight') {
        setParentIframeHeight();
    }
    if (event == 'game_end') {
        if (ark.handleMessageFromGame) {
            ark.handleMessageFromGame(eventString.data)
        }
    }
}

ark_jQuery(document).ready(function () {
    ark_jQuery('.arena-more, .arena-more__title').on('click', function (e) {
        var selectedType = '';
        var thisElement = ark_jQuery(this);
        var modulesorttype = thisElement.attr('parentarkmodulesorttype');
        var modulekey = thisElement.attr('parentarkmodulekey');
        var originmodpos = thisElement.attr('originmodpos');
        var buttonname = thisElement.attr('data-buttonname');
        if (typeof modulesorttype == "string" && modulesorttype.length > 0) {
            selectedType = modulesorttype;
        } else {
            selectedType = modulekey;
        }
        ark.storage().setItem("more", buttonname);
    });
    cutDescription();
    setParentIframeHeight();

    if (arkPage.arena.inIframe) {
        ark.addListener("arkGameStartEvent", function () {
            setTimeout(function () {
                setParentIframeHeight();
            }, 3000);
        });
    }

    if (arkPage.arena.device === "pc") {
        ark_jQuery("body").addClass("arena-page-body-on-pc");
    }
});

ark.addListener(ark.analytic_social_button_click_event, function (buttonName) {
    if ((buttonName == 'fb-like' || buttonName == 'fb-comment' || buttonName == 'fb-share')) {
        ark_jQuery('.ark-logOut').show();
    }
});

ark.addListener('ark:login', function (e) {
    ark_jQuery('.ark-logOut').show();
    ark_jQuery('.arena-post-score').hide();
    ShowUserElements();
});

ark.addListener('ark:logout', function (e) {
    ark_jQuery('.ark-logOut').hide();
    if (arkGaVirtualPages.part1 != "game end") {
        ark_jQuery('.arena-post-score').show();
    }
    HideUserElements();
});

function fbLogOut(event) {
    var iframe = document.getElementById('arkIsolationIframe');
    if (iframe) {
        iframe.contentWindow.postMessage({ action: "arkLogout" }, "*");
    }
    arkPage.user.isActive = false;
    arkPage.user.logout();
    HideUserElements();
}

function HideUserElements() {
    /*var root = document.querySelector('ark-grid[arkmodulesorttype="RecentlyPlayed"]');
    if (root) {
        ark_jQuery(root).hide();
    }
    var menuItem = document.querySelector('ark-li[menu-item="RecentlyPlayed"]');
    if (menuItem) {
        ark_jQuery(menuItem).hide();
    }*/
    var loginLink = document.querySelector('a[data-buttonname="SignIn"]');
    if (loginLink) {
        ark_jQuery(loginLink).hide();
    }
    var SignInOnGameEndLink = document.querySelector('a[data-buttonname="SignInOnGameEnd"]');
    if (SignInOnGameEndLink) {
        ark_jQuery(loginLink).show();
    }
}

function ShowUserElements() {
    /*var root = document.querySelector('ark-grid[arkmodulesorttype="RecentlyPlayed"]');
    if (root) {
        ark_jQuery(root).show();
    }
    var menuItem = document.querySelector('ark-li[menu-item="RecentlyPlayed"]');
    if (menuItem) {
        ark_jQuery(menuItem).show();
    }*/
    var loginLink = document.querySelector('a[data-buttonname="SignIn"]');
    if (loginLink) {
        ark_jQuery(loginLink).show();
    }
    var SignInOnGameEndLink = document.querySelector('a[data-buttonname="SignInOnGameEnd"]');
    if (SignInOnGameEndLink) {
        ark_jQuery(loginLink).hide();
    }
}

window.twttr = (function (d, s, id) {
    var curUrl = arkPage.arena.inIframe ? document.referrer : document.location.href;
    curUrl += curUrl.indexOf("?") > 0 ? "&" : "?";
    curUrl += "refSource=twit-share";

    var href = 'https://twitter.com/intent/tweet?url=' + curUrl + '&lang=' + masterViewGlobals.language;

    ark_jQuery(".twitter-share-button").attr('href', href);
    ark_jQuery("#shareOnTwitterButton").attr('href', href);

    var t, js, fjs = d.getElementsByTagName(s)[0];
    if (d.getElementById(id)) {
        return
    }
    js = d.createElement(s);
    js.id = id;
    js.src = "//platform.twitter.com/widgets.js";
    fjs.parentNode.insertBefore(js, fjs);
    return window.twttr || (t = { _e: [], ready: function (f) { t._e.push(f) } })
}(document, "script", "twitter-wjs"));

ark_jQuery(document).ready(function () {

    function getSearchQueryParam(qstr) {
        qstr = qstr.replace("?", "");
        var query = {};
        var a = qstr.split('&');
        for (var i = 0; i < a.length; i++) {
            var b = a[i].split('=');
            query[decodeURIComponent(b[0])] = b[1] || '';
        }
        return query;
    }
    var showpopupEncoded = getSearchQueryParam(document.location.search)["showpopup"];
    var showpopup = decodeURIComponent(showpopupEncoded);
    if (showpopup && showpopup != "undefined") {
        var loc = window.location;
        if (history && "pushState" in history) {
            history.pushState("", document.title, loc.pathname + loc.search.replace("&showpopup=" + showpopupEncoded, "").replace("?showpopup=" + showpopupEncoded, ""));
        }
        ark_jQuery("#redirectMessage").text(showpopup);
        ark_Popup.open('RedirectMessage');
        setTimeout(function () { ark_Popup.close('RedirectMessage'); }, 20 * 1000);
    }
});

var filesForSend = [];

function Ark_checkContactForm() {
    //ark_jQuery(".arena-form-buttons").children().attr("style", "display: none !important");
    //ark_jQuery(".arena-form-buttons").addClass("loading");
    var mail = {};

    if (ark_jQuery("#varName").val().length > 0) {
        mail.user = encodeURI(ark_jQuery("#varName").val());
    } else {
        ark_jQuery("#varName").focus();
        overRequest(ark_jQuery("#varName").data('text'), "varName");
        return;
    }
    if (validateEmail(ark_jQuery("#varEmail").val())) {
        mail.userEmail = encodeURI(ark_jQuery("#varEmail").val());
    } else {
        ark_jQuery("#varEmail").focus();
        overRequest(ark_jQuery("#varEmail").data('text'), "varEmail");
        return;
    }
    var list = document.getElementById("varSubject");
    if (ark_jQuery(list).val().length > 0) {
        if (list.options[list.selectedIndex].getAttribute("data-extra-field") == "otherSubject") {
            var othersubj = document.getElementById("otherSubject");
            if (othersubj.value.length > 0) {
                mail.Subject = encodeURI(othersubj.value);
            } else {
                othersubj.focus();
                overRequest(ark_jQuery('#otherSubject').data('text'), "otherSubject");
                return;
            }
        }
        else { mail.Subject = encodeURI(ark_jQuery(list).val()); }
    } else {
        ark_jQuery("#varSubject").focus();
        overRequest(ark_jQuery("#otherSubject").data('text'), "otherSubject");
        return;
    }
    if (ark_jQuery("#billing-items").length > 0) {
        mail.billingItems = encodeURI(ark_jQuery("#billing-items").val());
    }
    if (ark_jQuery("#varMessage").val().length > 0) {
        mail.Message = encodeURI(ark_jQuery("#varMessage").val());
    } else {
        ark_jQuery("#varMessage").focus();
        overRequest(ark_jQuery("#varMessage").data('text'), "varMessage");
        return;
    }
    mail.files = filesForSend;
    if (ark_jQuery("#recaptcha_response_field").val().length > 0) {
        mail.recaptchaResponse = encodeURI(ark_jQuery("#recaptcha_response_field").val());
    } else {
        ark_jQuery("#recaptcha_response_field").focus();
        overRequest(ark_jQuery("#conactus_recapcha").data('text'));
        return;
    }

    var clientData = getClientData();

    mail.recaptchaChallenge = ark_jQuery("#recaptcha_challenge_field").val();
    mail.flashversion = encodeURI(clientData.flashVersion);
    mail.userAgent = encodeURI(clientData.browser + ' ' + clientData.browserMajorVersion + ' (' + clientData.browserVersion + ')');
    mail.clientOs = encodeURI(clientData.os + ' (' + clientData.osVersion + ')');
    mail.siteBaseUrl = encodeURI(arkPage.arena.siteBaseUrl);
    if (arkPage.user.isActive) {
        mail.userInfo = encodeURI(arkPage.user.id + ";" + arkPage.user.name + ";" + arkPage.user.email + ";" + arkPage.user.session + ";" + arkPage.arena.localization);
    } else {
        mail.userInfo = encodeURI("Guest");
    }
    mail.location = document.location.href;
    sendMail(mail);
}

function getClientData() {
    var unknown = '-';

    // screen
    var screenSize = '', width, height;
    if (screen.width) {
        width = (screen.width) ? screen.width : '';
        height = (screen.height) ? screen.height : '';
        screenSize += '' + width + " x " + height;
    }

    // browser
    var nVer = navigator.appVersion;
    var nAgt = navigator.userAgent;
    var browser = navigator.appName;
    var version = '' + parseFloat(navigator.appVersion);
    var majorVersion = parseInt(navigator.appVersion, 10);
    var nameOffset, verOffset, ix;

    // Opera
    if ((verOffset = nAgt.indexOf('Opera')) != -1) {
        browser = 'Opera';
        version = nAgt.substring(verOffset + 6);
        if ((verOffset = nAgt.indexOf('Version')) != -1) {
            version = nAgt.substring(verOffset + 8);
        }
    }
    // Opera Next
    if ((verOffset = nAgt.indexOf('OPR')) != -1) {
        browser = 'Opera';
        version = nAgt.substring(verOffset + 4);
    }
        // MSIE
    else if ((verOffset = nAgt.indexOf('MSIE')) != -1) {
        browser = 'Microsoft Internet Explorer';
        version = nAgt.substring(verOffset + 5);
    }
        // Chrome
    else if ((verOffset = nAgt.indexOf('Chrome')) != -1) {
        browser = 'Chrome';
        version = nAgt.substring(verOffset + 7);
    }
        // Safari
    else if ((verOffset = nAgt.indexOf('Safari')) != -1) {
        browser = 'Safari';
        version = nAgt.substring(verOffset + 7);
        if ((verOffset = nAgt.indexOf('Version')) != -1) {
            version = nAgt.substring(verOffset + 8);
        }
    }
        // Firefox
    else if ((verOffset = nAgt.indexOf('Firefox')) != -1) {
        browser = 'Firefox';
        version = nAgt.substring(verOffset + 8);
    }
        // MSIE 11+
    else if (nAgt.indexOf('Trident/') != -1) {
        browser = 'Microsoft Internet Explorer';
        version = nAgt.substring(nAgt.indexOf('rv:') + 3);
    }
        // Other browsers
    else if ((nameOffset = nAgt.lastIndexOf(' ') + 1) < (verOffset = nAgt.lastIndexOf('/'))) {
        browser = nAgt.substring(nameOffset, verOffset);
        version = nAgt.substring(verOffset + 1);
        if (browser.toLowerCase() == browser.toUpperCase()) {
            browser = navigator.appName;
        }
    }

    if ((ix = version.indexOf(';')) != -1) version = version.substring(0, ix);
    if ((ix = version.indexOf(' ')) != -1) version = version.substring(0, ix);
    if ((ix = version.indexOf(')')) != -1) version = version.substring(0, ix);

    majorVersion = parseInt('' + version, 10);
    if (isNaN(majorVersion)) {
        version = '' + parseFloat(navigator.appVersion);
        majorVersion = parseInt(navigator.appVersion, 10);
    }

    var mobile = /Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(nVer);

    var cookieEnabled = !!(navigator.cookieEnabled);

    if (typeof navigator.cookieEnabled == 'undefined' && !cookieEnabled) {
        document.cookie = 'testcookie';
        cookieEnabled = (document.cookie.indexOf('testcookie') != -1);
    }

    var os = unknown;
    var clientStrings = [
        { s: 'Windows 10', r: /(Windows 10.0|Windows NT 10.0)/ },
        { s: 'Windows 8.1', r: /(Windows 8.1|Windows NT 6.3)/ },
        { s: 'Windows 8', r: /(Windows 8|Windows NT 6.2)/ },
        { s: 'Windows 7', r: /(Windows 7|Windows NT 6.1)/ },
        { s: 'Windows Vista', r: /Windows NT 6.0/ },
        { s: 'Windows Server 2003', r: /Windows NT 5.2/ },
        { s: 'Windows XP', r: /(Windows NT 5.1|Windows XP)/ },
        { s: 'Windows 2000', r: /(Windows NT 5.0|Windows 2000)/ },
        { s: 'Windows ME', r: /(Win 9x 4.90|Windows ME)/ },
        { s: 'Windows 98', r: /(Windows 98|Win98)/ },
        { s: 'Windows 95', r: /(Windows 95|Win95|Windows_95)/ },
        { s: 'Windows NT 4.0', r: /(Windows NT 4.0|WinNT4.0|WinNT|Windows NT)/ },
        { s: 'Windows CE', r: /Windows CE/ },
        { s: 'Windows 3.11', r: /Win16/ },
        { s: 'Android', r: /Android/ },
        { s: 'Open BSD', r: /OpenBSD/ },
        { s: 'Sun OS', r: /SunOS/ },
        { s: 'Linux', r: /(Linux|X11)/ },
        { s: 'iOS', r: /(iPhone|iPad|iPod)/ },
        { s: 'Mac OS X', r: /Mac OS X/ },
        { s: 'Mac OS', r: /(MacPPC|MacIntel|Mac_PowerPC|Macintosh)/ },
        { s: 'QNX', r: /QNX/ },
        { s: 'UNIX', r: /UNIX/ },
        { s: 'BeOS', r: /BeOS/ },
        { s: 'OS/2', r: /OS\/2/ },
        { s: 'Search Bot', r: /(nuhk|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask Jeeves\/Teoma|ia_archiver)/ }
    ];
    for (var id in clientStrings) {
        var cs = clientStrings[id];
        if (cs.r.test(nAgt)) {
            os = cs.s;
            break;
        }
    }

    var osVersion = unknown;

    if (/Windows/.test(os)) {
        osVersion = /Windows (.*)/.exec(os)[1];
        os = 'Windows';
    }

    switch (os) {
        case 'Mac OS X':
            osVersion = /Mac OS X (10[\.\_\d]+)/.exec(nAgt)[1];
            break;

        case 'Android':
            osVersion = /Android ([\.\_\d]+)/.exec(nAgt)[1];
            break;

        case 'iOS':
            osVersion = /OS (\d+)_(\d+)_?(\d+)?/.exec(nVer);
            osVersion = osVersion[1] + '.' + osVersion[2] + '.' + (osVersion[3] | 0);
            break;
    }

    var flashVersion = 'no check';
    if (typeof swfobject != 'undefined') {
        var fv = swfobject.getFlashPlayerVersion();
        if (fv.major > 0) {
            flashVersion = fv.major + '.' + fv.minor + ' r' + fv.release;
        }
        else {
            flashVersion = unknown;
        }
    }

    return {
        screen: screenSize,
        browser: browser,
        browserVersion: version,
        browserMajorVersion: majorVersion,
        mobile: mobile,
        os: os,
        osVersion: osVersion,
        cookies: cookieEnabled,
        flashVersion: flashVersion
    };
}

function getFlashVersion() {
    try {
        try {
            var axo = new ActiveXObject('ShockwaveFlash.ShockwaveFlash.6');
            try { axo.AllowScriptAccess = 'always'; }
            catch (e) { return '6,0,0'; }
        } catch (e) { }
        return new ActiveXObject('ShockwaveFlash.ShockwaveFlash').GetVariable('$version').replace(/\D+/g, ',').match(/^,?(.+),?$/)[1];
    } catch (e) {
        try {
            if (navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin) {
                return (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]).description.replace(/\D+/g, ",").match(/^,?(.+),?$/)[1];
            }
        } catch (e) { }
    }
    return '0,0,0';
}
function overRequest(message, field) {
    ark_jQuery(".arena-field-required-warning").text("");
    if (field != undefined) {
        ark_jQuery("#" + field + " + .arena-field-required .arena-field-required-warning").text(message);
    } else {
        console.log('error. contact us message was not sent.')
    }
    ReloadRecaptcha("focusoff");
}

function validateEmail(email) {
   var re = masterViewGlobals.regValidateContactUs;
   return re.test(email);
}

function sendMail(data) {
    var url = arkPage.arena.siteBaseUrl + "/Services/Support.ashx";
    var dataJson = JSON.stringify(data).replace("\"[", "[").replace("]\"", "]").replace(/\\\"/g, '"');
    ark_jQuery.ajax({
        type: "POST",
        url: url,
        data: { json: dataJson },
        success: function (result) {
            overRequest(result);
            ark_jQuery("#ARK_popup_ContactUs .ark_subtitle.arena-message-result").text(result).show();
            ark_jQuery("#ARK_popup_ContactUs .arena-ContactUs").hide();
        },
        error: function (result) {
            if (result.status == 403) {
                overRequest(result.responseText);
            }
            else { overRequest("something went wrong please try again later."); }
        }
    });
}

function FileUpload() {
    for (var i = 0, f; f = filesForSend[i]; i++) {
        document.getElementById('output-list').innerHTML = "";
        // Only process image files.
        if (!f.type.match('image.*')) {
            continue;
        }

        var reader = new FileReader();

        // Closure to capture the file information.
        reader.onload = (function (theFile) {
            return function (e) {
                theFile["userImgBase64"] = e.target.result;
                theFile["userfilelastModifiedDate"] = e.target.name;
                theFile["userfilename"] = e.target.name;
                theFile["userfiletype"] = e.target.type;
                theFile["userfilesize"] = e.target.size;

                // Render thumbnail.

                var span = document.createElement('span');
                span.innerHTML = ['<img src="', e.target.result,
                    '" title="', encodeURI(theFile.name), '" style="width:100px;"/>'].join('');
                document.getElementById('output-list').insertBefore(span, null);
            };
        })(f);

        reader.readAsDataURL(f);
    }
}

function handleFileSelect(evt) {
    ark_jQuery(".arena-ContactUs .arena-file_upload").removeClass("active");
    evt.stopPropagation();
    evt.preventDefault();

    var files = evt.dataTransfer.files; // FileList object.

    // files is a FileList of File objects. List some properties.
    var output = [];
    var totalSize = 0;
    for (var i = 0, f; f = files[i]; i++) {
        output.push('<li><strong>', encodeURI(f.name), '</strong> (', f.type || 'n/a', ') - ',
            f.size, ' bytes, last modified: ',
            f.lastModifiedDate.toLocaleDateString(), '</li>');
        totalSize += f.size;
        filesForSend.push(f);
    }
    if (!handleFileSizeLimit(totalSize)) {
        filesForSend.pop();
        return;
    }
    FileUpload();
}

function handleFileSelectInput(evt) {
    var files = evt.target.files; // FileList object

    // files is a FileList of File objects. List some properties.
    var output = [];
    var totalSize = 0;
    for (var i = 0, f; f = files[i]; i++) {
        output.push('<li><strong>', encodeURI(f.name), '</strong> (', f.type || 'n/a', ') - ',
            f.size, ' bytes, last modified: ',
            f.lastModifiedDate.toLocaleDateString(), '</li>');
        totalSize += f.size;
        filesForSend.push(f);
    }
    if (!handleFileSizeLimit(totalSize)) {
        filesForSend.pop();
        return;
    }
    FileUpload();
}

function handleDragOver(evt) {
    evt.stopPropagation();
    evt.preventDefault();
    evt.dataTransfer.dropEffect = 'copy'; // Explicitly show this is a copy.
}

function handleFileSizeLimit(fileSize) {
    var result = fileSize < 20971520;
    if (!result) {
        overRequest("Total size of files are out of 20 MB");
    }
    return result;
}

function checkMultipleProp() {
    return !!("multiple" in document.createElement("input"));
}

// Setup the dnd listeners.
var dropZone = document.getElementById('drop_zone');
ark_jQuery(dropZone).on(
    'dragover', handleDragOver).on(
        'dragenter', function () { ark_jQuery(".arena-ContactUs .arena-file_upload").addClass("active"); }).on(
            'dragleave', function () { ark_jQuery(".arena-ContactUs .arena-file_upload").removeClass("active"); }).on(
                'drop', handleFileSelect).on(
                    'change', handleFileSelectInput);
if (!checkMultipleProp()) {
    ark_jQuery(dropZone).parent().addClass("notSupportDragDrop");
}

ark.addListener('ARK_PopUp_ContactUs:EventOpen', function () {
    ark_jQuery("#ARK_popup_ContactUs .arena-ContactUs").show();
    ark_jQuery("#ARK_popup_ContactUs .ark_subtitle.arena-message-result").text("").hide();
    GenerateRecaptcha("conactus_recapcha", null, function () { ark_jQuery("#varName").focus(); });
    ark_jQuery("#varSubject").trigger("change");
    //overRequest("");
});

ark_jQuery("#varSubject").on("change", function () {
    ark_jQuery("#otherSubject + .arena-field-required .arena-field-required-warning").text("");
    var item = this.options[this.selectedIndex].getAttribute("data-extra-field");
    ark_jQuery(".optionalField").hide();
    ark_jQuery("#otherSubject").removeAttr("required");
    if (item != undefined && item != "") {
        ark_jQuery("." + item).show();
        if (item == "otherSubject") {
            ark_jQuery("#otherSubject").attr("required", "required");
        }
    }
});
ark.addListener('ARK_PopUp_ContactUs:EventClose', function () {
    ark_jQuery('#ARK_popup_ContactUs form')[0].reset();
    ark_jQuery(".optionalField").hide();
    ark_jQuery("#output-list").html("");
    filesForSend = [];
    DestroyRecaptcha();
});
ark_jQuery(document).ready(function () {
    var articlesAmount = ark_jQuery('.blog-block-column').length;
    var blockBlog = ark_jQuery('.blog-block');
    var minHeightBlock, maxHeightBlock;

    function setBlogHeight() {
        maxHeightBlock = ark_jQuery('.innerBlog').outerHeight();
        var arrayBlogHeight = [];
        ark_jQuery('.blog-block-column').each(function () {
            arrayBlogHeight.push(ark_jQuery(this).outerHeight());
        });
        var maxBlogHeight = [];
        for (var i = 0; i < 2; i++) {
            maxBlogHeight.push(arrayBlogHeight[i]);
        }
        var maxBlogHeightNum = Math.max.apply(Math, maxBlogHeight);
        minHeightBlock = maxBlogHeightNum + 'px';
        blockBlog.css('height', minHeightBlock);
        ark_jQuery('.arena-blog-arrow').removeClass('rotateArrow');
    }

    setBlogHeight();
    ark_jQuery(window).resize(setBlogHeight);

    ark_jQuery('.arena-blog-arrow').on('click', function () {
        blockBlog.toggleClass('opendBlog');
        if (blockBlog.hasClass('opendBlog')) {
            ark_jQuery(blockBlog).css('height', maxHeightBlock);
            ark_jQuery('.arena-blog-arrow').addClass('rotateArrow');
        }
        else {
            ark_jQuery(blockBlog).css('height', minHeightBlock);
            ark_jQuery('.arena-blog-arrow').removeClass('rotateArrow');
        }
    });
});
window.arkExternalApiCommunicator = {
    _userId: null,
    _sessionStart: null,
    _gameId: null,
    _avgGameRevenue: 0.0,
    _adsEvents: [],

    _callbackPeriodSeconds: window.userActivityCallbackPeriod || 30,
    _eventPeriodSeconds: window.externalApiEventPeriod || 30,
    _gameStarted: false,
    _gameEnded: false,
    _callbackTimeoutId: 0,
    _eventIntervalId: 0,
    _gameplayStartDateTime: null,
    _html5OverlayTimeoutId: 0,
    _gameEndHandled: false,

    overallGameplayTime: 0,

    init: function () {
        this._getUserIp();
        this._sessionStart = new Date();
        this._gameId = arkPage.game.externalGameId;
        this._userId = this._getUserId();
        this._initListeners();
        this._loadGameRevenue();
    },

    reinit: function () {

        this._userId = null;

        this._sessionStart = null;
        this._avgGameRevenue = 0.0;
        this._adsEvents = [];

        this._callbackPeriodSeconds = window.userActivityCallbackPeriod || 30;
        this._eventPeriodSeconds = window.externalApiEventPeriod || 30;
        this._gameStarted = false;
        this._gameEnded = false;
        this._killCallbacks();

        this._gameEndHandled = false;
        this.overallGameplayTime = 0;
        
        this._gameplayStartDateTime = null;
        this._sessionStart = new Date();
        this._gameId = arkPage.game.externalGameId;
        this._userId = this._getUserId();
        this._loadGameRevenue();
    },
    _getUserIp: function () {
        var url = '/manage/GetUserIp/';
        ark_jQuery.get(url)
            .done(function (res) {
                try {
                    arkPage.arena.userIP = res;
                } catch (e) {
                }
            });
    },
    _killCallbacks: function () {
        if (this._callbackTimeoutId) {
            clearInterval(this._callbackTimeoutId);
            this._callbackTimeoutId = 0;
        }

        if (this._eventIntervalId) {
            clearInterval(this._eventIntervalId);
            this._eventIntervalId = 0;
        }

        if (this._html5OverlayTimeoutId) {
            clearTimeout(this._html5OverlayTimeoutId);
            this._html5OverlayTimeoutId = 0;
        }
    },

    _initListeners: function () {

        ark.addListener("game_scores_ready",
            function (obj) {
                if (!window.arkExternalApiCommunicator._gameEnded) {
                    window.arkExternalApiCommunicator._gameEndHandled = true;
                    window.arkExternalApiCommunicator.stopGame(obj);
                }
            });

        ark.addListener("arkContentEndEvent",
            function () {
                window.ark_jQuery("ark-div.game-over-button").hide();
                window.arkExternalApiCommunicator._disableTimeBasedEvent();
            });

        ark.addListener("arkGaOnEventSending",
            function (data) {
                var event = data.data;
                if ((event.eventCategory.indexOf("Roll_End") !== -1 || event.eventCategory.indexOf("OnPageDisp") !== -1) &&
                    window.arkExternalApiCommunicator._adsEvents.indexOf(event) === -1) {
                    window.arkExternalApiCommunicator._adsEvents.push(event);
                }
            });


        ark.addListener('arkContentStartEvent', function () {
            window.ark_jQuery("ark-div.game-over-button").show();
            window.arkExternalApiCommunicator._gameplayStartDateTime = new Date();
            window.arkExternalApiCommunicator._gameStarted = true;
            window.ark_jQuery(document).on('touch touchstart touchend click mousemove keypress keydown keyup', function () {
                window.arkExternalApiCommunicator.refreshActivityCallback();
            });

            if (window.addEventListener) {
                window.addEventListener('message', window.arkExternalApiCommunicator.handleMessageFromGame, false);
            } else {
                window.attachEvent('onmessage', window.arkExternalApiCommunicator.handleMessageFromGame);
            }
            ;
            window.arkExternalApiCommunicator.refreshActivityCallback();
            window.arkExternalApiCommunicator._setTimeBasedEvent();
        });

    },

    handleMessageFromGame: function (msg) {
        try {
            var eventObj = ark.makeEventObject(msg);
            if (eventObj.name && eventObj.name !== '') {
                window.arkExternalApiCommunicator.refreshActivityCallback()
            }
        } catch (ex) {
        }
        ;
    },

    _setTimeBasedEvent: function () {
        this._eventIntervalId = setInterval(function () {
                var adsServed = window.arkExternalApiCommunicator._processAdsEvents();
                var resObj = {
                    uid: window.arkExternalApiCommunicator._userId,
                    user_ip: arkPage.arena.userIP,
                    gameId: window.arkExternalApiCommunicator._gameId,
                    sessionDuration: Math.floor((new Date().getTime() - window.arkExternalApiCommunicator._sessionStart.getTime()) / 1000),
                    gameplayDuration: window.arkExternalApiCommunicator.overallGameplayTime + window.arkExternalApiCommunicator._getGameplayDuration(),
                    adsServed: adsServed,
                    avgRevenuePerSession: window.arkExternalApiCommunicator._avgGameRevenue,
                    avgRevenue: window.arkExternalApiCommunicator._avgRev(adsServed)
                };
                ark.triggerEvent('arkGameCompletionDataProgress', resObj);
            },
            this._eventPeriodSeconds * 1000);
    },

    _disableTimeBasedEvent: function () {
        clearInterval(this._eventIntervalId);
    },

    _getUserId: function () {
        var qstr = document.location.search.replace("?", "");
        var query = {};
        var a = qstr.split('&');
        for (var i = 0; i < a.length; i++) {
            var b = a[i].split('=');
            query[decodeURIComponent(b[0])] = decodeURIComponent(b[1] || '');
        }
        var userId = query['user_id'];

        if (userId) {
            window.ark_jQuery.cookie('externalUserId', userId, {path: "/"});
        }
        return window.ark_jQuery.cookie('externalUserId');
    },

    _loadGameRevenue: function () {
        try {
            var data = arkPage.game.adsRevData.grd;
            var mappings = {
                "pc": "desktop",
                "phone": "mobile",
                "tablet": "tablet"
            };
            var currentPlatformMapped = mappings[arkPage.arena.device];

            for (var i = 0; i < data.platform.length; i++) {
                var item = data.platform[i];
                if (item.Key === currentPlatformMapped) {
                    if (item.Value && item.Value.revenue) {
                        window.arkExternalApiCommunicator._avgGameRevenue = item.Value.revenue;
                    }
                }
            }
        } catch (e) {
        }
    },

    _getGameplayDuration: function () {
        if (window.arkExternalApiCommunicator._gameplayStartDateTime) {
            var time = new Date().getTime() - window.arkExternalApiCommunicator._gameplayStartDateTime.getTime();
            return Math.floor((time) / (1000));
        }
        ;
        return 0;
    },

    refreshActivityCallback: function () {
        if (window.arkExternalApiCommunicator._gameStarted) {
            if (!this._gameplayStartDateTime) {
                this._gameplayStartDateTime = new Date();
            }
            ;
            if (this._callbackTimeoutId) {
                clearTimeout(this._callbackTimeoutId);
            }
            ;
            if (this._html5OverlayTimeoutId) {
                clearTimeout(this._html5OverlayTimeoutId);
                this.removeHtml5Overlay();
            }
            ;
            this._callbackTimeoutId = setTimeout(function () {
                    window.arkExternalApiCommunicator.stopActivityCallback();
                },
                window.arkExternalApiCommunicator._callbackPeriodSeconds * 1000);
            this._html5OverlayTimeoutId = setTimeout(function () {
                    window.arkExternalApiCommunicator.setHtml5Overlay();
                },
                10000);
            console.log('activity timeout refresh');
        }
    },

    stopActivityCallback: function () {
        this.overallGameplayTime += this._getGameplayDuration();
        this._gameplayStartDateTime = null;
        console.log('activity timeout stop');
        if (!window.arkExternalApiCommunicator._gameEndHandled && arkGaVirtualPages.part1 === 'game start') {
            if (arkPage.arena.device == 'pc') {
                ark_Popup.open('gamePaused');
            } else {
                alert('Your game was paused due to inactivity...');
                window.arkExternalApiCommunicator.refreshActivityCallback();
            }
        }
    },

    _isIe: function () {
        var containsIe = window.navigator.userAgent.indexOf('MSIE ');
        if (containsIe > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)) {
            return true;
        }
        return false;
    },

    setHtml5Overlay: function () {
        if (this._isIe()) {
            window.ark_jQuery('#gameBlock').prepend('<ark-div style="width: 100%; height: 100%; position: absolute;" id="arkIeOverlay" ></ark-div>')
        }
        ;
        window.ark_jQuery('#gameBlock > iframe').css('pointer-events', 'none');
    },

    removeHtml5Overlay: function () {
        if (this._isIe()) {
            window.ark_jQuery('#arkIeOverlay').remove();
        }
        ;
        window.ark_jQuery('#gameBlock > iframe').css('pointer-events', '');
    },

    _parseSearchQuery: function (qstr) {
        qstr = qstr.replace("?", "");
        var query = {};
        var a = qstr.split('&');
        for (var i = 0; i < a.length; i++) {
            var b = a[i].split('=');
            query[decodeURIComponent(b[0])] = decodeURIComponent(b[1] || '');
        }
        return query;
    },

    _processAdsEvents: function () {
        var eventsProcessed = [];
        for (var i = 0; i < this._adsEvents.length; i++) {
            var evt = this._adsEvents[i];
            if (evt.eventCategory.indexOf("Roll") !== -1) {
                var name = evt.eventCategory.split("_")[1];
                eventsProcessed.push({
                    adType: "video",
                    adSubtype: name
                });
            } else {
                eventsProcessed.push({
                    adType: "display",
                    adSubtype: evt.eventCategory
                });
            }
        }
        return eventsProcessed;
    },

    _avgRev: function (ads) {
        var res = 0;
        if (ads) {
            for (var i = 0; i < ads.length; i++) {
                try {
                    var ad = ads[i];
                    if (arkPage.game.adsRevData && arkPage.game.adsRevData.ard && arkPage.game.adsRevData.ard.cpms) {
                        if (arkPage.game.adsRevData.ard.cpms[ad.adType]) {
                            res += arkPage.game.adsRevData.ard.cpms[ad.adType] / 1000;
                        }
                    }
                } catch (e) {
                }
            }
        }
        return res;
    },

    getGameplayDataObject: function () {
        var adsServed = this._processAdsEvents();
        var resObj = {
            gameplayDuration: this.overallGameplayTime + this._getGameplayDuration(),
            avgRevenue: this._avgRev(adsServed)
        };
        return resObj;
    },

    stopGame: function (scoreObj) {
        window.arkExternalApiCommunicator._gameEnded = true;
        window.arkExternalApiCommunicator._disableTimeBasedEvent();
        this._killCallbacks();
        var adsServed = this._processAdsEvents();
        var resObj = {
            uid: this._userId,
            user_ip: arkPage.arena.userIP,
            gameId: this._gameId,
            score: scoreObj.score,
            scoreHash: scoreObj.hash,
            sessionDuration: Math.floor((new Date().getTime() - this._sessionStart.getTime()) / 1000),
            gameplayDuration: this.overallGameplayTime + this._getGameplayDuration(),
            adsServed: adsServed,
            avgRevenuePerSession: this._avgGameRevenue,
            avgRevenue: this._avgRev(adsServed)
        };
        ark.triggerEvent('arkGameCompletionDataReady', resObj);
        window.arkExternalApiCommunicator.reinit();
    }
};
if(window.useAwardBasedMechanics){
    window.arkExternalApiCommunicator.init();
}
/**
 * Created by roman.mikhailov on 5/5/2017.
 */

function SSOGameEndLogin() {
 if (arkPage.arena.loginSystems.indexOf("sso:") == -1) return;
 var s = parseInt(ark_jQuery('#score').html().replace(",", ""));
 //var args = { externalGameId: arkPage.game.externalGameId, score: s };
 ark_jQuery.cookie("ssoGELogin",
  base64.encode("externalGameId=" + arkPage.game.externalGameId + "&score=" + s),
  { path: "/" });
 window.DoCustomRegisterLogin();
}

function SSOSaveGuestAfterLogin() {
 if (ark_jQuery.cookie("ssoGELogin") == null) return;
 var sc;
 var externalGameId;
 var ssoGELoginValue = base64.decode(ark_jQuery.cookie("ssoGELogin"));
 var a = ssoGELoginValue.split('&');
 for (var i = 0; i < a.length; i++) {
  var b = a[i].split('=');
  if (b[0] == "externalGameId") {
   externalGameId = b[1];
  }
  if (b[0] == "score") {
   sc = b[1];
  }
 }

 var args = { externalGameId: externalGameId, score: sc };
 var url = '/manage/saveguestgamescore/';
 ark_jQuery.post(url,
  args,
  function(data) {
   if (data == 'true') {
    ark_jQuery('.arena-post-score').hide();
    if (ark_jQuery('#arkLeaderboardTab').hasClass("active")) {
     ark_jQuery.cookie('lbTimePeriod', 'day', { expires: 300, path: "/" });
     ark_jQuery(".arena-detail-tabs span").removeClass("active");
     ark_jQuery("#arkLeaderboardTab").addClass("active");
     ark_jQuery.cookie('arkInfoTabLastActive', 'arkLeaderboardTab', { path: "/" });
    }
    var refreshNeeded = checkIfRefreshLeaderboardNeeded();
    if (refreshNeeded) {
     updateLeaderboardWithoutCache();
    }
    ark_jQuery.cookie('ssoGELogin', '', { expires: -1, path: "/" });
   } else {
    ark.logging("Error: Score submit error in saveguestgamescore");
   }
  });
}


/**
 * Created by roman.mikhailov on 5/29/2017.
 */

function ArkUserBadgesWorker() {

    var ready = false;

    var jq = window.ark_jQuery;

    function isIe() {
        var userAgent = navigator.userAgent;
        return userAgent.indexOf("MSIE ") > -1 || userAgent.indexOf("Trident/") > -1 || userAgent.indexOf("Edge/") > -1;
    }


    function awardBadge(key, callback) {

        if (typeof callback !== "function") {
            callback = function (resp) {
            };
        }

        var url = "/UserItems/AwardBadge";
        if (isIe()) {
            url += "?v=" + Math.random();
        }
        jq.post(url, {Key: key}, function (resp) {
            callback(resp);
        });
    }

    function loadBadgesConfig() {
        var url = "/UserItems/UserBadgesInfo/";
        if (isIe()) {
            url += "?v=" + Math.random(); //fix for IE to prevent caching
        }
        ark_jQuery.ajax({
            async: false,
            type: 'GET',
            url: url,
            success: function (resp) {
                if (resp.Result) {
                    init(resp.Result);
                }
            }
        });
    }


    function initListeners() {
        if (window.masterViewGlobals.supportBadges) {
            if (arkPage.user.isActive) {
                loadBadgesConfig();
            } else {
                ark.addListener("ark:login",
                    function () {
                        loadBadgesConfig();
                    });
            }
        }
    }

    function filterBadges(src) {
        var result = [];
        var supportedBadges = ["badge-30-days-visit", "badge-7-days-visit", "badge-played-5-games", "badge-played-25-games"];
        for (var i = 0; i < src.length; i++) {
            var badge = src[i];
            if (supportedBadges.indexOf(badge.Key) !== -1 && !badge.IsUnlocked) {
                result.push(src[i]);
            }
        }
        return result;
    }


    var badgeAwarders = {
        "badge-30-days-visit": {
            initWatcher: function () {
                var cookieName = "arkBadge30DaysVisitCookie";
                var cookie = jq.cookie(cookieName);

                var contents = {};
                var now = (new Date()).getTime();

                if (cookie) {
                    contents = JSON.parse(base64.decode(cookie));
                    var day = 24 * 60 * 60 * 1000;
                    if ((now - contents.lastDate) > day) {
                        contents.firstDate = now;
                    }
                    contents.lastDate = now;
                    jq.cookie(cookieName, base64.encode(JSON.stringify(contents)), {expires: 365, path: "/"});
                    if ((contents.lastDate - contents.firstDate) >= day * 30) {
                        awardBadge("badge-30-days-visit", function (resp) {
                            ark.triggerEvent("arkUserBadgeAwarded", "badge-30-days-visit");
                            jq.cookie(cookieName, "", {expires: -1, path: "/"});
                        });
                        return;
                    }
                } else {
                    contents.lastDate = now;
                    contents.firstDate = now;
                }
                jq.cookie(cookieName, base64.encode(JSON.stringify(contents)), {expires: 365, path: "/"});
            }
        },
        "badge-7-days-visit": {
            initWatcher: function () {
                var cookieName = "arkBadge7DaysVisitCookie";
                var cookie = jq.cookie(cookieName);

                var contents = {};
                var now = (new Date()).getTime();

                if (cookie) {
                    contents = JSON.parse(base64.decode(cookie));
                    var day = 24 * 60 * 60 * 1000;
                    if ((now - contents.lastDate) > day) {
                        contents.firstDate = now;
                    }
                    contents.lastDate = now;
                    jq.cookie(cookieName, base64.encode(JSON.stringify(contents)), {expires: 365, path: "/"});
                    if ((contents.lastDate - contents.firstDate) >= day * 7) {
                        awardBadge("badge-7-days-visit", function (resp) {
                            ark.triggerEvent("arkUserBadgeAwarded", "badge-7-days-visit");
                            jq.cookie(cookieName, "", {expires: -1, path: "/"});
                        });
                        return;
                    }
                } else {
                    contents.lastDate = now;
                    contents.firstDate = now;
                }
                jq.cookie(cookieName, base64.encode(JSON.stringify(contents)), {expires: 365, path: "/"});

            }
        },
        "badge-played-5-games": {
            initWatcher: function () {

                function badgeAwardLogic() {
                    var cookieName = "arkBadge5GamesPlayed";
                    var cookie = jq.cookie(cookieName);
                    var contents = [];
                    if (cookie) {
                        contents = JSON.parse(base64.decode(cookie));
                    }
                    if (contents.indexOf(arkPage.game.externalGameId) === -1) {
                        contents.push(arkPage.game.externalGameId);
                    }
                    jq.cookie(cookieName, base64.encode(JSON.stringify(contents)), {expires: 365, path: "/"});
                    if (contents.length >= 5) {
                        awardBadge("badge-played-5-games", function () {
                            ark.triggerEvent("arkUserBadgeAwarded", "badge-played-5-games");
                            jq.cookie(cookieName, "", {expires: -1, path: "/"});
                        });
                        return;
                    }
                }

                ark.removeListener("arkContentStartEvent", badgeAwardLogic);
                ark.addListener("arkContentStartEvent", badgeAwardLogic);

                ark.removeListener("arkContentEndEvent", badgeAwardLogic);
                ark.addListener("arkContentEndEvent", badgeAwardLogic);
            }
        },
        "badge-played-25-games": {
            initWatcher: function () {

                function badgeAwardLogic() {
                    var cookieName = "arkBadge25GamesPlayed";
                    var cookie = jq.cookie(cookieName);
                    var contents = [];
                    if (cookie) {
                        contents = JSON.parse(base64.decode(cookie));
                    }

                    if (contents.indexOf(arkPage.game.externalGameId) === -1) {
                        contents.push(arkPage.game.externalGameId);
                    }
                    jq.cookie(cookieName, base64.encode(JSON.stringify(contents)), {expires: 365, path: "/"});
                    if (contents.length >= 25) {
                        awardBadge("badge-played-25-games", function () {
                            ark.triggerEvent("arkUserBadgeAwarded", "badge-played-25-games");
                            jq.cookie(cookieName, "", {expires: -1, path: "/"});
                        });
                    }
                }

                ark.removeListener("arkContentStartEvent", badgeAwardLogic);
                ark.addListener("arkContentStartEvent", badgeAwardLogic);

                ark.removeListener("arkContentEndEvent", badgeAwardLogic);
                ark.addListener("arkContentEndEvent", badgeAwardLogic);

            }
        }
    };

    this.userBadgesList = function () {

    };

    function init(config) {
        if (ready) return;
        window.userBadges = config.filter(function (itm) {
            return itm.IsUnlocked;
        });
        var availableBadges = filterBadges(config);
        for (var i = 0; i < availableBadges.length; i++) {
            var badge = availableBadges[i];
            try {
                badgeAwarders[badge.Key].initWatcher();
            } catch (err) {
            }
        }
        ready = true;
    }
    initListeners();
};
ark_jQuery(document).ready(function () {
    window.arkUserBadgesWorker = new ArkUserBadgesWorker();
});




 function ToolTipHelper() {
    var $ = ark_jQuery;
    var self = this;
    
    this.Init = function (root) {
        root = root || document.querySelector('body');
        var tooltipMarginBottom = 10;
        if (root && $('body').hasClass('arena-page-body-on-pc')) {
            $(root).find('.js-show-ark-tooltip').hover(function() {
                    //creating tooltip
                    var tooltipText = $(this).data('ark-tooltip');
                    if (!tooltipText) return;
                        
                    var tooltip = '<ark-div class="ark-game-tooltip" style="opacity: 0">' + tooltipText + '</ark-div>';
                    $('body').append(tooltip);

                    //setting positions
                    var $this = $(this);

                    //tooltip sizes
                    var $tooltip = $('.ark-game-tooltip');
                    var tooltipWidth = $tooltip.outerWidth();
                    var tooltipHeight = $tooltip.outerHeight();

                    //item sizes
                    var itemWidth = $this.outerWidth();
                    var itemHeight = $this.outerHeight();
                    var itemCenterPoint = itemWidth / 2;
                    var itemLeft = $(this).offset().left;
                    var itemTop = $(this).offset().top;

                    //boundaries
                    var leftBound = 0;
                    var rightBound = $(window).width();
                    var windowTop = $(window).scrollTop();

                    //default tooltip positions
                    var tooltipTop = itemTop - tooltipHeight - tooltipMarginBottom;
                    var tooltipLeft = (itemLeft + itemCenterPoint) - (tooltipWidth / 2);

                    var isTooltipLeftBounded = tooltipLeft < leftBound;
                    var isTooltipRightBounded = tooltipLeft + tooltipWidth > rightBound;
                    var isTooltipTopBounded = tooltipTop < windowTop;

                    //adjusting positioning
                    if (isTooltipLeftBounded) {
                        tooltipLeft = itemLeft;
                    }

                    if (isTooltipRightBounded) {
                        tooltipLeft = itemLeft - tooltipWidth + itemWidth;
                    }

                    if (isTooltipTopBounded) {
                        tooltipTop = itemTop + itemHeight;
                    }

                    //adding class to style tooltip arrow
                    if (isTooltipLeftBounded && isTooltipTopBounded) {
                        $tooltip.addClass('ark-game-tooltip--left-bottom');
                    }

                    if (isTooltipRightBounded && isTooltipTopBounded) {
                        $tooltip.addClass('ark-game-tooltip--right-bottom');
                    }

                    if (!isTooltipRightBounded && !isTooltipLeftBounded && isTooltipTopBounded) {
                        $tooltip.addClass('ark-game-tooltip--center-bottom');
                    }

                    if (isTooltipLeftBounded && !isTooltipTopBounded) {
                        $tooltip.addClass('ark-game-tooltip--left-top');
                    }

                    if (isTooltipRightBounded && !isTooltipTopBounded) {
                        $tooltip.addClass('ark-game-tooltip--right-top');
                    }

                    $tooltip.css({
                        'top': tooltipTop,
                        'left': tooltipLeft,
                        'opacity': 1 // setting opacity after positioning
                    });

                },
                function() {
                    $('.ark-game-tooltip').remove();
                });
        }
    };
    $(document).ready(function() { self.Init(); });
}
window.arkToolTipHelper = new ToolTipHelper();
