Facebook = function () {

    var $FacebookBox = null;
    var IsInitialized = false;
    var AuthToken = null;
    var Friends = null;

    var PictureTemplate = '<li friendId="<Id>" friendName="<Name>"><a href="javascript:void(0);"><img height="50" width="50" src="<PictureUrl>" title="<Name>"/></a></li>';

    function storeAuthToken(response) {
        if (response && response.session)
            AuthToken = response.session.access_token;
        else
            AuthToken = null;
    }

    function fireFacebookInitialization() {
        FB.init({
            appId: '174896102520720',
            status: true,
            cookie: true,
            xfbml: true
        });

        var session = FB.getLoginStatus(function (response) {
            storeAuthToken(response);
            showSession(response.session);
        });
    }

    function initScripts() {
        if (typeof (FB) == 'undefined') {
            // Load connect script
            var e = document.createElement('script'); e.async = true;
            e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
            var root = document.getElementById('fb-root');
            // Exit if element not found     
            if (!root) return;
            root.appendChild(e);

            var fbAsyncInit = window.fbAsyncInit || function () { };

            window.fbAsyncInit = function () {
                if (!IsInitialized) {
                    fireFacebookInitialization();
                    IsInitialized = true;
                }
            };
        } else {
            fireFacebookInitialization();
        }
    }

    function showFriends() {
        $("div.message-for-friend").hide();
        var $friendCount = $FacebookBox.find(".friend-count");
        if ($friendCount)
            $friendCount.text(0);
        var $randomFriends = $FacebookBox.find(".random-friends");
        $randomFriends.html("");
        if (Friends == null) {
            return;
        }

        var result = '';
        $.each(Friends, function () {
            friend = this;
            if ($friendCount)
                $friendCount.text(friend.TotalCount);
            result += PictureTemplate.replace("<PictureUrl>", friend.PictureUrl)
                .replace("<Id>", friend.Id).replace("<Name>", friend.Name).replace("<Name>", friend.Name);
        });
        $randomFriends.html("<ul>" + result + "</ul>");

        $("div.facebook-box .random-friends img").click(function () {
            $("div.facebook-box .random-friends img.active").removeClass("active");
            $(this).addClass("active");

            var friendName = $(this).parents("li:first").attr("friendName");
            var friendId = $(this).parents("li:first").attr("friendId");
            $("div.facebook-box .message-for-friend .friend-id").val(friendId);
            $("div.facebook-box .message-for-friend .friend-name").html(friendName);
            $("div.facebook-box .message-for-friend").show();
        });
    }

    function refreshFriends() {
        Friends = null;
        $.ajax({
            type: "post",
            url: "/en/Home/RandomFriends",
            data: { authToken: AuthToken, count: 6 },
            beforeSend: function () { },
            complete: function () { },
            success: function (data) {
                Friends = data;
                showFriends();
            },
            error: function () {
                fireFacebookInitialization();
            }
        });
    }

    function clearFriendsCache() {
        Friends = null;
        $.ajax({
            type: "post",
            url: "/en/Home/ClearFriendsCache",
            data: { authToken: AuthToken },
            beforeSend: function () { },
            complete: function () { },
            success: function (data) { },
            error: function () { }
        });
    }

    function showControls() {
        $FacebookBox.find(".login").hide();
        refreshFriends();
        $FacebookBox.find(".loaded").show();
    }

    function showSession(session) {
        if (session != null) {
            showControls();
        } else {
            $FacebookBox.find(".loaded").hide();
            $FacebookBox.find(".login").show();
            $("div.message-for-friend").hide();
        }
    }

    function logOut() {
        if (typeof (FB) == 'undefined')
            return;

        FB.getLoginStatus(function (response) {
            if (response.session == null) return;
            else {
                window.setTimeout(function () { FB.logout(OnLogOut()); return (fakeFunction) }, 0);
            }
        });
    }

    function OnLogOut() {
        showSession(null);
        clearFriendsCache();
        return;
    }

    function fakeFunction() {
    }

    function assignLogin() {
        $FacebookBox.find(".fb-btn").click(function () {
            FB.login(
                function (response) {
                    if (response.session != null) {
                        storeAuthToken(response);
                        showControls();
                    } else {
                        initScripts();
                    }
                },
                { perms: 'read_stream,publish_stream,status_update,user_events,user_photo_video_tags' }
            );
        })
    }

    function assignFriendRefresh() {
        $FacebookBox.find(".friend-refresh").click(function () {
            refreshFriends();
        })
    }

    function assignPost() {
        $("div.facebook-box .message-for-friend .friend-post").click(function () {
            var id = $("div.facebook-box .message-for-friend .friend-id").val();
            var message = $("#fancybox-wrap").find(".facebook-box .message-for-friend .friend-message").val();
            addFeedMessage(id, message);
            $("div.facebook-box .message-for-friend").hide();
        });
    }

    function assignLogout() {
        $FacebookBox.find(".logout").click(function () {
            logOut();
        })
    }

    function addFeedMessage(userId, message) {
        $.ajax({
            type: "post",
            url: "/en/Home/AddFeedMessage",
            data: { authToken: AuthToken, userId: userId, message: message },
            beforeSend: function () { },
            complete: function () { },
            success: function (data) {
            },
            error: function () {
                fireFacebookInitialization();
            }
        });
    }

    return {
        Init: function () {
            IsInitialized = false;
            $FacebookBox = $("div.facebook-box");

            $("div.facebook-loader").html("<p class='loader'></p>");

            initScripts();
            assignLogin();
            assignLogout();
            assignFriendRefresh();
            assignPost();

            $("div.facebook-loader p.loader").remove();
        }
    }

} ();

