/******************************** PLEASE DO NOT MAKE ANY CHANGES HERE ********************************/
/*                            This is a common base same for all domains                             */
/*                 For domain related CSS rules scroll at the bottom of this page                    */
/*****************************************************************************************************/

// Sportingbet webteam data object
if(typeof(sbWeb)=="undefined" || sbWeb==null) var sbWeb = {};

// User inderface
if (typeof (sbWeb.ui) == "undefined" || sbWeb.ui == null) sbWeb.ui = {
    "translation": {
        "previous": "previous",
        "next": "next",
        "open": "open",
        "close": "close"
    },
    "translate": function(text) {
        var word = this.translation[text];
        return (this.translation[text]) ? word.charAt(0).toUpperCase() + word.slice(1) : "";
    },
    "createViewPort": function(elem, axis) {
        var wrapper = $("<div></div>").css({
            "position": "absolute",
            "float": elem.css("float"),
            "overflow": "hidden",
            "margin": elem.css("margin-top") + " " + elem.css("margin-right") + " " + elem.css("margin-bottom") + " " + elem.css("margin-left"),
            "background": elem.css("background-color") + " " + elem.css("background-image") + " " + ((typeof (elem.css("background-position")) != "undefined") ? elem.css("background-position") : elem.css("background-position-x") + " " + elem.css("background-position-y")) + " " + elem.css("background-repeat"), // IE backbroundPosition fix
            "border-top": elem.css("border-top-width") + " " + elem.css("border-top-style") + " " + elem.css("border-top-color"),
            "border-right": elem.css("border-right-width") + " " + elem.css("border-right-style") + " " + elem.css("border-right-color"),
            "border-bottom": elem.css("border-bottom-width") + " " + elem.css("border-bottom-style") + " " + elem.css("border-bottom-color"),
            "border-left": elem.css("border-left-width") + " " + elem.css("border-left-style") + " " + elem.css("border-left-color")
        });
        elem.css({ "display": "block" });
        elem.children().css({ "float": "left" });
        var width = elem.innerWidth();
        var height = elem.innerHeight();
        elem.css({ "position": "relative", "float": "left", "top": "0px", "left": "0px", "width": "auto", "height": "auto", "overflow": "visible", "margin": "0", "background": "none", "border": "0 none" });
        wrapper = elem.wrap(wrapper).parent().attr("data-uielem", "viewport");
        if (axis == "horizontal") wrapper.css({ "height": height + "px", "width": "1000000px" });
        else if (axis == "vertical") wrapper.css({ "width": width + "px", "height": "1000000px" });
        wrapper.data("innerElem", { "width": elem.outerWidth(), "height": elem.outerHeight() });
        wrapper.css({ "position": "relative", "width": width + "px", "height": height + "px" });
        elem.css("position", "absolute");
        return wrapper;
    },
    // Animated ticker tape
    // data-ticker="direction [forceAnimation] [durationPerPixel]"
    "ticker": function(elem, atributes) {
        if (elem.parent().is("[data-uielem=viewport]")) return false;
        atributes = atributes.toLowerCase().split(" ");
        var direction = $.grep(atributes, function(e, i) { return e.search(/^(up|right|down|left)$/) != -1; })[0] || false;
        var axis = (direction == "left" || direction == "right") ? "horizontal" : "vertical";
        if (direction) {
            var forceAnimation = $.grep(atributes, function(e, i) { return e.search(/^(yes|no)$/) != -1; })[0] || "no";
            var durationPerPixel = parseInt($.grep(atributes, function(e, i) { return e.search(/^\d+$/) != -1; })[0]) || 15;
            var wrapper = this.createViewPort(elem, axis);
            var innerElemWidth = wrapper.data("innerElem").width;
            var innerElemHeight = wrapper.data("innerElem").height;
            switch (direction) {
                case "left":
                    var isBigger = innerElemWidth > wrapper.innerWidth();
                    if (isBigger) {
                        var leftFrom = wrapper.innerWidth() - innerElemWidth;
                        var leftTo = leftFrom - innerElemWidth;
                        elem.append(elem.children().clone(true));
                        elem.css("width", innerElemWidth * 2 + "px");
                        var animateBiggerLeft = function() {
                            elem.css("left", leftFrom + "px").animate({ "left": leftTo + "px" }, innerElemWidth * durationPerPixel, "linear", animateBiggerLeft);
                        };
                        elem.animate({ "left": leftTo + "px" }, Math.abs(leftTo) * durationPerPixel, "linear", animateBiggerLeft);
                    }
                    else if (forceAnimation == "yes") {
                        var leftFrom = wrapper.innerWidth();
                        var leftTo = -innerElemWidth;
                        elem.css("width", innerElemWidth + "px");
                        var animateSmallerLeft = function() {
                            elem.css("left", leftFrom + "px").animate({ "left": leftTo + "px" }, (leftFrom - leftTo) * durationPerPixel, "linear", animateSmallerLeft);
                        };
                        animateSmallerLeft();
                    }
                    else {
                        wrapper.removeAttr("style");
                        elem.removeAttr("style");
                        elem.children().removeAttr("style");
                    }
                    break;
            }
        }
    },
    // Show limited number of children + navigation arrows
    // data-showonly="numberOfChildren axis"
    "showonly": function(elem, atributes) {
        elem.removeClass("hide");
        if (elem.parent().is("[data-uielem=viewport]")) return false;
        atributes = atributes.toLowerCase().split(" ");
        var axis = $.grep(atributes, function(e, i) { return e.search(/^(horizontal|vertical)$/) != -1; })[0] || false;
        var numberOfChildren = $.grep(atributes, function(e, i) { return e.search(/^\d+$/) != -1; })[0] || false;
        if (axis && numberOfChildren && (numberOfChildren < elem.children().length)) {
            var wrapper = sbWeb.ui.createViewPort(elem, axis);
            var innerElemWidth = wrapper.data("innerElem").width;
            var innerElemHeight = wrapper.data("innerElem").height;
            if (elem.is("[data-toggle=body]")) {
                elem.removeAttr("data-toggle");
                wrapper.wrap("<div></div>").parent().attr("data-toggle", "body").css({ "float": elem.css("float"), "width": elem.width() + "px" });
            }
            var dimensionOuterMax = 0;
            var dimensionOuterMax = 0;
            var dimension = "";
            var changeCss = "";
            var slideId = "";
            var countChildren = elem.children().length;
            switch (axis) {
                case "vertical":
                    elem.children().each(function() {
                        if ($(this).outerHeight(true) > dimensionOuterMax) {
                            dimensionOuterMax = $(this).outerHeight(true);
                            dimensionCssMax = $(this).height();
                        }
                    });
                    dimension = "height";
                    changeCss = "top";
                    slideId = "Y";
                    break;
                case "horizontal":
                    elem.children().each(function() {
                        if ($(this).outerWidth(true) > dimensionOuterMax) {
                            dimensionOuterMax = $(this).outerWidth(true);
                            dimensionCssMax = $(this).width();
                        }
                    });
                    dimension = "width";
                    changeCss = "left";
                    slideId = "X";
                    break;
            }
            elem.children().css(dimension, dimensionCssMax + "px");
            elem.css(dimension, countChildren * dimensionOuterMax + "px");
            wrapper.css(dimension, dimensionOuterMax * numberOfChildren + "px");
            var previous = wrapper.before("<div><span>" + sbWeb.ui.translate("previous") + "</span></div>").prev().bind("mouseenter mouseleave",
				function() { $(this).toggleClass("hover"); }
			).attr({ "title": sbWeb.ui.translate("previous"), "class": "slide" + slideId + " slide" + slideId + "previous" });
            var next = wrapper.after("<div><span>" + sbWeb.ui.translate("next") + "</span></div>").next().bind("mouseenter mouseleave",
				function() { $(this).toggleClass("hover"); }
			).attr({ "title": sbWeb.ui.translate("next"), "class": "slide" + slideId + " slide" + slideId + "next" });
            previous.click(function() {
                if (elem.is(":not(:animated)")) {
                    previous.addClass("disabled");
                    elem.prepend(elem.children(":last"));
                    elem.css(changeCss, parseInt(elem.css(changeCss).slice(0, -2)) - dimensionOuterMax + "px");
                    var animationArgs = {};
                    animationArgs[changeCss] = parseInt(elem.css(changeCss).slice(0, -2)) + dimensionOuterMax + "px";
                    elem.animate(
						animationArgs,
						"fast",
						function() {
						    previous.removeClass("disabled");
						}
					);
                    next.removeClass("disabled");
                }
                return false;
            });
            next.click(function() {
                if (elem.is(":not(:animated)")) {
                    next.addClass("disabled");
                    var animationArgs = {};
                    animationArgs[changeCss] = parseInt(elem.css(changeCss).slice(0, -2)) - dimensionOuterMax + "px";
                    elem.animate(
						animationArgs,
						"fast",
						function() {
						    next.removeClass("disabled");
						    elem.append(elem.children(":first"));
						    elem.css(changeCss, parseInt(elem.css(changeCss).slice(0, -2)) + dimensionOuterMax + "px");
						}
					);
                    previous.removeClass("disabled");
                }
                return false;
            });
        }
    },
    // Rounded corners
    // data-roundcorner="radiusType"
    "roundcorner": function(elem, radiusType) {
        if (elem.children(".corner").length > 0) return false;
        radiusType = (radiusType.search(/^(1|2|3)$/) != -1) ? radiusType : false;
        elem = (elem.is("[data-ticker], table, tbody, thead, tr, ul, dl, input, selection")) ? false : elem; // restrict tags that would create invalid HTML, also not aplicable on ticker-ed element
        if (radiusType && elem) {
            // don't use prepend - .class:first-child issues
            elem.css({ "display": ((elem.css("display") == "none") ? "none" : "block"), "position": ((elem.css("position") == "absolute") ? "absolute" : "relative"), "overflow": "visible" }).append("<div class=\"corner r" + radiusType + "LT\"></div><div class=\"corner r" + radiusType + "TR\"></div><div class=\"corner r" + radiusType + "RB\"></div><div class=\"corner r" + radiusType + "BL\"></div>");
        }
    },
    // Open-Close boxes
    "togglebox": function(box) {
        var head = box.find("[data-toggle=head]:eq(0)");
        var body = box.find("[data-toggle=body]:eq(0)").css({ "display": (box.hasClass("opened")) ? "block" : "none" });
        if (body.css("float") == "none") {
            var display = body.css("display");
            body.css({ "display": "block" }).css({ "width": body.width() + "px" }).css({ "float": "left", "display": display });
        }
        head.click(function() {
            if (body.is(":not(:animated)")) {
                head.addClass("disabled");
                if (box.hasClass("opened")) {
                    body.slideUp("fast", function() { head.removeClass("disabled"); }).fadeOut("slow");
                    box.removeClass("opened");
                    head.attr("title", sbWeb.ui.translate("open"));
                }
                else {
                    body.slideDown("fast", function() { head.removeClass("disabled"); }).css({ "visibility": "hidden", "display": "block" });
                    box.addClass("opened");
                    window.setTimeout(function() { body.css({ "display": "none", "visibility": "visible" }).fadeIn("slow").dequeue(); }, 150);
                    head.attr("title", sbWeb.ui.translate("close"));
                }
            }
        }).bind("mouseenter mouseleave",
			function() { head.toggleClass("hover"); }
		).addClass("hand").attr("title", (box.hasClass("opened")) ? sbWeb.ui.translate("close") : sbWeb.ui.translate("open")).prepend("<span class=\"arrow\"></span>");
    },
    // Overlay call-back
    "overlayCallBack": function() {
        $("#popupBox .outerBox .outerHeader:not(:has(a)), #popupBox .outerBox .outerHeader a:first-child, #popupBox .outerBox .innerHeader:not(:has(a)), #popupBox .outerBox .innerHeader a:first-child, #popupBox .button:not(ul, .go), #popupBox .button a, #popupBox .btnLink a, #popupBox .form1ColHeader, #popupBox .fieldSetHeader, #popupBox .column h4").each(function() {
            sbWeb.ui.roundcorner($(this), "3");
        });
        // Funding overlay empty error boxes (fix of DEV issue)
        $("#popupBox #divFunding .errormsg:empty").removeClass("errormsg");
        // IE6 fixing
        if (typeof (DD_belatedPNG) != "undefined") {
            // Fix :first-child for IE6
            $("#popupBox ul > li:first-child, #popupBox table > tbody > tr:first-child, #popupBox table tr th:first-child").addClass("first-child");
            // Input type fix
            $("#popupBox input[type=text]").addClass("text");
            $("#popupBox input[type=password]").addClass("password");
            $("#popupBox input[type=checkbox]").addClass("checkbox");
        }
        $("#popupBox #registrationForm #PersonalDetailsFieldSet:eq(0)").ajaxComplete(function() {
            // Lookup address buttons in retistration form
            $("#popupBox .btnLink a").each(function() {
                sbWeb.ui.roundcorner($(this), "3");
            });
        });
    },
    // MyAccount call-back
    "myAccountCallBack": function() {
        $("#sape.myAccounts .outerBox .outerHeader:not(:has(a)), #sape.myAccounts .outerBox .outerHeader a:first-child, #sape.myAccounts .outerBox .innerHeader:not(:has(a)), #sape.myAccounts .outerBox .innerHeader a:first-child, #sape.myAccounts .button:not(ul, .go), #sape.myAccounts .button a, #sape.myAccounts .btnLink a, #sape.myAccounts .column h4").each(function() {
            sbWeb.ui.roundcorner($(this), "3");
        });
        // IE6 fixing
        if (typeof (DD_belatedPNG) != "undefined") {
            // Fix :first-child for IE6
            $("#sape.myAccounts ul > li:first-child, #sape.myAccounts table > tbody > tr:first-child, #sape.myAccounts table tr th:first-child").addClass("first-child");

            // Input type fix
            $("#sape.myAccounts input[type=text]").addClass("text");
            $("#sape.myAccounts input[type=password]").addClass("password");
            $("#sape.myAccounts input[type=checkbox]").addClass("checkbox");
        }
    },
    // Left navigation hide 3rd menu level
    "navLeft3rdLevelHide": function() {
        $("#navLeft ul.menu > li > ul > li > ul > li > ul").hide();
        $("#navLeft ul.menu > li > ul > li > ul > li > a").removeClass("opened");
    },
    // Promotions banners hide empty groups
    "promotionsHideEmptyGroups": function() {
        // Hide empty groups
        $(".outerBox.promotions > ul.groups > li").each(function() {
            if ($(this).find("ul li").length < 1) $(this).addClass("hide");
        });
        // Hide the whole box if no promotions
        if ($(".outerBox.promotions > ul.groups > li:not(.hide)").length < 1) $(".outerBox.promotions").addClass("hide");
    },
    "init": function() {
        // Today's and Next events DEV module fix
        var nextEvents = $("#content .aBox.nextevents");
        nextEvents.wrapInner("<div class=\"hideListSeparators\"></div>");
        nextEvents.each(function() {
            if ($(this).find(".row").length < 1) $(this).addClass("hide");
        });
        // Create rounded corners
        $(".outerBox, #betBasket, #embeddedGamesBox, #sape.myAccounts, #content .aBox.nextevents").each(function() {
            sbWeb.ui.roundcorner($(this), "1");
        });
        $(".imgOuter").each(function() {
            sbWeb.ui.roundcorner($(this), "2");
        });
        $(".outerBox .outerHeader, .outerBox .innerHeader, #navLeft .header, #navRight .box, .btnLink a, #sape.myAccounts .bar, .aBox.nextevents .mainHeader, #embeddedGamesBox .mainHeader, #content .caption, #betBasket .mainHeader, #betBasket ul.tabs li").each(function() {
            sbWeb.ui.roundcorner($(this), "3");
        });
        var allbuttons = $(".button");
        allbuttons.not("ul, .go").each(function() {
            sbWeb.ui.roundcorner($(this), "3");
        });
        allbuttons.find("a").each(function() {
            sbWeb.ui.roundcorner($(this), "3");
        });
        $("#betBasket").ajaxComplete(function() {
            sbWeb.ui.roundcorner($("#betBasket"), "1"); // Rounded corners recreated after betslip refreshed
            sbWeb.ui.roundcorner($("#betBasket .mainHeader"), "3");
            sbWeb.ui.roundcorner($("#betBasket ul.tabs li"), "3");
        });
        // Ticker
        $("[data-ticker]").each(function() {
            sbWeb.ui.ticker($(this), $(this).attr("data-ticker"));
        });
        // Limited children view in box
        $("[data-showonly]").each(function() {
            sbWeb.ui.showonly($(this), $(this).attr("data-showonly"));
        });
        // Rounded corners
        $("[data-roundcorner]").each(function() {
            sbWeb.ui.roundcorner($(this), $(this).attr("data-roundcorner"));
        });
        // Open-Close boxes
        $("[data-toggle=box]").each(function() {
            sbWeb.ui.togglebox($(this));
        });
        // Sports left navigarion
        sbWeb.sports.init("navLeft");
        // MyAccount hoverable bars
        sbWeb.sports.init("myAccount");
        // Homepage headlines
        sbWeb.sports.init("headlines");
        // Promotions banners hide empty groups
        sbWeb.ui.promotionsHideEmptyGroups();
        // Hide empty slide-shows (when slides managed via Insider)
        $(".outerBox.top:has(.banner ul.slide-show):not(:has(.banner ul.slide-show li))").addClass("hide");
        // Left navigation
        // 2nd level expandable submenus
        $("#navLeft ul.menu > li > ul > li:has(ul) > .headerSub > a").click(function() {
            sbWeb.ui.navLeft3rdLevelHide(); // hide 3rd menu level
            $(this).toggleClass("opened").parent(".headerSub").parent("li").children("ul").slideToggle("fast");
            return false;
        }).wrapInner("<span></span>"); // span is used for the arrow icon
        // 3rd level submenus
        $("#navLeft ul.menu > li > ul > li:has(ul) > ul > li:has(ul) > a:first-child").each(function() {
            $(this).click(function() {
                sbWeb.ui.navLeft3rdLevelHide(); // hide 3rd menu level
                $(this).addClass("opened");
                $(this).parent("li").children("ul:eq(0)").css("margin-top", -$(this).parent("li").children("a:eq(0)").outerHeight() + "px").fadeIn("fast");
                return false;
            }).attr("href", "#").parent("li").children("ul:first")
				.prepend("<li><a class=\"close\" href=\"#\">" + sbWeb.ui.translate("close") + "</a></li>").children("li").children("a:first").click(function() {
				    sbWeb.ui.navLeft3rdLevelHide();
				    return false;
				}); // Inserting close 3rd level submenu links
        });
        // Right navigation - copy behaveour to image
        $("#navRight .box .image").each(function() {
            if ($(this).parent().find("a.button").length > 0) {
                if ($(this).parent().find("a.button").get(0).onclick) eval("$(this).parent().find(\"a.button\").click(function(){" + $(this).parent().find("a.button").attr("onclick").toString().replace("javascript:", "") + ";}).attr(\"onclick\", \"\");");
                $(this).parent().find("a.button").click(function(e) { if (typeof (e.result) != "undefined") $(this).attr("return", e.result.toString()); });
                $(this).attr("href", $(this).parent().find("a.button").attr("href")).click(function() { $(this).parent().find("a.button").click(); if ($(this).parent().find("a.button").attr("return") == "false") return false; });
            }
        });
        // Change language custom dropdown menu
        $("ul#customChangeLanguage").data("heightMin", $("ul#customChangeLanguage").height())
			.css({ "visibility": "hidden", "display": "block", "height": "auto" })
			.data("heightMax", $("ul#customChangeLanguage").height())
			.css({ "visibility": "visible", "height": $("ul#customChangeLanguage").data("heightMin") + "px" })
			.click(
				function(e) {
				    if (!$(this).hasClass("opened")) {
				        $(this).addClass("opened");
				        $(this).stop(true).animate(
							{ height: $(this).data("heightMax") + "px" },
							"fast",
							function() {
							}
						);
				        return false;
				    }
				}
			).mouseleave(
				function() {
				    $(this).stop(true).animate(
						{ height: $(this).data("heightMin") + "px" },
						"fast",
						function() {
						    $(this).removeClass("opened");
						}
					);
				}
		);
    }
}

