﻿//<![CDATA[
function setModulesHeightCampaign() {
    var $rwEl = $(".rowwrapper");
    if ($rwEl.length > 0) {
        $rwEl.each(function () {
            var colHeight = 0;
            var headingHeight = 0;
            var currentEl = this;
            if (($(".box-content", currentEl).length > 1 || $(".image-box", currentEl).length > 1) && $(".FlashPnl", currentEl).length > 0) {
                $(".box-content", currentEl).each(function () {
                    var tmpHeightHead = $(currentEl).prev().height();
                    var tmpHeight = $(currentEl).height();
                    if (colHeight < tmpHeight)
                        colHeight = tmpHeight;
                    if (headingHeight < tmpHeightHead)
                        headingHeight = tmpHeightHead;
                });
                //                 $(".image-box", this).each(function () {
                //                    var tmpHeightHead = $(this).prev().height();
                //                    var tmpHeight = $(this).height();
                //                    if (colHeight < tmpHeight)
                //                        colHeight = tmpHeight;
                //                    if (headingHeight < tmpHeightHead)
                //                        headingHeight = tmpHeightHead;
                //                });

                $(".GeneralHeader", currentEl).height(headingHeight);
                $(".box-content", currentEl).height(colHeight);
            }
        });
    }
}
function setModulesHeight() {
    // Set same height on module boxes
    if ($(".rowwrapper").length > 0) {
        $(".rowwrapper").each(function () {
            var colHeight = 0;
            var headingHeight = 0;
            if ($(".box-content", this).length > 1 && $(".FlashPnl", this).length < 1) {
                $(".box-content", this).each(function () {
                    var tmpHeightHead = $(this).prev().height();
                    var tmpHeight = $(this).height();
                    if (colHeight < tmpHeight)
                        colHeight = tmpHeight;
                    if (headingHeight < tmpHeightHead)
                        headingHeight = tmpHeightHead;
                });

                $(".GeneralHeader", this).height(headingHeight);
                $(".box-content", this).height(colHeight);
            }
        });
    }
}

function openLightboxWin(wSource, wWidth, wHeight)
{
    $.colorbox({ width: wWidth + "px", height: wHeight + "px", iframe: true, href: wSource, speed: 100, transition: 'fade' });
}


$(window).load(function () {

    setModulesHeightCampaign();

    // If game, reload account balance and bonus..
    function reloadBalanceAndBonus() {
        if ($('.balanceVal').length != 1 && $('.loggedInBonusPanel ul').length != 1)
            return;
        $.ajax({
            url: "/site/cms/templates/ajaxDepositHeader.aspx",
            type: "post",
            cache: false,
            success: function (data) {
                if ($('.balanceVal').length > 0) {
                    $('.balanceVal').html($('.balanceVal', data).html());
                }
                if ($('.loggedInBonusPanel ul').length > 0) {
                    $('.loggedInBonusPanel ul').html($('.loggedInBonusPanel ul', data).html());
                }

                var $bingoRight = $("#bingoRight .top");
                if ($bingoRight.length > 0) {
                    $bingoRight.html($('.left', data).html() + "<ul>" + $('.loggedInBonusPanel ul', data).html() + "</ul>");
                }
            }
        });
    }

    // Start timer that handles balance/bonus updates
    setInterval(reloadBalanceAndBonus, 10000);

    if ($(".bonusInAccount").length > 0) {
        $('<div class="redInfoTxt">' + $(".bonusInAccount").text() + '</div>').insertBefore('._withdrawal');
    }
    else {
        // Reposition bottom if not logged on
        if ($("#bingoRight .bottom").length > 0)
            $("#bingoRight .bottom").css("top", "40px");
    }

    if ($(".winnerList").length < 1)
        setModulesHeight();
    // Fix social bar with bingo
    //    if ($("#socialbar").length > 0 && $(".bingoWrapper").length > 0) {
    //        $('<div style="background-color:rgb(210,119,12);position:absolute;bottom:0px;height:34px;left:50%;margin-left:-473px;margin-top:0;width:943px;z-index:999999999;">&nbsp;</div>').prependTo('body');
    //        
    //    }

});

