/*
 * This is the mymb js functions for the NEW facebook javascript api, 
 * which was released in May 2010 with the Open Graph API. 
 * 
 * Currently used ONLY ON THE NEW GAME PAGE.
 *
 */



// hash to mbid to fbid, and vice-versa. These are initialised once we've established that  
// you have valid cookies
// ( init these as -1, not zero. Because some users really have no friends :) ) 
var aFBIDtoMBID = -1;
var aMBIDtoFBID = -1;
var iUID = -1;
/**
 * clear out your MBID cookies if you don't need them anymore
 * else if you DO need them, set them up
 */
function checkMBCookies(callback)
{
	session = FB.getSession();
	if (session && session.uid){
		iUID = session.uid;
	}
	
	/**
	 * if you're not logged in, clear out your MBID and MBFRIENDS cookies 
	 * if you're logged in, and you have MBID and MBFRIENDS cookies, you're fine.
	 * if you're logged in but DON'T have cookies, then let's get some
	 */

	// if you're not logged in, clear out your MBID and MBFRIENDS cookies
	if (!session){
		console.log('logged out, clearing cookies');
		$.cookie('MBID', null);
		$.cookie('MBID_SIG', null);
		$.cookie('MBFRIENDS', null);
		$.cookie('MBFRIENDS_SIG', null);
		$.cookie('MBFRIENDS_FBS', null);
		$.cookie('MBFRIENDS_FBS_SIG', null);
		callback();
		return;
	}

	// if you're logged in, and you have MBID and MBFRIENDS cookies, you're fine.
	if ($.cookie('MBID') && 
	    $.cookie('MBID_SIG') &&
	    $.cookie('MBFRIENDS') &&
	    $.cookie('MBFRIENDS_SIG') &&
	    $.cookie('MBFRIENDS_FBS') &&
	    $.cookie('MBFRIENDS_FBS_SIG'))
        {
            // your cookies are fine
			console.log('cookies OK');
			callback();
            return;
	}

	// else if you're logged in but DON'T have cookies, then let's get some
	FB.api({
		method: 'friends.get',
		},
		function(friends){
			console.log('fetching new cookies');
			$.post('/user/login', {friends:JSON.stringify(friends)}, callback, 'JSON');
		}
	);

}
