﻿    var _facebook_logged_in = false;
    var run_once = false;
    function show_all_friends(){
	    content = $('#friend_placeholder').html();
	    // remove contents and show loading  panel
        $.blockUI({ message: '<img src="/assets/images/ajaxLoader.gif"><div><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() {
            FB.ensureInit(function() {
                $.blockUI({ message: '<img src="/assets/images/ajaxLoader.gif"><div><b>Please Wait, Processing...</b></div>' });
                FB.Connect.ifUserConnected(function() {
                    _facebook_logged_in = true;
                    $('.show_all_friends').show();
                    $('.fb_friends').show();
                    $('.HideFacebook').show();
                    $('.ShowFacebookSignIn').hide();
                    facebook_data.loadFriends(16);
                },
                function() {
                    $('.show_all_friends').hide();
                    $('.fb_friends').hide();
                    $('.HideFacebook').hide();
                });
                $.unblockUI();            
            });
	},
	postToFacebook: function(){
        //Used for onClick even to Post	to users wall
        FB.Connect.ifUserConnected(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();
					if(!run_once){
					    run_once = true;
						FriendArray = [];
						reload = false;
						Cookiefound = false;
						if(/fbFriendArray=([^;]+)/.test(document.cookie)){
							Cookiefound = true;
							var api = FB.Facebook.apiClient;
							uid = api.get_session().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){
		FB_RequireFeatures(["Api"], function(){
			FB.Facebook.get_sessionState().waitUntilReady(function() { 
				var api = FB.Facebook.apiClient;
				var myQuery='SELECT name, pic_square, uid FROM user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1= ' + api.get_session().uid + ')';
				api.requireLogin(function(exception){
				    api.fql_query(myQuery,callback);
				});
			 });
		});
	},
	// get the friends from facebook and load into cookie
	initFriends: function(num, callback){
		var once = facebook_data.RunOnce(function(){
			facebook_data.facebookReady(function() {
				var api = FB.Facebook.apiClient;
				var myQuery='SELECT name, pic_square, uid FROM user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1 = '+api.get_session().uid+')';
				api.requireLogin(function(exception){
				    api.fql_query(myQuery,function(users){
				        facebook_data.SetFQLResponse(users, num, callback);
				    });
				});
			 });
		});
		FB_RequireFeatures(["Api"], once);
	},
    // 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);
         }
    },
    facebookReady: function(callback){
		FB.ensureInit(function() {
	      FB.Facebook.get_sessionState().waitUntilReady(function(session) {
	          var is_now_logged_into_facebook = session ? true : false;
	          if (is_now_logged_into_facebook == _facebook_logged_in) {
	            callback();
				return;
	          }
              _facebook_logged_in = false;  
	          $('.show_all_friends').hide();
	          $('.fb_friends').hide();
              $('.ShowFacebookSignIn').show();
	          
	        });
	    });
	},
   RunOnce: function(callback) {
	    var obj = new function() {
		    this.executed = false;
		    this.run = function() {
			    if (!this.executed) {
				    this.executed = true;
				    callback();
			    }
		    };
	    }
        return function() {
	        obj.run();
        };
  },
  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 api = FB.Facebook.apiClient;
		var uid = api.get_session().uid;
	    document.cookie = "fbFriendArray=({retrieved:"+now.getTime()+",user_"+uid+":["+ret.join(',')+']'+'}); expires=' + expires.toGMTString() + '; path=/';
	    callback(users.splice(0,num));
	}
 };