// Sportsbook data object
if(typeof(sbWeb.sports)=="undefined" || sbWeb.sports==null) sbWeb.sports = {
	"init": function(section) {
		switch(section) {
			case "navLeft":
				$("#navLeft a#modLayoutLeftSport230").wrapInner("<span></span>"); // Span needed for inplay Icon
				break;
			case "rightNav":
				break;
			// MyAccount hoverable bars
			case "myAccount":
				$("#sape.myAccounts .bar").each(function() {
					var bar = $(this);
					bar.click(function() {
						if(bar.hasClass("awake")) bar.attr("title", sbWeb.ui.translate("close"));
						else bar.attr("title", sbWeb.ui.translate("open"));
					}).bind("mouseenter",
						function() { bar.addClass("hover"); }
					).bind("mouseleave",
						function() { bar.removeClass("hover"); }
					).addClass("hand").attr("title", (bar.hasClass("awake"))?sbWeb.ui.translate("close"):sbWeb.ui.translate("open"));
				});
				break;
			// Homepage headlines
			case "headlines":
				// Hide empty groups
				$(".outerBox.headlines > ul.groups > li").each(function() {
					if($(this).find("ul li.event").length<1) $(this).addClass("hide");
				});
				// Hide the whole box if no headlines
				if($(".outerBox.headlines > ul.groups > li:not(.hide)").length<1) $(".outerBox.headlines").addClass("hide");
				break;
			default:
				;
		}
	}
}

