﻿/// <reference path="jquery-1.4.1-vsdoc.js"/>

var gamesCategory = "GamesGroupCollection";
var gamesGroupName = "Featured";
var scratchCardsGroup = "Featured";
var GMTClickCount = 0;
var selectedGroup = "Featured";
var currentlyShowing = null;
var playtechGamesPod;

$(document).ready(function () {
    HideAnnouncementMsg();
    $("[id$=_ClickToViewMessagesLink],[id$=_CloseUrgentMessages]").click(function () {
        HideUrgentMessagesPrompt();
    });

    if (!bet365.GMT) {
        $(".GameOption a").live("click", null, function (event) { popupwindow(event) });
    }
    gamesCategory = $(".GroupNavigationActive").attr("name");
    selectedGroup = $(".GamesGroupNavigationActive").attr("name");

    //sliding panel code
    $(".CollapsibleSectionHeader").live("click", function () {
        var oldVal = $(this).html();
        $(this).html($(this).attr("rel"));
        $(this).attr("rel", oldVal);
        $(".CollapsibleSection").slideToggle(400);
    });

    $(".CollapsibleSection").slideToggle(0);
    if (!bet365.GMT) {
        SetPodHover();
    }else{
        $("div[class^=GamesPod], div[class^=PlaytechGamesPod]").live("mouseover mouseout", function (event) {
            if (event.type === "mouseover") {
                $(this).attr('title', $(this).find(".PodName").html());
                $(this).addClass("GamesPodHover");

            }else {
                $(this).attr('title', $(this).find(".PodName").html());
                $(this).removeClass("GamesPodHover");
            }
        });
    }
    SetGamesGroupNavigation(gamesCategory);
    SetAdsHover();

    //get the href of the playnow button and add it to the div click event
    $(".InformationPodContainer").click(
        function () {
            window.location = $(this).find(".PlayNowButton a").attr("href");
        }
    );

    $(".InformationPodContainer").hover(
        function () {
            $(this).find(".PlayNowButton a").css({ backgroundPosition: "0px -15px" });
            $(this).css("border-color", "#FFDF1B");
        },
        function () {
            $(this).find(".PlayNowButton a").css({ backgroundPosition: "0px 0px" });
            $(this).css("border-color", "#666666");
        }
    );

    $(".RHSAdvert").live("click",
        function (event) {
            if (event.target == this) {
                if ($(this).find("a").click) {
                    $(this).find("a").click();
                } else {
                    window.location = $(this).find("a").attr("href");
                }
                if (bet365.GMT) {
                    if ($(this).attr("GameId")) {
                        bet365.GMT.RunGMTAlgorithmFromGameId($(this).attr("GameId"));
                    } else if ($(this).parent().attr("GameId")) {
                        bet365.GMT.RunGMTAlgorithmFromGameId($(this).parent().attr("GameId"));
                    }
                }
            }
            return true;
        }
    );

    $(".FreePlayAdvert").live("click",
        function (event) {
            if (event.target == this) {
                if ($(this).find("a").click) {
                    $(this).find("a").click();
                } else {
                    window.location = $(this).find("a").attr("href");
                }
            }
            return true;
        }
    );

    $(".SectionAInnerContainer").hover(
        function () {
            $(this).css({ borderColor: "#FFDF1B" });
        },
        function () {
            $(this).css({ borderColor: "#666666" });
        }
    );

    $(".StaticBannerButton").hover(
        function () {
            $(this).css({ 'background-position-y': 'bottom' });
        },
        function () {
            $(this).css({ 'background-position-y': 'top' });
        }
    );
    //get the href of the playnow button and add it to the div click event
    $(".SectionAInnerContainer").click(
        function () {
            if ($(this).find("a").attr("href")) {
                window.location = $(this).find("a").attr("href");
            }
        }
    );


    var promotionalGames = $(".GameContainer");

    if (promotionalGames.length > 0) {
        promotionalGames.each(function () {
            $(this).hover(function () {
                $(this).css("cursor", "pointer");
                $(".GameImageRollover", $(this)).css("border-color", "#FFDF1B");
                $(".PlayLinks > a", $(this)).each(function (index) {
                    if (index === 0) {
                        $(this).css("text-decoration", "underline");
                    }
                });
            }, function () {
                $(this).css("cursor", "normal");
                $(".GameImageRollover", $(this)).css("border-color", "#144634");
                $(".PlayLinks > a", $(this)).each(function (index) {
                    if (index === 0) {
                        $(this).css("text-decoration", "none");
                    }
                });
            });

            //PlayLinks
        });

        $("a, h2, h3, p", promotionalGames).each(function () {
            $(this).click(function () {
                $holder = $(this).siblings().add($(this).siblings().find(".PlayLinks"));
                $holder = $("a:first", $holder);
                $holder.click();
            });
        });
    }

    var featuredGame = $(".FeaturedGame");

    if (featuredGame.length > 0) {
        featuredGame.each(function () {
            $("#HeaderImageContainerRight").hover(function () {
                $(this)
                    .css("cursor", "pointer")
                    .css("border-color", "#FFDF1B");

                $(".FeaturedGame a").each(function () {
                    $(this).css("text-decoration", "underline");
                });
            }, function () {
                $(this)
                    .css("cursor", "normal")
                    .css("border-color", "#144634");
                $(".FeaturedGame a").css("text-decoration", "none");
            });

            // Set up click for the image
            $("#HeaderImageContainerRight").bind("click", $("a:first", $(this)), OnHeaderImageContainerRightClick);

            $("a", $(this)).each(function () {
                $(this).hover(function () {
                    $(this)
                        .css("cursor", "pointer")
                        .css("text-decoration", "underline");
                    $("#HeaderImageContainerRight").css("border-color", "#FFDF1B");
                }, function () {
                    $(this)
                        .css("cursor", "normal")
                        .css("text-decoration", "none");
                    $("#HeaderImageContainerRight").css("border-color", "#144634");
                });
            });
        });
    }

    //bind progressive script
    BindProgressivePods();

    ShowUrgentMessagesPrompt();
    bet365.flash.ShouldShowMsg();
    $("#KYCIFrame").ready(function () {
        setTimeout(function () { showKycForm(); }, 3000);
    });

    $("#TandCPopup").ready(function () {
        if ($("#TandCPopup").length == 1) {
            setTimeout(function () { bet365.popups.showDialog("#TandCPopup", "black"); }, 500);
        }

    });

    if (bet365.GMT != undefined) {

        bet365.GMT.SetupGMT();
    } else {
        //bind a click event to the Playtech Game Pods so that we know which one is clicked for GMT purposes
        $("div[class^=PlaytechGamesPod]").live("click", null, function () {
            RunGMTAlgorithm({ isPlaytech: true, requiredFlashVersion: '10.0.22' }, null, $(this).children("#PodPlayNow").children("#PlayNowLink"));
        });

        $("div[class^=GamesPod]").live("click", null, function (event) { popupwindow(event) });

    }

});