$(document).ready(function () {

    // Winner list init (set the height of all winner modules)
    var $moduleWinList = $(".Module1ColWinners");
    if ($moduleWinList.length > 0) {
        $moduleWinList.each(function (indx) {
            var $moduleWin = $(this);
            $moduleWin.addClass("winnerModule" + indx);
            $(".winners", $moduleWin).html($(".winnerData", $moduleWin).html());
            var winElHeight = $(".winners", $moduleWin).height();
            $(".winners", $moduleWin).css({ "height": winElHeight + "px", "width": "100%", "overflow": "hidden" });
        });
    }

    // Filter loader
    if ($(".m_loader").length > 0) {
        $(".short, .long, .medium").live("click", function () {
            $(".m_loader").show();
        });
    }

    // Analog clock
    $("#jqtp_clock").jqtp();
    $("#jqtp_clock").jqtp_realtime();

    // Fills LoginUser field with value
    if ($(".LoginUser").length > 0)
        $(".LoginUser").val(LoginUsrOrEmailTxt);


    // Play game button pressed
    $(".playGameBtn").click(function (e) {
        e.preventDefault();
        location.href = $("a", this).attr("href");
    });

    // Click on Game favorites
    $(".star").live("click", function () {
        $(this).removeClass("star").addClass("starLoading");
    });

    $(".game-delete").live("click", function () {
        $(this).find("input").css("visibility", "hidden");
        $(this).addClass("smallStarLoading");
    });

    // Empties login fields if default value
    function emptyUser() {
        if ($(".LoginUser").val() == LoginUsrOrEmailTxt) {
            $(".LoginUser").val("");
            $(".LoginUser").focus();
        }
    }
    function emptyPassword() {
        $("#textfield").hide();
        $(".LoginPassword").show();
        $(".LoginPassword").empty();
        $(".LoginPassword").val("");
        $(".LoginPassword").focus();
    }
    // Fills login fields with value if fields are empty
    function fillUser() {
        if ($(".LoginUser").val() == '')
            $(".LoginUser").val(LoginUsrOrEmailTxt);
        showPassword();
    }
    function fillPassword() {
        if ($(".LoginPassword").val() == '') {
            $(".LoginPassword").hide();
            $("#textfield").show();
            $("#textfield").val("Lösenord");
        }
    }

    function showPassword() {
        $(".LoginPassword").show();
        $(".LoginPassword").focus();
        $("#textfield").hide();
    }

    $(".LoginUser").click(emptyUser);
    $(".LoginUser").blur(fillUser);
    $(".LoginText").click(emptyPassword);
    $(".LoginText").keydown(emptyPassword);

    $('.LinkOpenFriend, .OpenUserProfilePage').live('click', function (e) {
        if ($(this).closest(".headerLoggedInAvatar").length > 0) {
            e.preventDefault();
            return;
        }
        $.colorbox({ width: "600px", height: "600px", iframe: true, href: $(this).attr("href"), speed: 100, transition: 'fade' });
    });

    // Avatar
    $('.avatarEditor').live('click', function (e) {
        e.preventDefault();
        $.colorbox({ width: "940px", height: "800px", iframe: true, href: $(this).attr("href"), speed: 100, transition: 'fade', onClosed: function () {
            parent.location.reload();
        }
        });
    });

    /* User Registration Tool tip */
    var toolTipClicked = false;
    var $oldToolTipEl;
    $(".field-wrapper input").mouseover(function () {
        var $toolTipEl = $(".toolTip", $(this).closest(".field-wrapper"));
        if ($toolTipEl.length < 1 || toolTipClicked == true)
            return;
        if ($toolTipEl.length > 1)
            $toolTipEl = $(".toolTip", $(this).closest(".container"));
        $toolTipEl.show();
    }).focus(function (e) {
        var $toolTipEl = $(".toolTip", $(this).closest(".field-wrapper"));
        if ($toolTipEl.length < 1)
            return;
        if ($toolTipEl.length > 1)
            $toolTipEl = $(".toolTip", $(this).closest(".container"));
        $toolTipEl.show();
        if ($oldToolTipEl != null)
            $oldToolTipEl.hide();
        $oldToolTipEl = $toolTipEl;
        toolTipClicked = true;
    }).mouseleave(function () {
        var $toolTipEl = $(".toolTip", $(this).closest(".field-wrapper"));
        if ($toolTipEl.length < 1 || toolTipClicked == true)
            return;
        if ($toolTipEl.length > 1)
            $toolTipEl = $(".toolTip", $(this).closest(".container"));
        $toolTipEl.hide();
        toolTipClicked = false;
    }).blur(function () {
        var $toolTipEl = $(".toolTip", $(this).closest(".field-wrapper"));
        if ($toolTipEl.length < 1)
            return;
        if ($toolTipEl.length > 1)
            $toolTipEl = $(".toolTip", $(this).closest(".container"));
        $toolTipEl.hide();
        toolTipClicked = false;
    });

    // Trigger lightbox for registration
    //$(".usrRegLnk").colorbox({ width: "842px", height: "867px", iframe: true, speed: 200, transition: 'fade' });
    $('.lnk_openCSEmailForm').click(function (e) {
        e.preventDefault();
        function GV(what) {
            var v = PluginDetect.getVersion(what)
            if (v && v != '') {
                return v
            }
            return "false"
        }
        var lnk = $(this).attr("href") + "?d=" + BrowserDetect.browser + "(Version:" + BrowserDetect.version + ")|" + BrowserDetect.OS + "|" + GV('Flash') + "|" + GV('QuickTime') + "|" + GV('WindowsMediaPlayer') + "|" + GV('Silverlight') + ("|" + screen.width + "*" + screen.height) + "&setVals=2";

        $.colorbox({ width: "550px", height: "600px", iframe: true, href: lnk, speed: 100, transition: 'fade' });
    });

    if ($('.lnk_ShowforgottenPswConfirm').length > 0)
        $.colorbox({ width: "400px", height: "600px", iframe: true, href: $('.lnk_ShowforgottenPswConfirm').attr("href"), speed: 100, transition: 'fade' });

    // Trigger lightbox for lost password
    if ($(".lostPassword").length > 0)
        $(".lostPassword").colorbox({ width: "400px", height: "600px", iframe: true, speed: 100, transition: 'fade' });
    //$(".lightbox").colorbox({ width: "842px", height: "867px", iframe: true, speed: 200, transition: 'fade' });

    // Trigger lightbox for login alert
    if ($("#ShowLoginSystemError").length > 0)
        $.colorbox({ width: "552px", height: "317px", inline: true, href: "#ShowLoginSystemError", speed: 200, transition: 'fade' });

    if ($("#LoginAlert").length > 0 && $('.lnk_ShowforgottenPswConfirm').length < 1)
        $.colorbox({ inline: true, href: "#LoginAlert", speed: 200, transition: 'fade' });

    // Trigger lightbox for deposit money
    if ($(".deposit").length > 0) {
        $('.deposit').colorbox({ width: "550px", height: "1000px", iframe: true, speed: 100, transition: 'fade' });

        $('#bingoRight .top').click(function () { $.colorbox({ width: "550px", height: "1000px", iframe: true, href: $('.deposit').attr("href"), speed: 100, transition: 'fade' }); });
    }


    if ($(".myAccountLinks .Item2 a").length > 0)
        $('.myAccountLinks .Item2 a').colorbox({ width: "550px", height: "700px", iframe: true, speed: 100, transition: 'fade' });

    // Trigger lightbox for logout
    if ($("#ShowLogoutMessage").length > 0 && $("#LogoutAlert").length > 0)
        $("#ShowLogoutMessage").colorbox({ inline: true, href: "#LogoutAlert" });

    // Lightbox Popup - Fix mouse-down bg-image on the "close button"
    if ($("#cboxClose").length > 0) {
        $("#cboxClose").mousedown(function () {
            $(this).css("background-position", "0 -95px");
        });
    }

    // Open and close customer service
    $('html').click(function (e) {
        var $el = $(e.target);
        if ($('#headercustomerservice:visible').length > 0 && $el.closest("#headercustomerservice").length < 1) {
            $('#headercustomerservice').hide();
            $('#headercustomerservice').css("z-index", "999");
            $("#headercustomerservicelink").removeClass("selected", "");
            $("#nav").css("z-index", "1000");
        }
        if ($('.loggedInUserMenu:visible').length > 0 && $el.closest(".loggedInUserMenu").length < 1 && $el.closest(".headerLoggedInAvatar").length < 1) {
            $('.myAccountLinks').hide();
            $('.myAccountLinks').css("z-index", "999");
            $("#nav").css("z-index", "1000");
        }
    });

    $("#headercustomerservicelink").click(function (e) {
        e.preventDefault();
        $("#headercustomerservicelink").addClass("selected", "");
        $("#headercustomerservice").show(10, function () {
            // Reposition element to fix IE bug
            $(this).css({ 'right': '1px', 'top': '44px' });
            if ($(this).is(":visible"))
                $("#nav").css("z-index", "-1");
            else
                $("#nav").css("z-index", "auto");
        });
    });

    // Trigger UserMenu
    $(".loggedInUserMenu, .headerLoggedInAvatar").click(function () {
        $el = $(".myAccountLinks");
        if ($el.is(":visible")) {
            $(".myAccountLinks").hide();
            $(".myAccountLinks").css("z-index", "-1");
            $("#nav").css("z-index", "1000");
        }
        else {
            $(".myAccountLinks").show();
            $(".myAccountLinks").css("z-index", "1000");
            $("#nav").css("z-index", "-1");
        }
    });

    // Render div id"subnav-wrapper" if subnav is populated. Remove when fixed in Code behind.
    if ($("#subnav ul").hasClass("nav")) {
        $("#subnav-wrapper").show();
    }

    // temporary code for social bar, to open and close
    $(".profile").click(function () {
        $(".profile-info").toggle();
    });

    $(".favourites").click(function (e) {
        if ($(e.target).hasClass("icon") || $(e.target).hasClass("favourites"))
            $(".favourites-info").toggle();
    });


    $(".history").click(function () {
        $hEl = $(".history-info");
        if ($(".history-info:visible").length > 0)
            $hEl.hide();
        else {
            $hEl.show();
            showHistoryList($hEl);
        }
    });

    // Show history list
    function showHistoryList(hEl) {
        hEl.addClass("loading");
        $.ajax({
            url: "/site/cms/templates/historyListing.aspx",
            type: "post",
            cache: false,
            success: function (data) {
                // Show history list
                $(".history-info").html($("#ajaxContent", data).html());
            }
        });
    }

    // Search
    $(".searchbutton").val("    ");
    if ($(".searchbuttonFriends").length > 0)
        $(".searchbuttonFriends").val("    ");

    function doAjaxSearch(qString, qEl, doNotOpenResult) {

        if (qString.length >= fChrs) {
            qEl.addClass("loading");
            var form = $("form");
            $.ajax({
                url: "/site/cms/templates/search_findasyoutyperesult.aspx?CMS_SearchString=" + qString,
                type: "post",
                cache: false,
                success: function (data) {
                    // Show FAYT result
                    var $resultWrapper = $("#searchResultWrapper", data);
                    if ($resultWrapper.length > 0) {
                        $("#searchResult").html($resultWrapper.html());
                        if ($("#searchResult").html().length > 30 && !doNotOpenResult)
                            $("#searchResult").show();
                        qEl.removeClass("loading");
                    }
                }
            });
        }
        else {
            $("#searchResult").hide();
            $("#searchResult").html("");
            qEl.removeClass("loading");
        }
    }

    if ($(".searchfield").length > 0) {

        $(".searchShowAll").live("click", function (e) {
            e.preventDefault();
            $(".searchbutton").click();
        });

        if ($(".searchfield").val().length > fChrs) {
            var $qEl = $(".searchfield");
            var $qString = $qEl.val();
            doAjaxSearch($qString, $qEl, true);
        }

        $(".searchfield").keyup(function () {
            // Do find as you type search
            var $qEl = $(this);
            var $qString = $qEl.val();

            doAjaxSearch($qString, $qEl);

        }).mouseover(function () {
            if ($(this).val().length >= fChrs) {
                if ($("#searchResult").html().length > 30)
                    $("#searchResult").show();
            }
        });

        $("#search").mouseleave(function (e) {
            $("#searchResult").hide();
        });
    }

    // FAQ left and right columns
    //$(".faqItems li:nth-child(odd)").addClass("left");

    // FAQ - open up and close answers to questions
    $(".faqInfo").click(function () {
        $(this).hide().next().fadeIn();
    });
    $(".faqSelected").click(function () {
        $(this).hide().prev().fadeIn();
    });

    // Check and set FLASH Obj
    var $flshPnl = $(".FlashPnl");
    var $flshCampaignPnl = $(".campaign-wrapper .FlashPnl");
    if ($flshPnl.length > 0) {
        //var campaignShelfString = "";
        var campaignCirclesString = "";
        var FlashPnlCnt = $flshCampaignPnl.length - 1;
        //var $campaignShelf = $("#CampaignBottomShelf");
        var $campaignCircles = $("#CampaignCircles");
        var $campaignContainer = $(".campaignContainer");
        var cnt = 0;
        $flshPnl.each(function (i) {
            var thisPnl = this;
            var tmpFlashLink = $(this).find(".FlashLnk").val();

            var isCampaign = $(thisPnl).closest(".campaign-wrapper").length > 0;

            // Book shelf
            //            if ($campaignShelf.length > 0 && isCampaign) {
            //                var $tmpThumbImg = $(thisPnl).find("div");
            //                campaignShelfString += ('<div><a href="#">' + $tmpThumbImg.html() + '</a><span><img src="/UI/Img/Campaign/glow.png" alt="" /></span></div>');
            //                if (FlashPnlCnt == cnt)
            //                    $campaignShelf.html(campaignShelfString);
            //                cnt++;
            //            }

            //Campaign circles
            if ($campaignCircles.length > 0 && isCampaign) {
                //var $tmpThumbImg = $(thisPnl).find("div");
                //campaignCirclesString += ('<div><a class="" href="#"><img src="/UI/Img/Campaign/inactivecircle.png" alt="" /></a></div>');
                campaignCirclesString += ('<div><a href="#">&nbsp;</a></div>');
                if (FlashPnlCnt == cnt)
                    $campaignCircles.html(campaignCirclesString);
                cnt++;
            }

            if (!$(thisPnl).hasClass("imgPnl")) {
                var tmpHeight = !isCampaign ? ($(this).find(".FlashHeight").length > 0 ? $(this).find(".FlashHeight").val() : 200) : "528";

                // Embed Flash Campaign
                $(this).html('<div id="flashCamp' + i + '">&nbsp;</div>');
                var tmpWidth = !isCampaign ? $("#flashCamp" + i).width() : "1250";

                swfobject.embedSWF(tmpFlashLink, "flashCamp" + i, tmpWidth, tmpHeight, "7", false, false, { wmode: 'transparent' });
                //, scale: 'noscale'
            }
        });

        // Hide book shelf if only 1 campaign is shown
        //        if ($campaignContainer.length < 2)
        //            $campaignShelf.hide();

        // Hide campaign circles if only 1 campaign is shown
        if ($campaignContainer.length < 2)
            $campaignCircles.hide();

    }



});