// IE6 fix Document ready 
$(document).ready(function() {
	// IE6 fixing
	if(typeof(DD_belatedPNG)!="undefined") {
		$("body").addClass("ie6");
		// Fix :first-child for IE6
		$("ul > li:first-child, table > tbody > tr:first-child, table tr th:first-child, #navRight > .box:first-child, #boxContent .sub .box").addClass("first-child");
		// Input type fix
		$("input[type=text]").addClass("text");
		$("input[type=password]").addClass("password");
		$("input[type=checkbox]").addClass("checkbox");
	}
});

// Document ready 
$(document).ready(function() {
	// Initialize
	sbWeb.ui.init();
	// Instant games popup window hardcoded background (fix of DEV issue)
	$("body#games").parent("html").addClass("instantGamePopup");
});

/*
	Descr: 	 Javascript class for including various leaderboards, consult wiki for more information 
	Creator: Daniel K. Mouritsen (daniel.mouritsen@sportingbet.com)
*/

sbWeb.Leaderboard = function() 
{
	var requestUrl = null;
	var requestParams = null;
	var tableElement = null;
	var pagenationElement = null;
	
	var numElementPerPage = 15;
	var classNames = {pagenationLink: "lbPagenationLink", pagenationLinkSelected: "selected",
					  oddRow:"lbRowOdd", evenRow: "lbRowEven", highlight: "highlighted"};
	var thisRef = null;
	var boolLoaded = false;
	
	var prizes = null;
	var highLightRow = null;
	var searchPos = null;


	this.init = function(pUrl, pRequestVars, pSelectors, pNumElements) 
	{
		requestUrl = pUrl;
		requestParams = pRequestVars;
		tableElement = $(pSelectors.tableSelector + " tbody");
		pagenationElement = $(pSelectors.pagenationSelector);
		if(pNumElements) numElementPerPage = pNumElements;
		thisRef = this;
	}
	
	this.addPrizes = function(pFrom, pTo, pString) 
	{
		if(prizes == null) prizes = new Array();
		prizes.push([pFrom, pTo, pString]);	
	}

	this.getPrize = function(pIndex) 
	{
		for(var i = 0; i < prizes.length; i++) 
		{
			if(prizes[i][0] <= pIndex && prizes[i][1] >= pIndex) 
			{
				return prizes[i][2];
			}
		}	
	}
	
	this.setCSSNames = function(pLinkClass, pSelectedLinkClass) 
	{
		if(pLinkClass && pSelectedLinkClass) {
			pagenationLink = pLinkClass;
			pagenationLinkSelected = pSelectedLinkClass;
		}
	}
	
	this.gotoPosition = function(pPos) 
	{
		searchPos = pPos;
		var pNum = this.updateHLPos();
		this.doRequest(pNum);
	}
	
	this.updateHLPos = function() 
	{
		if(searchPos != null) 
		{
			var pageNumber = Math.ceil(searchPos/numElementPerPage);
			highLightRow = (searchPos - ((pageNumber-1)*numElementPerPage));
			return pageNumber;
		}
	}
	

	this.doRequest = function(pPage) 
	{
		requestParams.pageNumber = 1;
		if(pPage) { requestParams.pageNumber = pPage; }
		requestParams.resultsPerPage = numElementPerPage;
		$.ajax({url: requestUrl, data: requestParams, dataType: "xml", cache: false, success: handleRequest});
	}
	
	var handleRequest = function(pRequest) 
	{				
		if(boolLoaded) { tableElement.filter("tbody").children().remove(); updatePagenation($(pRequest).find("leaderboard").attr("pageNumber"));}
		else { createPagenation($(pRequest).find("leaderboard")); }
		
		$(pRequest).find("row").each(populateTable);
		
		boolLoaded = true;
	}
	
	var populateTable = function(pRowNum)
	{
		var row = $("<tr/>");
		
		if((pRowNum+1) % 2 == 0) {row.addClass(classNames.evenRow);}
		else {row.addClass(classNames.oddRow);}
		
		if(pRowNum+1 == highLightRow && searchPos != null) row.addClass(classNames.highlight);
		
		var pos = (requestParams.pageNumber-1) * numElementPerPage + pRowNum + 1;  
		
		$(this).children().each(function(){
			var cell = $("<td/>");
			cell.append($(this).attr("value"));
			row.append(cell);
		});
			
		if(prizes) 
		{
			var cell = $("<td/>");
			cell.append(thisRef.getPrize(pos));
			row.append(cell);			
		}
		
		tableElement.append(row);
	}
	
	var createPagenation = function(pObj)
	{
		var numCurrentPage = pObj.attr('pageNumber');
		var numPages = pObj.attr('totalPages');
		
		var span = null;
		for (var i = 0; i < numPages; i++)
		{
			span = $("<span/>");
			span.html(i+1);
			span.addClass(classNames.pagenationLink);
			span.click(handleClick);
			if(i == numCurrentPage-1)
			{
				span.addClass(classNames.pagenationLinkSelected);
			}
			pagenationElement.append(span);
			pagenationElement.append(" ");
		}
	}
	
	var updatePagenation = function(pPage) 
	{
		$("." + classNames.pagenationLinkSelected).removeClass(classNames.pagenationLinkSelected);
		$("span." + classNames.pagenationLink).eq(pPage);
	}
	
	var handleClick = function() 
	{
		searchPos = null;
		//thisRef.updateHLPos(searchPos);
		$("." + classNames.pagenationLinkSelected).removeClass(classNames.pagenationLinkSelected);
		$(this).addClass(classNames.pagenationLinkSelected);
		thisRef.doRequest($(this).html());
	}
}