function ShowUrgentMessagesPrompt() {

    var control = $(".UrgentMessagesContainer");
    if (control.length == 1) {

        var position = 'fixed';
        var browser = bet365.GetBrowser();

        if (browser == 'IE6') {
            position = 'relative';
        }

        $(".UrgentMessagesContainer").css({ 'position': position, 'top': bet365.Screen.Top(control) + 'px', 'left': bet365.Screen.Left(control) + 'px', 'z-index': 9999, 'display': 'block' });

        $(window).bind("resize", function () {
            $(".UrgentMessagesContainer").css({ 'position': position, 'top': bet365.Screen.Top(control) + 'px', 'left': bet365.Screen.Left(control) + 'px', 'z-index': 9999, 'display': 'block' });   
        });
    }
}

function HideUrgentMessagesPrompt() {
    $(".UrgentMessagesContainer").css("display", "none");

    $(window).unbind("resize");
}


function OnHeaderImageContainerRightClick(event) {
    $("#HeaderImageContainerRight").unbind("click");
    var linkJQuery = event.data;
    linkJQuery.click();
    $("#HeaderImageContainerRight").bind("click", linkJQuery, OnHeaderImageContainerRightClick);
}

function BindProgressivePods() {
    //bind the progressive script to the pods
    $(".GamesPod, .GamesPodEnd, .PlaytechGamesPod, .PlaytechGamesPodEnd").each(function () {
        bet365.flash.ProgressiveScript($(this).attr("id"));
    });
}

function SetAdsHover() {
    $(".RHSAdvertContainer").hover(
        function () {
            $(this).addClass('hover');
        },
        function () {
            $(this).removeClass('hover');
        }
    );
}

