﻿var _facebook_logged_in = false;

function show_all_friends() {
    content = $('#friend_placeholder').html();

    // remove contents and show loading  panel
    $.blockUI({ message: '<div style="width:55px;text-align:center;float:left;"><img src="/assets/css/Telerik/Window/loading.gif" /></div><div style="float:left;color:#666;font-size:17px;margin:11px 0 0 10px;"><b>Please Wait, Processing...</b></div>' });

    // ask facebook for the users 
    facebook_data.get_all_friends(function (users) {
        // sort the users by name 
        users.sort(function (thisObject, thatObject) {
            if (thisObject.name > thatObject.name)
                return 1;
            else if (thisObject.name < thatObject.name)
                return -1;
            return 0;
        });

        $('#fb_friends').html('<div id="friend_placeholder" style="display:none;">' + content + '</div>');
        $('#fb_friends').show();
        $('.show_all_friends').hide();
        $.unblockUI();

        divs = $('.fb_friends').children('div');
        facebookCount = users.length
        facebook_data.renderFriends(users);
    });
}

var facebookCount = 16;
var facebook_data = {
    initializeFacebook: function () {
        FacebookUtil.isLoggedIn(function (status) {
            if (status.toString() == 'true') {
                _facebook_logged_in = true;
                $('.ShowFacebookSignIn').hide();
                facebook_data.loadFriends(16);
            } else {
                $('.show_all_friends').hide();
                $('.fb_friends').hide();
                $('.HideFacebook').hide();
            }
        });
    },
    postToFacebook: function () {
        //Used for onClick even to Post	to users wall
        FacebookUtil.isLoggedIn(function () { postToFacebook(); }, null);
    },
    //Initialize Load
    loadFriends: function (number) {
        facebook_data.getFriends(number, function (users) {
            facebook_data.renderFriends(users);
        });
    },
    getFriends: function (num, callback) {
        // remove the old friend cookie 
        //document.cookie = "fbFriendArray=; expires=Thu, 01-Jan-1970 00:00:01 GMT; path=/";
        var FriendArray = new Array();
        run_once = false;
        if (!run_once) {
            FriendArray = [];
            reload = false;
            Cookiefound = false;
            if (/fbFriendArray=([^;]+)/.test(document.cookie)) {
                Cookiefound = true;
                uid = FB.getSession().uid;

                fbFriendArray = eval(unescape(/fbFriendArray=(.*?)(?:;|$)/.exec(document.cookie)[1]));

                if (fbFriendArray['user_' + uid]) {
                    FriendArray = fbFriendArray['user_' + uid];
                }
                if (fbFriendArray['retrieved']) {
                    loaded_time = fbFriendArray['retrieved'];
                    // if not today's date, reload
                    loaded = new Date(loaded_time);
                    now = new Date();
                    if ((loaded.getMonth() != now.getMonth()) || (loaded.getDate() != now.getDate())) {
                        reload = true;
                    }
                }
            }
            if (Cookiefound && !reload) {
                // if blank cookie array make sure they dont have any friends. get users again.
                if (FriendArray.length == 0) {
                    facebook_data.initFriends(num, callback);
                }
                else {
                    callback(FriendArray.splice(0, num));
                }
            } else {
                // this will put 16 of the fbFriendArray into cookies
                facebook_data.initFriends(num, callback);
            }
            run_once = true;
        }
    },
    // get the users' friends
    get_all_friends: function (callback) {
        var ses = FB.getSession()
        var qry = FB.Data.query('SELECT name, pic_square, uid FROM user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1 = {0})', ses.uid);
        qry.wait(function (users) {
            callback(users);
        });
    },
    // get the friends from facebook and load into cookie
    initFriends: function (num, callback) {
        var ses = FB.getSession()
        var qry = FB.Data.query('SELECT name, pic_square, uid FROM user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1 = {0})', ses.uid);
        qry.wait(function (users) {
            facebook_data.SetFQLResponse(users, num, callback);
        });
    },
    // render users' friends to page
    renderFriends: function (users) {
        var placeholder = $('#friend_placeholder');
        var container = $('#fb_friends');
        var content = placeholder.html();
        for (i = 0; i < users.length && i < facebookCount; i++) {
            if (!users[i].pic_square) {
                users[i].pic_square = '/assets/images/facebook/facebook_blankprofile.gif';
            }
            var div_content = content.replace(/rel=["']#img["']/, "src='" + users[i].pic_square + "'");
            div_content = div_content.replace('#name', users[i].name);
            div_content = div_content.replace('#uid', users[i].uid);
            container.append(div_content);
        }
    },
    SetFQLResponse: function (users, num, callback) {
        // serialize the data for the cookie
        ret = new Array();
        for (i = 0; i < 16; i++) {
            if (users[i]) {
                ret.push(escape("{uid:'" + users[i].uid + "', name:'" + users[i].name.replace(/'/g, "\\'") + "', pic_square: '" + users[i].pic_square + "'}"));
            }
        }
        // set the cookie for cache and run the callback
        expires = new Date();
        expires.setTime(Date.parse((expires.getMonth() + 1) + '/' + expires.getDate() + '/' + expires.getFullYear()));
        expires.setDate(expires.getDate() + 1);
        now = new Date();

        var uid = FB.getSession().uid;
        document.cookie = "fbFriendArray=({retrieved:" + now.getTime() + ",user_" + uid + ":[" + ret.join(',') + ']' + '}); expires=' + expires.toGMTString() + '; path=/';
        callback(users.splice(0, num));
    }
};