/* ---------------------------------- Leaderboard code ENDS HERE ------------------------------ */


/**************************** INSERT YOUR DOMAIN RELATED CODE BELOW **********************************/
/*                                Please do not change the code above                                */
/*                                 which is the same for all domains                                 */
/*****************************************************************************************************/

// User Interfase Translations - please translate and make sure you save the file in UTF-8
sbWeb.ui.translation["previous"] = "previous";
sbWeb.ui.translation["next"] = "next";
sbWeb.ui.translation["open"] = "open";
sbWeb.ui.translation["close"] = "close";


// Shows Hides div layer
function showCalendar(showMonth) {
	var mArr = new Array("january","february","march","april","may");
	for (var i=0;i<mArr.length;i++)
	{
		var thisMonth = mArr[i];
		if(showMonth == thisMonth)
		{
			if(document.layers)
			{	
				document.layers[thisMonth].visibility = "show";
				document.layers[thisMonth].display = "";
			}
			else if(document.getElementById) 
			{
				document.getElementById(thisMonth).style.visibility = "visible";
				document.getElementById(thisMonth).style.display = "";
			}
			else 
			{
				document.all(thisMonth).style.visibility = "visible";
				document.all(thisMonth).style.display = "";
			}
		}
		else
		{
			if(document.layers)
			{	
				document.layers[thisMonth].visibility = "hide";
    	        document.layers[thisMonth].display ="none";		
			}
			else if(document.getElementById) 
			{
				document.getElementById(thisMonth).style.visibility = "hidden";
				document.getElementById(thisMonth).style.display = "none";
			}
			else 
			{
				document.all(thisMonth).style.visibility = "hidden";
				document.all(thisMonth).style.display = "none";
			}
		}
	}
}