function SetPodHover() {
    $("div[class^=GamesPod], div[class^=PlaytechGamesPod]").hover(function () {
        $(this).css({ cursor: "pointer" });
        $(this).find(".PodHeader").css({ borderColor: "#FFDF1B" });
        $(this).find(".PodHeader").attr('title', $(this).find(".PodName").html());
        $(this).find(".PodPlayNow a").css({ marginTop: "-23px" });
        $(this).find(".PodName").css({ textDecoration: "underline" });
    },
        function () {
            $(this).find(".PodHeader").css({ borderColor: "#064532" });
            $(this).find(".PodHeader").attr('title', $(this).find(".PodName").html());
            $(this).find(".PodPlayNow a").css({ marginTop: "0px" });
            $(this).find(".PodName").css({ textDecoration: "none" });
        }
    );
}


function SetGamesGroupNavigation() {
    $(".GamesGroupNavigation a").click(function (evt) {
        evt.preventDefault();
        if (selectedGroup != $(this).attr("name")) {
            selectedGroup = $(this).attr("name");
            contentPath = $("#HomeContentPath")[0].value;
            if (gamesCategory == "GamesGroupCollection") {
                gamesGroupName = selectedGroup;
            }
            else {
                scratchCardsGroup = selectedGroup;
            }
            var url = "HomePage.aspx/UpdateGamesGrid";
            var data = "{'gamesGroupName' : '" + selectedGroup + "','contentPath' : '" + contentPath + "'}";

            currentlyShowing = null;
            var sectionName = $(this).attr("name");
            if (bet365.GMT){
                bet365.popups.showDialog("#LoadingDiv", "#000", 0.6, 0, '#GamesGridPopupMask');
                $("#GroupNavigationPopupMask").css({ 'z-index': 9999, 'display': 'block' });
                $("#GamesGroupNavigationPopupMask").css({ 'z-index': 9999, 'display': 'block' });
            }
            $.ajax({
                type: "POST",
                url: url,
                data: data,
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (msg) {
                    PopulateGrid(msg.d, sectionName);
                    $(".GamesGroupNavigationActive").removeClass("GamesGroupNavigationActive");
                    $("a[name='" + selectedGroup + "']").addClass("GamesGroupNavigationActive");

                },
                complete: function (req, status) {
                    if (bet365.GMT){
                        bet365.popups.hideDialog("#LoadingDiv", 0, '#GamesGridPopupMask');
                        $("#GroupNavigationPopupMask").css({  'display': 'none' });
                        $("#GamesGroupNavigationPopupMask").css({  'display': 'none' });
                    }
                }
            });
        }
    });
}

function PopulateGrid(gridData, sectionName) {
    var flashPosition = gridData.indexOf('<div id="MultiElementBannerContainer"');
    if (flashPosition > -1) {
        var gamesGrid = gridData.substring(0, flashPosition); //  + "</div>";
        var flashDiv = gridData.substring(flashPosition, (gridData.length));
        $(".GamesGrid").replaceWith(gamesGrid);

        var scriptIDPos = flashDiv.indexOf('</script>');
        var flashContainer = flashDiv.substring(scriptIDPos, (flashDiv.length));

        // Set the new flash container HTML
        $(".MultiElementFlashBorder").html(flashDiv);

        // Find Flash and NoFlash div elements
        var flashMovieDiv = $("div[id*='FlashMovieDiv']");
        var noFlashDiv = $("div[id*='NoFlashDiv']");

        $(".GamesGroupNavigationActive").removeClass("GamesGroupNavigationActive");
        $("[name='" + sectionName + "']").filter("a").addClass("GamesGroupNavigationActive").removeClass("GamesGroupNavigation");

        // Find the hidden field
        var hiddenFlashElement = $("input[id*='HiddenFlash']");
        var hiddenFlashLaunchElement = $("input[id*='HiddenFlashLaunch']");

        // Get the js for Flash Object
        var sflashJS = $(hiddenFlashElement).val();
        sflashJS = sflashJS.replace("FlashMovieDiv", $(flashMovieDiv).attr("id"));
        sflashJS = sflashJS.replace("NoFlashDiv", $(noFlashDiv).attr("id"));

        // Replace the flash load function with new implementation
        var sflashLaunchJS = $(hiddenFlashLaunchElement).val();

        evalGlobal(sflashLaunchJS);
        evalGlobal(sflashJS);
        if(!bet365.GMT){
            SetPodHover();
        }
        SetAdsHover();
        BindProgressivePods();

    }
    else {
        $(".GamesGrid").replaceWith(gridData);
        SetAdsHover();
        if(!bet365.GMT){
            SetPodHover();
        }
        $(".GamesGroupNavigationActive").removeClass("GamesGroupNavigationActive");
        $("[name='" + sectionName + "']").filter("a").addClass("GamesGroupNavigationActive").removeClass("GamesGroupNavigation");
        BindProgressivePods();
    }

    if (bet365.GMT) {
        bet365.GMT.ResetDomContext();
    }
}