function refreshWinners(winnerListID, modulePageID) {
    var timeOut = 1500;
    try {
        var winnersInMemory = GetWinnersInMemory(winnerListID);
        if (winnersInMemory.length == 0) {
            readNewWinnersFromServer(winnerListID, modulePageID);
        }
        else {
            slideDownNextWinner(winnersInMemory[0], winnerListID);
            winnersInMemory.shift();
        }
    }
    finally {
        setTimeout("refreshWinners('" + winnerListID + "','" + modulePageID + "')", timeOut);
    }

}

function GetWinnersInMemory(winnerListID) {
    var winnersInMemory = window[winnerListID];
    if (typeof winnersInMemory == 'undefined' || winnersInMemory == null) {
        winnersInMemory = new Array();
    }
    return winnersInMemory;
}

function OkToCallServer(winnerListID) {
    var lastCallTime = window[winnerListID + 'lastCall'];

    if (window['winnersCallingServer'] == 1)
        return 0;

    if (typeof lastCallTime == 'undefined') {
        window[winnerListID + 'lastCall'] = new Date().getTime();
        return 1;
    }
    var millisNow = new Date().getTime();
    var diff = millisNow - lastCallTime;
    if (diff > 5000) {
        window[winnerListID + 'lastCall'] = millisNow;
        return 1;
    }
    return 0;
}