ContactUsPhoneUpdate = function(f, d) 
{
    var p_num = new Array();

    p_num[0] = "";//This space is for the default number, i.e Dialing from the U.K. = 0800...
    p_num[1] = "00 353 1511 0840";//Australia
    p_num[2] = "00 353 1511 0840";//Belgium
    p_num[3] = "00 353 1511 0840";//Canada
    p_num[4] = "00 353 15110804";//Denmark
    p_num[5] = "00 353 16297338";//Finland 
    p_num[6] = "00 353 15110830";//France
    p_num[7] = "0800 028 0348";//Germany
    p_num[8] = "00 353 1511 0840";//Holland
    p_num[9] = "800 908102"; //Hong Kong
    p_num[10] = "00 353 15110829";//Italy
    p_num[11] = "1800 803316";//Malaysia
    p_num[12] = "00 353 15110842";//Norway
    p_num[13] = "00 353 16297318";//South Africa
    p_num[14] = "+44 (0)20 7553 4162";//Singapore
    p_num[15] = "00 34 9028 88288";//Spain
    p_num[16] = "00 353 15110805";//Sweden 
    p_num[17] = "00800 142 030 463";//Turkey
    p_num[18] = "0800 0280348";//UK
    p_num[19] = "001 800 1562 030463";//Thailand
    p_num[20] = "00 353 1511 0840";//Singapore
    p_num[21] = "00 353 16297320";//Japan

	p_num[0] = d;
	f.code.value = p_num[f.country.selectedIndex]
}