// Function to perform a global scope eval
// Could become a global function iteself
function evalGlobal(code) {
    var scope_global = this;
    if (window.execScript) {
        window.execScript(code);
        return null;
    }
    return scope_global.eval ? scope_global.eval(code) : eval(code);
}

popupwindow = function (e) {
    var profiles = {};
    e.preventDefault();

    var settings, parameters, mysettings, b, a, winObj, linkObject;

    if ($(e.currentTarget).attr("href") != undefined) {
        linkObject = $(e.currentTarget);
    } else {
        //determine whether it is a free play or real play link click
        var eventTargetObject = $((e.originalTarget == undefined) ? e.target : e.originalTarget);
        if (eventTargetObject.hasClass("PodFreePlay")) {
            linkObject = eventTargetObject;
        } else {
            linkObject = $(".PodPlayNow > a", $(e.currentTarget));
        }
    }


    // for overrideing the default settings
    mysettings = (jQuery(linkObject).attr("rel") || "").split(",");

    settings = {
        height: 596, // sets the height in pixels of the window.
        width: 792, // sets the width in pixels of the window.
        toolbar: 0, // determines whether a toolbar (includes the forward and back buttons) is displayed {1 (YES) or 0 (NO)}.
        scrollbars: 1, // determines whether scrollbars appear on the window {1 (YES) or 0 (NO)}.
        status: 0, // whether a status line appears at the bottom of the window {1 (YES) or 0 (NO)}.
        resizable: 1, // whether the window can be resized {1 (YES) or 0 (NO)}. Can also be overloaded using resizable.
        left: 0, // left position when the window appears.
        top: 0, // top position when the window appears.
        center: 1, // should we center the window? {1 (YES) or 0 (NO)}. overrides top and left
        // Open a new window for each game
        createnew: 1, // should we create a new window for each occurance {1 (YES) or 0 (NO)}.
        location: 0, // determines whether the address bar is displayed {1 (YES) or 0 (NO)}.
        menubar: 0, // determines whether the menu bar is displayed {1 (YES) or 0 (NO)}.
        onUnload: null, // function to call when the window is closed
        requiredFlashVersion: $('body').data('pageAttributes').flashVersion,
        isPlaytech: false
    };

    // if mysettings length is 1 and not a value pair then assume it is a profile declaration
    // and see if the profile settings exists

    if (mysettings.length == 1 && mysettings[0].split(":").length == 1) {
        a = mysettings[0];
        // see if a profile has been defined
        if (typeof profiles[a] != "undefined") {
            settings = jQuery.extend(settings, profiles[a]);
        }
    }
    else {
        // overrides the settings with parameter passed in using the rel tag.
        for (var i = 0; i < mysettings.length; i++) {
            b = mysettings[i].split(":");
            if (typeof settings[b[0]] != "undefined" && b.length == 2) {
                settings[b[0]] = b[1];
            }
        }
    }

    // center the window
    if (settings.center == 1) {
        settings.top = (screen.height - (settings.height + 110)) / 2;
        settings.left = (screen.width - settings.width) / 2;
    }

    parameters = "location=" + settings.location + ",menubar=" + settings.menubar + ",height=" + settings.height + ",width=" + settings.width + ",toolbar=" + settings.toolbar + ",scrollbars=" + settings.scrollbars + ",status=" + settings.status + ",resizable=" + settings.resizable + ",left=" + settings.left + ",screenX=" + settings.left + ",top=" + settings.top + ",screenY=" + settings.top;

    if (!bet365.GMT){
        RunGMTAlgorithm(settings, parameters, linkObject);
    }

    if (bet365.GMT && bet365.GMT.Homepage) {
        if (!swfobject.hasFlashPlayerVersion(settings.requiredFlashVersion)) {
            //flash not available so trigger modal popup           
            bet365.flash.showNoFlashLauncherPrompt();
        } else {

            if ((settings.createnew == 0) && (persistantGameWindow != null)) {
                persistantGameWindow.close();
            }

            // Use the settings if it has been set in GamePod.ascx free link.
            var name = ((settings.createnew == 1) ? "_blank" : ((settings.createnew == 0) ? "GGG" : settings.createnew));
            winObj = window.open(linkObject.attr("href"), name, parameters);
            persistantGameWindow = winObj;

        }

        bet365.GMT.Homepage.RunGMTAlgorithm(settings, parameters, linkObject);
    }
};