function readNewWinnersFromServer(winnerListID, modulePageID) {
    var firstChild = $(winnerListID + " li:first-child");
    var latestTransactionID = "-1";
    if (firstChild != null && typeof firstChild.attr('transactionID') != 'undefined') {
        latestTransactionID = firstChild.attr('transactionID');
        //Check in memory as well
    }

    if (OkToCallServer(winnerListID) == 1) {
        window['winnersCallingServer'] = 1;
        $.ajax({
            type: 'POST',
            url: '/Site/WebServices/ScriptService.asmx/GetWinnerScriptData',
            data: '{"latestTransactionID": "' + latestTransactionID + '", "modulePageID": "' + modulePageID + '"}',
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            complete: function () {
                var millisNow = new Date().getTime();
                window[winnerListID + 'lastCall'] = millisNow;
                window['winnersCallingServer'] = 0;
            },
            success: function (response) {
                var result = response.d;
                var noWinnersToShow = result.NoWinnersToShow;
                var winnerEntries = result.WinnerEntryList;
                //Do different stuff if latestTransactionID is null, not null or higher than the value from the web service
                if (winnerEntries.length == 1) {

                    var data = winnerEntries[0];
                    slideDownNextWinner(data, winnerListID);
                }
                else if (winnerEntries.length > 1) {
                    if (latestTransactionID == -1) {
                        //First call fade in, maxcount first
                        window[winnerListID] = winnerEntries;
                        switchWinners(winnerListID, noWinnersToShow);
                    }
                    else {
                        window[winnerListID] = winnerEntries;
                        var winnersInMemory = GetWinnersInMemory(winnerListID);
                        slideDownNextWinner(winnersInMemory[0], winnerListID);
                        winnersInMemory.shift();
                    }
                }
                else if (winnerEntries.length == 0) {
                    //Nothing
                }

                var winElHeight = 45 * noWinnersToShow;
                var parentEl = $(winnerListID).closest(".winnerList");
                if (parentEl.length > 0) {
                    if (!parentEl.hasClass("heightIsSet")) {
                        parentEl.css({ "height": winElHeight + "px", "width": "100%", "overflow": "hidden" }).addClass("heightIsSet");
                        if ($(".winnerList").length == $(".heightIsSet").length) {
                            setModulesHeight();
                        }
                    }
                }
            }
        });
    }
}