function gotoCasinoDownload()
{
	gotoDefaultCasinoDownload();
}

function submitCasinoDownload() {
    gotoDefaultCasinoDownload();
}

// Used to start instant play casino, and then redirect to the beginner's room, instant play casino.
function gotoInstant() {
    gaInstantCasino();
	LaunchIgamesSVC();
}

// Followng 4 functions are moved from \s\js\sc.js

function OpenWindow(linkAddress)
{
	window.open(linkAddress, "Betting", "width=600,height=470,resizable,scrollbars");
}

function pop(theURL,winName,features)
{
	window.open(theURL,winName,features);
}

function gotoContact(){
	//alert("Display Contact Info:");
	window.opener.location.href ="/t/forms/contactUs.aspx";
	window.close();
}	

function gotoWinnings(currentPPID)
{
	window.opener.location = window.opener.location.toString().replace(/\?.*/, "")+"?useraction=withdraw&currentPPID="+currentPPID;
	window.close();
}

$(document).ready(function() {
	// Functionality for Collapsing definitions lists - RREPKA
	if($(".collapsing-definition-list").length>0) {
		$(".collapsing-definition-list").each(
			function(i) {
				$(this).find("dl > dd").hide();
				if(!$(this).find(".collapsing-definition-list-show").length>0) $(this).prepend('<div class="collapsing-definition-list-show">Show</div>');
				if(!$(this).find(".collapsing-definition-list-hide").length>0) $(this).prepend('<div class="collapsing-definition-list-hide">Hide</div>');
				$(this).find(".collapsing-definition-list-show").hide();
				$(this).find(".collapsing-definition-list-hide").hide();
				$(this).find("dl dd").append('<a class="close">'+$(this).find(".collapsing-definition-list-hide").text()+'</a>');
				$(this).find("dl dd > a.close").attr("href", "#").click( function() {
					$(this).parent("dd").slideToggle("fast");
					$(this).parent("dd").prev("dt").children("a").attr("title", ($(this).parent("dd").prev("dt").children("a").attr("title")==$(this).parents(".collapsing-definition-list").find(".collapsing-definition-list-show").text())?$(this).parents(".collapsing-definition-list").find(".collapsing-definition-list-hide").text():$(this).parents(".collapsing-definition-list").find(".collapsing-definition-list-show").text());
					return false;
				})
				$(this).find("dl dt a").attr("href", "#").attr("title", $(this).find(".collapsing-definition-list-show").text()).click( function() {
					$(this).parent("dt").next("dd").slideToggle("fast");
					$(this).attr("title", ($(this).attr("title")==$(this).parents(".collapsing-definition-list").find(".collapsing-definition-list-show").text())?$(this).parents(".collapsing-definition-list").find(".collapsing-definition-list-hide").text():$(this).parents(".collapsing-definition-list").find(".collapsing-definition-list-show").text());
					return false;
				});
			}
		);
	}
	// End Functionality for Collapsing definitions lists
});
// JavaScript Document for touchPoint.ascx
function showHideOneRandom(nameBase) {
	//for block elenents styled inline display:none
	//string nameBase - e.g. 'myDivId' when ids are myDivId1, myDivId2, ...
	if(document.getElementById(nameBase+"1")) {
		howMeny=whichOne=0;
		for(i=1; document.getElementById(nameBase+i); i++) howMeny=i;
		whichOne=((new Date()).getSeconds())%howMeny+1;
		document.getElementById(nameBase+whichOne).style.display="block";
		return nameBase+whichOne;		
	}
}

