// this script assumes you are using the Facebook OAuth API and have already called FB.init on your site.
if(!OAuthBridge) {
	var OAuthBridge = {};
	OAuthBridge._swfId = 'swfContainer';

	OAuthBridge.setSwfId = function(id) {
		OAuthBridge._swfId = id;
	}

	OAuthBridge.initialize = function() {
		// set a timeout of a second in case getLoginStatus fails.
		/*OAuthBridge._timer = setTimeout(function() {
			document.getElementById(OAuthBridge._swfId).handleFacebookLogout();
		},1000);*/

		FB.getLoginStatus(function(response) {
			clearTimeout(OAuthBridge._timer);
			OAuthBridge._timer = null;
			
			if (response.session) {
				// there is a bug in the current getLoginStatus method Facebook JavaScript SDK -- it doesn't return permissions as expected. the best we can do is manually ask.
				FB.api({
						method : 'fql.query',
			            query : 'SELECT status_update,photo_upload,sms,offline_access,email,create_event,rsvp_event,publish_stream,read_stream,share_item,create_note,bookmarked,tab_added FROM permissions WHERE uid=' + FB.getSession().uid
					},
					function(response) {
						var perms = [];
						for(perm in response[0]) {
							if(response[0][perm] == '1') perms.push(perm);
						}

						document.getElementById(OAuthBridge._swfId).handleFacebookLogin(FB.getSession(),perms.join(','));
					}
			    );
			}
			else {
				document.getElementById(OAuthBridge._swfId).handleFacebookLogout();
			}
		});
	}

	OAuthBridge.login = function(opts) {
		if(!opts) opts = {};

		FB.login(function(response) {
			if(response.session) {
				document.getElementById(OAuthBridge._swfId).handleFacebookLogin( FB.getSession() );
			} else {
				document.getElementById(OAuthBridge._swfId).handleFacebookLoginCancel();
			}
		},opts);
	}

	OAuthBridge.logout = function() {
		FB.logout(function(response) {});
		document.getElementById(OAuthBridge._swfId).handleFacebookLogout();
	}
}
