﻿/// <reference path="jquery-1.4.4.min.js" />

$j = jQuery.noConflict();

window.Settings = {
    EnableDebugging: true,
    TrackEvents: false
};

function dbg(message) {
    if (window.Settings.EnableDebugging) {
        var dbgDiv = $j("#PnlDBG");

        if (dbgDiv.length == 0) {
            dbgDiv = $j("<div id=\"PnlDBG\" />");
            dbgDiv.css({
                "position": "fixed",
                "z-index": 999999,
                "top": "0px",
                "left": "0px",
                "width": "300px",
                "height": "600px",
                "background-color": "#FFFFFF",
                "border": "1px gray solid"
            });

            dbgDiv.dblclick(function () {
                $j(this).css("display", "none");
            });

            dbgDiv.appendTo(document.body);
        }

        dbgDiv.css("display", "block");

        var date = new Date();
        dbgDiv.html(date.getMinutes() + ":" + date.getSeconds() + " - " + message + "<br />" + dbgDiv.html());
    }
}

function Trigger(eventName, param) {
    $j(document).trigger(eventName, param);
}

function PagePartRendered(pagePartName) {
    if (window.Settings.TrackEvents)
        dbg("RenderPart: " + pagePartName);

    Trigger("PagePartRendered", { PartName: pagePartName });
}

function GetKeyFromArgs(e) {
    if (e) {
        if (e.keyCode)
            return e.keyCode;

        if (e.charCode)
            return e.charCode;
    }

    return -1;
}

function PostToPage(target) {
    $j("form").attr("action", target).submit();
}

function ConnectWithFacebook() {
    FB.login(function (response) {
        if (response.session) {
            IsConnectedWithFacebook();
        } 
        else {
            // user cancelled login
        }
    });
}

function IsConnectedWithFacebook() {
    if (window.FB) {
        FB.getLoginStatus(function (response) {
            if (response.session) {

                $j.post('/Settings/StoreAccessToken', { accessToken: response.session.access_token });

                if ($j('div.CommentMetaData').length) {
                    $j('div.CommentMetaData > table').toggle();

                    if ($j('input#CommentName').length) {
                        FB.api('/me', function (response) {
                            $j('input#CommentName').val(response.name);
                        });
                    }
                }

            }
            else {
                // no user session available, someone you dont know
            }
        });
    }
}

function PostToPage(target) {
    $j("form").attr("action", target);
    SubmitForm();
}

function SubmitForm() {
    document.forms[0].submit()
}

// I don't like it - but MVC is unable to just pass my single-ticks. So I have to go this way. :(
// [MB]
function CleanField(item) {
    if (item) {
        var fieldToCleanAttr = $j(item).attr("fieldToClean");

        if (fieldToCleanAttr)
            $j("#" + fieldToCleanAttr).val("");
    }
}

function DisconnectFromFacebook(url) {
    FB.logout(function (response) {
        window.location = url;
    });
}

function BindSelectableRows() {
    $j(".SelectableRow").click(function (e) {
        window.location = $j(this).find("a").attr("href");
        e.preventDefault();
        e.stopPropagation();
    }).mouseenter(function () {
        $j(this).addClass("Selected");
    }).mouseleave(function () {
        $j(this).removeClass("Selected");
    });
}

function BindWoopeeClicks() {
    $j(".WoopeeItem").click(function () {
        var curLink = $j(this).find("a[href^=/]");

        if ((curLink.length > 0) && (curLink.attr("target") != "_blank"))
            window.location = curLink.attr("href");
    });
}