function RunGMTAlgorithm(settings, parameters, pod) {
    if (!swfobject.hasFlashPlayerVersion(settings.requiredFlashVersion)) {
        //flash not available so trigger modal popup

        var modalPopupObj = $(".NoFlashLauncherContainer");

        bet365.flash.showNoFlashLauncherPrompt();
    }
    else {
        gamesCategory = $(".GroupNavigationActive").attr("name");
        selectedGroup = $(".GamesGroupNavigationActive").attr("name");

        if ((settings.createnew == 0) && (persistantGameWindow != null)) {
            persistantGameWindow.close();
        }
        if (!settings.isPlaytech) {

            // Use the settings if it has been set in GamePod.ascx free link.
            var name = ((settings.createnew == 1) ? "_blank" : ((settings.createnew == 0) ? "GGG" : settings.createnew));
            winObj = window.open(pod.attr("href"), name, parameters);

            if (settings.createnew == 0 && name == "GGG")
            {
                persistantGameWindow = winObj;
            }
        }

        if ((bet365.CheckType($("body").data("GMTCanRun")) === "Boolean") && ($("body").data("GMTCanRun") == true)) { //check for if gmt can run
            
            currentlyShowing = $("input[id$=hidCurrentlyShowing]").val();
            
            contentPath = $("#HomeContentPath")[0].value;
            //this handles the gmt grid change
            var runAfterClicks = $("[id$=RunAfterClicks]").val();
            var canRunForCategory = true;
           
            if ($("[id$=DoNotShowFor]").val() == selectedGroup) {
                canRunForCategory = false;
            } else { 
            
                var categorys = $("[id$=DoNotShowFor]").val().split(",");

                var catLength = categorys.length;
                for (i = 0; i <= catLength; i++) {
                    if (categorys[i] == selectedGroup) {
                        canRunForCategory = false;
                        break;
                    }
                }
            }
            
            GMTClickCount += 1;

            if ((canRunForCategory) && (GMTClickCount % runAfterClicks == 0)) {
                var gameHref = pod.attr("href");
                var gameCategory = pod.attr("rel");

                if ((gameHref !== '') && (gameCategory !== '')) {
                    var gameId = pod.parent().parent().attr("id").replace(/(GamesPod_)(\d+)(.*)/ig, function ($0, $1, $2, $3) { return $2; }); //need to get the selctor working in the parents() method, more elegant and doesn't break if html changes
                    var matches = gameCategory.match( /categoryName\:([^,]+)(?=,)/ );

                    if (matches != null && matches.length == 2) {
                        var categoryName = matches[1];

                        var selectedGame = pod;
                        $.ajax({
                            type: "POST",
                            url: "HomePage.aspx/GetGameMappings",
                            data: "{'gamesGroupName' : '" + selectedGroup + "','gamesCategory' : '" + gamesCategory + "', 'selectedGameId' : '" + gameId + "', 'currentlyShowing': '" + currentlyShowing + "', 'categoryName': '" + categoryName + "', 'contentPath': '" + contentPath + "' }",
                            contentType: "application/json; charset=utf-8",
                            dataType: "json",
                            success: function (msg) {
                                if (msg.d !== '') {
                                    jsonGrid(msg.d, selectedGame, gamesGroupName);
                                }
                            }
                        });
                    }
                }
            }
        } //end of check for whether gmt is allowed

        if (!settings.isPlaytech) {
            if (settings.onUnload) {
                // Incremental check for window status
                // Attaching directly to window.onunlaod event causes invoke when document within window is reloaded
                // (i.e. an inner refresh)
                unloadInterval = setInterval(function () {
                    if (!winObj || winObj.closed) {
                        clearInterval(unloadInterval);
                        settings.onUnload.call(pod); 
                    }
                }, 500);
            }

            winObj.focus();
        }
        return false;
    }
}

