// Facebook Connect code - restricts access to molotsi.com blog
// (C) 2009 Hugh Molotsi
//

// Global to track the current visitor's name
var g_visitorFirstName = "";
var g_vistorName = "";

// Return the user's name
function SetVisitorInfo(user_id)
{
    FB_RequireFeatures(["Api"], function() {
		FB.Facebook.apiClient.users_getInfo(user_id, ['name', 'first_name'], 
			function(userInfo, f_exception) {
				g_visitorName = userInfo[0]['name'];
				g_visitorFirstName = userInfo[0]['first_name'];

				// Update the blog description to welcome the visitor
				var divBlogDescription = document.getElementById("blog-description");
				divBlogDescription.innerHTML = "<p>Welcome " + g_visitorFirstName + " to the Molotsi Family Blog: Michelle, Hugh, Danielle, and Dineo.</p>";
			});
	});
}

// If the user is not our friend - send them away!
function checkFriendResults(results)
{
    if ( !results[0].are_friends && !results[1].are_friends ) {
		var param="?url=" + window.location;
	    window.location="http://molotsi.com/connect/fbnotfriend.html" + param;      
    }
}

// The user is connected - check if they are Hugh or Michelle's friends
function onConnected(user_id) {
    var homeIds = ["557748351", "551452118"];
    var guestIds = [];

	guestIds[0] = user_id;
    guestIds[1] = user_id;

    FB_RequireFeatures(["Api"], function() {
	   	FB.Facebook.apiClient.friends_areFriends(homeIds, guestIds, checkFriendResults);
	});
	
	SetVisitorInfo(user_id);
} 

// The user is not connected...ask them to login and authorize the app
function onNotConnected() { 
	var param="?url=" + window.location;
    window.location="http://molotsi.com/connect/fblogin.html" + param;
/*
     FB.ensureInit(function() {
        FB.Connect.get_status().waitUntilReady(function(status) {
			var param="?url=" + window.location;
		    if (status == FB.ConnectState.userNotLoggedIn )    {
                window.location="http://molotsi.com/connect/fblogin.html" + param;
            }
            if (status == FB.ConnectState.appNotAuthorized)    {
                window.location="http://molotsi.com/connect/fblogin.html" + param;
            }
        });
    });
*/
}


// Initialize Facebook and check to see if the user is connected
FB_RequireFeatures(["Connect"], function() {
    FB.init("078a3e14cfe0e20d2af0147d03d9c1ff", "/connect/xd_receiver.htm",
     {"reloadIfSessionStateChanged":true,
	"ifUserConnected":onConnected, 
	"ifUserNotConnected":onNotConnected});
});