function getHtmlForWinnerEntry(data, winnerListID) {
    var htmlData = '<li transactionID="' + data.TransactionID + '"><div class="image left"><img src="' + data.AvatarImageURL + '" Height="30" Width="30"/></div><div class="names left"><div class="PlayerName">' + data.Name + '</div><div class="GameDate">' + data.Date + '</div><div class="GameName"><a href="' + data.GameURL + '">' + data.GameName + '</a></div></div><div class="amount left" id="elAmountWon" runat="server">' + data.Amount + '</div></li>';
    return htmlData;
}

function switchWinners(winnerListID, noWinnersToShow) {
    $(winnerListID).hide();
    $(winnerListID).children().remove();

    var winnersInMemory = GetWinnersInMemory(winnerListID);

    for (i = 0; i < noWinnersToShow; i++) {
        if (winnersInMemory.length == 0) {
            break;
        }
        $(winnerListID).prepend(getHtmlForWinnerEntry(winnersInMemory[0], winnerListID));
        winnersInMemory.shift();

    }
    $(winnerListID).fadeIn(1000);
}

function slideDownNextWinner(data, winnerListID, noWinnersToShow) {

    var $li = $(getHtmlForWinnerEntry(data, winnerListID)).prependTo(winnerListID).hide();

    $li.next().animate({
        'margin-top': $li.height()
    }, function () {
        $(this).css('margin-top', '0px');
        $li.fadeIn(250);
    });

    var numberToRemove = $(winnerListID + " > li").size() - data.NoWinnersToShow;
    if (numberToRemove == 1) {
        $(winnerListID + " li:last-child").fadeOut(300, function () {
            $(this).remove();
        });
    }
    else if (numberToRemove > 1) {
        for (i = 0; i < numberToRemove; i++) {
            $(winnerListID + " li:last-child").remove();
        }
    }
}

//]]>