function jsonGrid(json, selectedItem, gamesGroupName) {
    var jsonObj = $.parseJSON(json);

    //we only want to do anything here if the pod information is not an empty array, otherwise we end up with pods disappearing

    if (jsonObj[0].length > 0) {
        //0 contains pod information
        //1 contains currently showing list of games
        //2 contains RHS pod information
        var context = $("[id$=GamesGrid]")[0];
        var pod = selectedItem.parents("div.GamesPodEnd, div.GamesPod, div.PlaytechGamesPod, div.PlaytechGamesPodEnd", context);
        var gamesPod = pod.siblings("div.GamesPodEnd, div.GamesPod", context)[0];
        var playtechPod = pod.siblings("div.PlaytechGamesPod, div.PlaytechGamesPodEnd", context)[0];
        
        if (playtechPod == null) {
            playtechPod = pod;
        }

        if (gamesPod == null) {
            gamesPod = pod;
        }

        $("[id$=ProgressiveDiv]", gamesPod).remove();
        $("[id$=ProgressiveDiv]", playtechPod).remove();

        var lastPodId;
        var podsToAdd = [];

        //remove currently added GMT pods
        //$("#gamesStart").nextUntil("input").remove();

        $("div.GamesPod, div.GamesPodEnd, div.PlaytechGamesPod, div.PlaytechGamesPodEnd", context).css("display", "block");

        $(jsonObj[0]).each(function (index)
        {
            var obj;

            if (bet365.CheckType(this.Lnk) === "String")
            {
                obj = $(playtechPod).clone(true);
            } else
            {
                obj = $(gamesPod).clone(true);
            }

            var gameId = (bet365.CheckType(this.Lnk) === "String") ? this.GId : this.Lnk;
            var id = "GamesPod_" + gameId;

            //find out if the pod exists somewhere else on the page and change the id, we do this so we get progressives working on the new pod as the id is the key in the data object
            var existingPod = $("#" + id, context);
            if (existingPod.length > 0)
            {
                existingPod.attr("id", id + '_' + index);
                existingPod.css("display", "none");
            }

            obj.attr("id", id);

            $(".PodHeader", obj).css("background-image", this.Hdr).attr("id", id + "_PodHeader");
            $(".PodCategoryText", obj).html(this.Cat).attr("id", id + "_PodCategoryText");
            $(".PodName", obj).html(this.Nme).attr("id", id + "_PodName");

            var newLink = $(".PodPlayNow > a", obj).attr("href");
            $(".PodPlayNow > a", obj).attr("rel", $(".PodPlayNow > a", obj).attr("rel").replace(/categoryName\:([^,]+)(?=,)/ig, "categoryName:" + this.Tag))
            $(".PodPlayNow > a", obj).attr("rel", $(".PodPlayNow > a", obj).attr("rel").replace(/createnew\:([01])/ig, "createnew:" + this.CrtNew))

            if (bet365.CheckType(this.Lnk) === "Number")
            {
                $(".PodPlayNow > a", obj).attr("href", newLink.replace(/GameId\=\d+/ig, "GameId=" + this.Lnk).replace(/Product\=[^&]+/ig, "Product=" + this.Prd)).attr("id", id + "_PodPlayNow");
                obj.removeClass("PlaytechGamesPodEnd, PlaytechGamesPod").addClass("GamesPod");
                //in case no games pod was cloned we need to remove the bound click event
                obj.unbind('click', calloutPlayForReal);
                obj.unbind('click', RunGMTAlgorithm);
            } else
            {
                //sort out the playtech launch games mechanism values
                $(".PodPlayNow > a", obj)[0].onclick = null;

                obj.attr("onclick", "").unbind("click").removeAttr("onclick");
                $(".PodPlayNow > a", obj).attr("onclick", "").unbind("click").removeAttr("onclick");
                $(".PodHeader", obj).attr("onclick", "").unbind("click").removeAttr("onclick");
                $(".PodName", obj).attr("onclick", "").unbind("click").removeAttr("onclick");

                $(".PodPlayNow > a", obj).attr("href", "#");
                //in case no playtech pod was cloned we need to remove the bound click event
                obj.unbind('click', popupwindow);
                obj.removeClass("GamesPodEnd, GamesPod").addClass("PlaytechGamesPod");

                var linkVal = this.Lnk;
                obj[0].onclick = function () { calloutPlayForReal(null, '' + linkVal + ''); return false; }
            }
            podsToAdd[index] = obj[0];
        });

        var oldPods = [];

        $("div.GamesPod, div.GamesPodEnd, div.PlaytechGamesPod, div.PlaytechGamesPodEnd", context).each(function (index) {
            oldPods[index] = $(this)[0];
            //$("div#" + $(this).attr("id"), context).remove();
        });

        $("div.GamesPod, div.GamesPodEnd, div.PlaytechGamesPod, div.PlaytechGamesPodEnd", context).remove();

        podsToAdd = podsToAdd.concat(oldPods);

        //reorder the podsToAdd array so the pods are in the same order as the currently showing list.

        var showingListIndex;
        var addedPodsIndex;
        var showingList = $(jsonObj)[1];
        var reOrderedPods = [];

        for (showingListIndex = 0; showingListIndex < showingList.length; showingListIndex++) {
            for (addedPodsIndex = 0; addedPodsIndex < podsToAdd.length; addedPodsIndex++) {
                var foundGameId = $(podsToAdd[addedPodsIndex]).attr("id").replace(/(GamesPod_)(\d+)(.*)/ig, function ($0, $1, $2, $3) { return $2; });

                if (foundGameId == showingList[showingListIndex]) {
                    reOrderedPods[showingListIndex] = podsToAdd[addedPodsIndex];
                    break;
                }
            }
        }

        $("#gamesStart", context).after(reOrderedPods);

        $("input[id$=hidCurrentlyShowing]").val($(jsonObj)[1]);
        $("input#" + gamesCategory + '_' + gamesGroupName).val($(jsonObj)[1]);

        var podPlacements = $(jsonObj)[1];
        var removedIndexes = 0;
        $("div.GamesPod, div.GamesPodEnd, div.PlaytechGamesPod, div.PlaytechGamesPodEnd", context).each(function (index) {
            var foundGameId = $(this).attr("id").replace(/(GamesPod_)(\d+)(.*)/ig, function ($0, $1, $2, $3) { return $2; });

            if (foundGameId != podPlacements[index - removedIndexes]) {
                //the pod has been moved to a different position or has been removed, so we need to remove this pod from the grid
                //$("div#" + $(this).attr("id"), context).css("display", "none");
                $("div#" + $(this).attr("id"), context).remove();
                removedIndexes += 1;
            } else {
                $("div#" + $(this).attr("id"), context).css("display", "block");
            }
        });

        var podCount = 0;
        $("div.GamesPod, div.GamesPodEnd, div.PlaytechGamesPod, div.PlaytechGamesPodEnd", context).each(function (index) {
            //remove the hidden pods from the grid
            if ($(this).css("display") !== "none") {
                if ((podCount != 0) && ((podCount + 1) % 4 == 0)) {
                    if ($(this).hasClass("GamesPod")) {
                        $(this).removeClass("GamesPod");
                        $(this).addClass("GamesPodEnd");
                    } else if ($(this).hasClass("PlaytechGamesPod")) {
                        $(this).removeClass("PlaytechGamesPod");
                        $(this).addClass("PlaytechGamesPodEnd");
                    }
                } else {
                    if ($(this).hasClass("GamesPodEnd")) {
                        $(this).removeClass("GamesPodEnd");
                        $(this).addClass("GamesPod");
                    } else if ($(this).hasClass("PlaytechGamesPodEnd")) {
                        $(this).removeClass("PlaytechGamesPodEnd");
                        $(this).addClass("PlaytechGamesPod");
                    }
                }

                //0 based ordinal count
                if (podCount == 3) {
                    podCount = 0;
                } else {
                    podCount += 1;
                }
            }
        });

        SetPodHover();
    }

    //RHS Pods
    if ($(jsonObj[2]).length > 0) {
        SetupRHSPods($(jsonObj[2]));
    }

    BindProgressivePods();
}