var adMixInStart = 2;
var adMixInInterval = 6;
var lastAdIdx = -1;
var adMovementTimeout = 10000;
var adMovementDuration = 400;
var adMovementDistance = 30;
var adRotationTimeoutHandle = null;
var adWoopees = null;
function MixAdvertisements() {
    var adWoopeeContainer = $j("#AdWoopees");

    if (adWoopeeContainer.length > 0) {
        adWoopees = adWoopeeContainer.find(".AdvertisementWoopee");

        if (adWoopees.length > 0) {
            var allWoopees = $j(".WoopeeItem");

            if (allWoopees.length < adMixInStart)
            {
                // To less woopees to insert ads.
                // [MB]
                return;
            }
            else 
            {
                var numberOfAdsToAdd = Math.floor((allWoopees.length - adMixInStart) / adMixInInterval) + 1; // +1 cause of the first ad added. [MB]

                var positionToAdd = 0;
                for (var i = 0; i < numberOfAdsToAdd; i++) {
                    if (i == 0) {
                        positionToAdd = adMixInStart;
                    }
                    else {
                        positionToAdd += adMixInInterval;
                    }

                    var availableAdsItemIdx = GetIdxOfAdWoopees(lastAdIdx);
                    lastAdIdx = availableAdsItemIdx;

                    $j(allWoopees[positionToAdd]).after("<div class=\"AdvertisementWoopee\" AddIdx=\"" + availableAdsItemIdx + "\" InList=\"true\">" + adWoopees[availableAdsItemIdx].innerHTML + "</div>");
                }
            }
        }
    }

    adRotationTimeoutHandle = window.setTimeout(RotateAds, adMovementTimeout);
}

function GetIdxOfAdWoopees(adIdxToSkip) {
    var availableAdsItemIdx = 0;
    var deadlockCounter = 0;
    do {
        availableAdsItemIdx = Math.floor(Math.random() * adWoopees.length);
        deadlockCounter++;
    }
    while ((adIdxToSkip == availableAdsItemIdx) && (deadlockCounter < 60));

    return availableAdsItemIdx;
}

function RotateAds() {
    $j(".AdvertisementWoopee[InList=true]").find(".AdMovementContainer").animate(
    {
        left: "+=" + adMovementDistance,
        opacity: 0
    }, adMovementDuration, function () {
        var movedOut = $j(this);
        var movedOutContainer = movedOut.parent();

        // Remove old ad.
        // [MB]
        var previousIdx = movedOutContainer.attr("AddIdx");
        $j(movedOut).remove();

        // Insert new one.
        // [MB]
        var newAdIdx = GetIdxOfAdWoopees(previousIdx);
        movedOutContainer.html(adWoopees[newAdIdx].innerHTML).attr("AddIdx", newAdIdx);
        movedOutContainer.find(".AdMovementContainer").css({
            left: -adMovementDistance,
            opacity: 0
        }).animate({
            left: "+=" + adMovementDistance,
            opacity: 1
        }, adMovementDuration);
    });


    // Start rotation again.
    // [MB]
    window.setTimeout(RotateAds, adMovementTimeout);
}

function UpdateAdsAfterReload() {
    var allAddedAds = $j(".AdvertisementWoopee[InList=true]");

    if (allAddedAds.length > 0) {
        var lastWoopeeWithoutAds = allAddedAds.last().next(".WoopeeItem");
        var allWoopees = $j(".WoopeeItem");

        if (allWoopees.length > 0) {
            var lastWoopeeWithoutAdIdx = allWoopees.index(lastWoopeeWithoutAds);

            for (var positionToAdd = (lastWoopeeWithoutAdIdx + adMixInInterval - 1); positionToAdd < allWoopees.length; positionToAdd += adMixInInterval) {
                var availableAdsItemIdx = GetIdxOfAdWoopees(lastAdIdx);
                lastAdIdx = availableAdsItemIdx;

                $j(allWoopees[positionToAdd]).after("<div class=\"AdvertisementWoopee\" AddIdx=\"" + availableAdsItemIdx + "\" InList=\"true\">" + adWoopees[availableAdsItemIdx].innerHTML + "</div>");
            }
        }
    }
}

function GenerateAvailableAds(numberOfAds) {
    var adIdxArray = [];

    for (var i = 0; i < numberOfAds; i++) {
        adIdxArray[adIdxArray.length] = i;
    }

    return adIdxArray;
}
