/*
* Social API Helper Functions
*/
/*
* JSLint Configuration:
*/
/*global $, mx, window, clearTimeout, setTimeout */
mx.social = (function () {
    var shareClickAlreadySet = false;

    return {
        backgroundContainer: null,
        connectPostbackUrl: "/social/facebookconnect/",
        permissions: 'user_about_me,user_birthday,user_location,user_hometown,user_likes,user_interests,user_website,user_education_history,user_work_history,publish_stream,email,read_friendlists,sms',
        cookieName: 'fb_user',

        // Initialization Script
        init: function () {
            // FACEBOOK INITIALISATION
            $('#facebookLogin')
                .unbind('click')
                .click(function (e) {
                    alert('oi');

                    mx.social.facebookLoginClick();
                    e.preventDefault();
                });

            var mixarooUser = $.cookie(mx.social.cookieName);

            // try to log the user from cookie data
            if (typeof mixarooUser != 'undefined' && mixarooUser !== null) {
                $('.connect-box').remove();

                $('#connection-header .loading').remove();

                $('#connection-header').append('<p class="loading"><img src="/content/img/loading.gif" alt="loading" /></p>');

                $.home.getConsumerKeyFromFacebook({
                    authResponse: {
                        accessToken: mixarooUser
                    }
                });
            }

            if (FB) {
                FB.init({ appId: mx.facebookApiKey, status: true, cookie: true, xfbml: true, oauth: true });
            }

            // SHARE THIS INITIALISATION
            var switchTo5x = true;

            $.getScript('http://w.sharethis.com/button/buttons.js', function () {
                stLight.options({
                    publisher: '1b171506-8a07-4a71-8680-6221a57f3346',
                    headerTitle: 'Boxfish'
                });

                // increment the counter for the number of shares 
                stLight.subscribe("click", function () {

                    if (shareClickAlreadySet) return;

                    shareClickAlreadySet = true;

                    $.ajax({
                        url: "/Programme/ShareSum",
                        type: "POST",
                        dataType: "JSON",
                        data: {
                            searchTerm: $('#search-bar').val(),
                            channelId: $.mentions ? $.mentions : currentChannelId
                        }
                    });
                });
            });
        },

        logOut: function (reloadPage) {
            $.cookie(mx.social.cookieName, null);
            if (reloadPage) { location.reload(); }
        },

        facebookLoginClick: function () {
            FB.login(mx.social.loginResponse, { scope: mx.social.permissions });
        },

        loginResponse: function (response) {
            if (response.session) {
                if (response.scope) {
                    // user is logged in: update profile
                    mx.ajax.post(
                    // user is granted some permissions. (scope is a 
                    // comma separated list of granted permissions)
                        mx.social.connectPostbackUrl,
                        { token: response.session.access_token },
                        function (response, status) {
                            var name = '';

                            if (typeof response.data != 'undefined') {
                                name = ' ' + response.data.name;

                                // Set Cookie
                                $.cookie(mx.social.cookieName, response.data.name, { expires: 365, path: '/', domain: mx.domain, secure: false });
                            }
                        },
                        function (response, desc, err) {
                            // an error occurred
                            if (typeof response.data !== 'undefined') {
                                // an error occurred
                            }
                        }
                    );
                } else {
                    // user did not grant any permissions
                }
            } else {
                // user cancelled login - do nothing
            }

            if ($.home) {

                $.home.getConsumerKeyFromFacebook(response);

                $.cookie(mx.social.cookieName, response.authResponse.accessToken);

            }
        }
    };

} ());

// Hookup to the jquery query object
(function ($) {
    $.fn.freindinvites = function () {
        return $.fn.toolConstructor(this, FriendInvites, arguments);
    };

})(jQuery);

function FriendInvites(target, options) {
    this.target = $(target);
    this.options = { baseUrl: '/', pageSize: 30 };
    this.setOptions(options);

    //create the container list.
    this.target.append(this.container = $("<ul />", { "class": "friends-list" }));

    var that = this;
    if (FB)
        FB.getLoginStatus(function (response) {
            that.name = response;
        });
}

FriendInvites.prototype.setOptions = function (options) {
    this.options = $.extend(this.options, options);
};

FriendInvites.prototype.setLoadingIcon = function (parent) {
    parent.unbind();
    parent.children().remove();
    parent.append("<img src='/content/img/loading.gif' class='icon' style='width : 15px; margin: 0 auto; display:block;' />");
};

FriendInvites.prototype.inviteFriend = function (to, name, auth, success) {
    var that = this;

    var result = FB.ui(
        {
            method: 'apprequests',
            message: 'You have been invited to join Boxfish, The index of Television!',
            to: to,
            link: 'http://www.boxfish.com/',
            picture: 'http://boxfish.com/v2/content/img/appicon/icon.png',
            actions: [
                { name: 'boxfish', link: 'http://www.boxfish.com/' }
            ]
        },
        function (response) {
            if (response) {
                $.ajax({
                    url: that.options.baseUrl + '/social/invited/{0}/{1}'.format(to, name),
                    data: auth,
                    dataType: "jsonp",
                    success: success
                });
            }
        });

    return $("#" + result.id);
};


FriendInvites.prototype.firstLoad = function () {
    //already loaded first part
    if (this.loaded)
        return;

    this.loaded = true;
    this.setLoadingIcon(this.container);
    var icon = this.container.children();
    this.showFriends(0, this.options.pageSize, function () {
        icon.remove();
    });

};

FriendInvites.prototype.showFriends = function (start, number, finished) {
    var that = this;

    //Facebook not defined yet.
    if (!FB)
        return;

    var auth = { token: FB.getAccessToken(), id: FB.getUserID() };

    $.ajax({
        url: this.options.baseUrl + '/social/getfriends/{0}/{1}'.format(start, number),
        data: auth,
        dataType: "jsonp",
        success: function (data) {
            $(data).each(function () {
                var item = $("<li />", { "class": "friend" });
                $("<img />", { src: 'http://graph.facebook.com/{0}/picture'.format(this.id), "class": "friend-image" }).appendTo(item);
                $("<span />", { "class": "friend-name" }).text(this.name).appendTo(item);
                var invite = $("<button />", { "class": "blue-button button" }).text("Invite").data("id", this.id).data("name", this.name);
                if (this.invited) {
                    invite.addClass("disabled");
                }
                else {
                    invite.click(function () {
                        var inviteFriend = $(this);
                        var dialog = that.inviteFriend(inviteFriend.data("id"), inviteFriend.data("name"), auth, function () {
                            inviteFriend.addClass("disabled").unbind();
                        });

                    });
                }
                item.append(invite);

                that.container.append(item);
            });

            if (data && data.length == number) {
                var li = $("<li />", { "class": "more-mentions-holder" })
                .append($("<a />", { "class": "next-page blue-link" }).text("More Friends"))
                .appendTo(that.container)
                .click(function () {
                    that.setLoadingIcon(li);
                    that.showFriends(start + number, number, function () {
                        li.remove();
                    });
                });

            }
            //if calling a function when done.
            if (finished)
                finished();


        }
    });

};