function SetupRHSPods(jsonList) {
    $(".RHSAdvertContainer").remove();

    jsonList.each(function (index) {
        var newDiv = $("<div></div>", { "class": "RHSAdvertContainer" }).appendTo(".GamesGridRHSAdverts");
        var innerDiv = $("<div></div>", { "class": "RHSAdvertInnerBorder" }).appendTo($(newDiv));
        if (this.Flash) {
            var advertDiv = $("<div></div>", { "class": "RHSAdvert" }).appendTo($(innerDiv)).css(
            { "height": this.Height,
                "width": this.Width,
                "z-index": "9000",
                "position": "absolute",
                "top": "0px"
            });

            var link = $("<a/>", { "href": this.Url }).appendTo($(advertDiv));

            if (this.OnClick) {
                link.click(new Function(this.OnClick))
            }

            var coverLink = $("<a>", { "class": "FlashRHSCoverLink" }).appendTo($(innerDiv)).css(
             {
                 "height": this.Height,
                 "width": this.Width,
                 "position": "absolute",
                 "top": "0px"
             });

            var flashDiv = $("<div></div>", { "class": "RHSAdvert" }).appendTo($(innerDiv));
            flashDiv.html(this.FlashSrc);
        } else {
            var advertDiv = $("<div></div>", { "class": "RHSAdvert",
                "height": this.Height,
                "width": this.Width
            }).appendTo($(innerDiv));
            if (this.Image) {
                $(advertDiv).css("background-image", this.Image);
            }
            var link = $("<a/>", { "href": this.Url }).appendTo($(advertDiv));
            if (this.OnClick) {
                link.click(new Function(this.OnClick))
            }
        }
    });
}