// onLoad tracking for touchPoint.ascx
function MultiTrackIt() {
	dcsMultiTrack('WT.ad', arguments[0]);
}

$(document).ready(function() { 

});


$(window).load(function() {
// Automatic download of the poker client - on any poker section url?EmaildownloadPokerClient=yes
if(location.href.indexOf("EmaildownloadPokerClient=yes") > 0) gotoDownload();
// End - Automatic download of the poker client

// Automatic display of Privacy Statemet - on any section url?EmailshowPrivacy=yes
            if(location.href.indexOf("EmailshowPrivacy=yes") > 0) SB.base.OpenDiv('/t/info/InformationPopup.aspx?info=privacy','popBadSelect2','popVeil2','popLayer2');
// Automatic display of Privacy Statemet 

            // Automatic display of Casino signup bonus - on any section url?CasinoSignupBonus=yes
            if(location.href.indexOf("CasinoSignupBonus=yes") > 0) SB.base.OpenDiv('/t/casino/promotions/signup-bonus-09/choose-popup.aspx','popBadSelect2','popVeil2','popLayer2');
            // Automatic display of Casino signup bonus
});


//---------------------------------------------------------------------
// EURO 2012 BetBank - overlay advertisements
// ZHeczei @ SportingBet 
//---------------------------------------------------------------------
if(typeof(sbWeb)=="undefined" || sbWeb==null) var sbWeb = {};
if(typeof(sbWeb.bbA)=="undefined" || sbWeb.bbA==null) sbWeb.bbA = 
{
	"servicesPath": "/php/euro2012/index.php?module=Services&action=getDetails",
	"cookieNameStarter": "SbBetBank_",
	"serverTime": '',
	"sbUserId": 0,	
	"currentMonth": 0,
	"currentDay": 0,
	"currentDateTimeStamp": 0,
	"hourDifferenceBetweenYourDomainAndUK": 0,
	"havePromoCarousel":0,
	"stages" : new Array(
		[15,11,2011],
		[19,11,2011],
		[24,11,2011],
		[25,11,2011],
		[28,11,2011],
		[29,11,2011],
		[10,12,2011],
		[15,12,2011],
		[22,12,2011],
		[15,1,2012],
		[23,1,2012],
		[11,2,2012],
		[19,2,2012],
		[25,2,2012],
		[29,2,2012],
		[06,3,2012],
		[15,3,2012],
		[17,3,2012],
		[25,3,2012],
		[05,4,2012],
		[14,4,2012],
		[19,4,2012],
		[25,4,2012],
		[26,4,2012],
		[5,5,2012],
		[14,5,2012],
		[19,5,2012],
		[26,5,2012],
		[29,5,2012]
	),
	
	"displayOverlay": function(status, lapsed){
		var contentType = 'unknown';
		//alert(status+" "+lapsed);
		if(sbWeb.bbA.currentDay<12){ // overlay just in the first 12 days of the month
			if(status=='notoptedin'){
				if(lapsed==0){
					contentType='active';
				}
				if(lapsed==1){
					contentType='lapsed';
				}
			}
			if(status=='betbankday'){
				contentType='betbankday';
			}
			
			// cookies
			var cookieName = sbWeb.bbA.cookieNameStarter + contentType + "_" + sbWeb.bbA.sbUserId + "_" + sbWeb.bbA.currentMonth;
			
			if($.cookie(cookieName) != 1){
				$.cookie(cookieName, 1, { expires: 20, path:'/' });
				SB.base.OpenDiv('/offers/euro2012/betbank/popups/overlay.aspx?contenttype='+contentType,'popBadSelect1','popVeil1','popLayer1');
			}
		}
		//SB.base.OpenDiv('/offers/euro2012/betbank/popups/overlay.aspx?contenttype='+contentType,'popBadSelect1','popVeil1','popLayer1');
	},
	
	"dateCalculations": function(){
		// DD/MM/YYY HH:MM:SS
		// var d = new Date(year, month, day, hours, minutes, seconds, milliseconds);
		var msInOneDay=1000*60*60*24
		var a1 = sbWeb.bbA.serverTime.split(" ");
		var a11 = a1[0].toString().split("/");
		var a12 = a1[1].toString().split(":");
		
		sbWeb.bbA.currentMonth = a11[1]-1;
		sbWeb.bbA.currentDay = a11[0];
		
		var serverCurrentDate = new Date(a11[2], (a11[1]-1), a11[0], a12[0], a12[1], a12[2], 1);
		var serverCurrentDateTimeStamp = serverCurrentDate.getTime();
		sbWeb.bbA.currentDateTimeStamp = serverCurrentDateTimeStamp + (sbWeb.bbA.hourDifferenceBetweenYourDomainAndUK*1000*60*60); // timezone difference addition
		//sbWeb.bbA.currentDate = new Date(sbWeb.bbA.currentDateTimeStamp);
	},
	
	"checkIfItsBetBankDay": function(){
		var result = 0;
		
		for(var i=0; i<sbWeb.bbA.stages.length; i++){
			var stageDate = new Date(sbWeb.bbA.stages[i][2], (sbWeb.bbA.stages[i][1]-1), sbWeb.bbA.stages[i][0], 0, 0, 1, 0);
			var stageDateTimeStamp = stageDate.getTime();
			
			if(sbWeb.bbA.currentDateTimeStamp<stageDateTimeStamp){
				if(i==0){ 
					// we are before the first stage
				} else {
					// check if i-1 stage is active
					var previouslyStartedStageEndDate = new Date(sbWeb.bbA.stages[(i-1)][2], ((sbWeb.bbA.stages[(i-1)][1])-1), sbWeb.bbA.stages[(i-1)][0], 23, 59, 59, 0);
					var previouslyStartedStageEndDateTimeStamp = previouslyStartedStageEndDate.getTime();
					
					if(sbWeb.bbA.currentDateTimeStamp<previouslyStartedStageEndDateTimeStamp){
						//-------------------------
						// active stage-> result=1
						//-------------------------
						return 1;
						//-------------------------
						//-------------------------
					} else {
						// no active stage
					}
				}
			
				break;
			}
		}
		
		return result;
	},
	
	"getDetailsAndManageFurtherAction" : function(){
		$.ajax({
			url: sbWeb.bbA.servicesPath,
			type: "GET",
			dataType: "xml",
			data: {sbpin : sbWeb.bbA.sbUserId},
			success: function(data){
				var response = $(data).children("response");
				
				//------------------------------------------
				// check if not allowed
				//------------------------------------------
				if(response.attr("success") == 0 && response.attr("error") == 50){
					// functions for not allowed users
					$(".betBankBanner").remove();
				} else {
					// show the banner
					$(".betBankBanner").show();
					
					// dateCalculations
					sbWeb.bbA.dateCalculations();
					
					//------------------------------------------
					// check if not opted in
					//------------------------------------------
					
					if(response.attr("success") == 0 && ( response.attr("error") == 60 || response.attr("error") == 61 || response.attr("error") == 62 )){
						// functions for not opted in users
						sbWeb.bbA.displayOverlay('notoptedin', response.attr("lapsed"));
					} else {
						// functions for opted in users
						// CHECK IF IT'S A BETBANK DAY. IF YES, DISPLAY THE OVERLAY
						if( sbWeb.bbA.checkIfItsBetBankDay()==1 ){
							sbWeb.bbA.displayOverlay('betbankday',0);
						}
					}
				}
				
				if (sbWeb.bbA.havePromoCarousel){
					sbWeb.promoTop.init("bannerSlideShow");
				}

			}
		});
	}
}
$(document).ready(function() {
	if(!(sbWeb.bbA.sbUserId==null || sbWeb.bbA.sbUserId == 0)){
		sbWeb.bbA.getDetailsAndManageFurtherAction();
	} else {
		if (sbWeb.bbA.havePromoCarousel){
			sbWeb.promoTop.init("bannerSlideShow");
		}
	}
});