function ProgressiveUpdate(serviceUrl, currency, gameCode, timeout) {
    $.ajax({
        type: 'POST',
        data: { 'gameCode': '' + gameCode + '', 'currencyCode': '' + currency + '' },
        url: serviceUrl,
        success: function (data) {
            $("#ProgressiveValues").val(data);
        },
        error: function (x, y, z) {
        }
    });

    setTimeout(function () {
        ProgressiveUpdate(serviceUrl, currency, gameCode, timeout)
    }, timeout);
}

function GetProgressiveValue(gameCode) {
    var returnValue = '';

    $.each($("#ProgressiveValues").val().split(","), function (index) {
        var gameValues = this.split(":");

        if (gameValues.length > 1) {
            if (gameValues[0].toLowerCase() === gameCode.toLowerCase()) {
                returnValue = gameValues[1];
                return false;
            }
        }
    });

    return returnValue;
}

function showKycForm() {
    var kycFrame = $("#KYCIFrame");
    var hasFlash = (swfobject !== null) && (typeof swfobject !== 'undefined');
    if (kycFrame.css("display") === "none" && hasFlash) {
        var kycFlashVersion = swfobject.getFlashPlayerVersion();
        if ((kycFlashVersion.major == 0) && (navigator.userAgent.toLowerCase().indexOf('chrome') != -1)) { return; }
        bet365.popups.showDialog("#KYCIFrame", "black");
    }
}

function hideMessageWindow() {
    bet365.popups.hideDialog('#KYCIFrame');
}

function HideAnnouncementMsg() {
    $(".CloseAnnouncements").unbind('click').click(function () {
        $(this).fadeTo(500, 0);
        //call service to set important announcement viewed cookie + slide up
        $.ajax({
            type: 'POST',
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            url: 'HomePage.aspx/SetAnnouncementSeenCookie',
            success: function (data) {
                if (data.d === true) {
                    $("div.ImportantAnnouncementOuterContainer").slideUp(800);
                }
            },
            error: function (x, y, z) {
            }
        });
    });
}

//set the hide announcement msg event on page load

function osxffOnload(specificFunction) {
    if (window.innerWidth != undefined) {
        var app = navigator.userAgent;

        if (app.match(/Mac\ OS.*Firefox/ig)) {
            if (specificFunction) {
                specificFunction();
            }
            osxffResizeBody();
            window.onresize = function () { osxffResizeBody(); };
        }
    }
    return true;
}

function osxffResizeBody() {
    // if the window has been opened in a popup, we need to flip the fix.
    if (window.opener) {
        $("#pageContainer").css("marginLeft", window.innerWidth % 2 == 0 ? 0 : 1);
    }
    else {
        $("#pageContainer").css("marginLeft", window.innerWidth % 2 == 0 ? 1 : 0);
    }
}

function osxffOnLoadPageSpecific() {
}

function enterLink() {
}

enterLink.prototype.webFormPostback = function (func, invoke) {
    var fCall = func;
    if (typeof func != "function") {
        fCall = new Function(func);
    }

    if (invoke) {
        fCall();
    }
}

function childRefreshed() {
    $holder = $(".divJoinNow");
    if ($holder.length > 0) {
        ReloadME();
    }
}
