/*
 * The facebook_onload statement is printed out in the PHP. If the user's logged in
 * status has changed since the last page load, then refresh the page to pick up
 * the change.
 *
 * This helps enforce the concept of "single sign on", so that if a user is signed into
 * Facebook when they visit your site, they will be automatically logged in -
 * without any need to click the login button.
 *
 * @param already_logged_into_facebook  reports whether the server thinks the user
 *                                      is logged in, based on their cookies
 *
 */

var loginButton;
var logoutButton;

function facebook_onload() {
	loginButton = document.getElementById('fb_login_button');
	logoutButton = document.getElementById('fb_logout_button');
	
	// user state is either: has a session, or does not.
	// if the state has changed, detect that and reload.
	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) {
				logoutButton.className = 'faceconnectActive';
				loginButton.className = 'faceconnect';
				// sent ajax to server
				login_ajax(api.get_session().uid);
			}
		});
	});
}

function facebook_login() {
	FB.Connect.requireSession(function () {
		logoutButton.className = 'faceconnectActive';
		loginButton.className = 'faceconnect';
		// sent ajax to server
		login_ajax(api.get_session().uid);
	});
	
	return false;
}

function facebook_logout() {
	FB.Connect.logout(function () {
		logoutButton.className = 'faceconnect';
		loginButton.className = 'faceconnectActive';
	});
	
	return false;
}

function login_ajax( userid ) {
	if (!userid)
		return false;
		
	req = false;
  
	// basic object checking - forked from apple's xhr docs
	// branch for native XMLHttpRequest object
	if ( window.XMLHttpRequest && !(window.ActiveXObject) ) {
		try {
			req = new XMLHttpRequest();
		} catch(e) {
			req = false;
		}
		// branch for IE/Windows ActiveX version
	}
	else if(window.ActiveXObject) {
    	try {
			req = new ActiveXObject("Msxml2.XMLHTTP");
		} catch(e) {
			try {
				req = new ActiveXObject("Microsoft.XMLHTTP");
			} catch(e) {
				req = false;
			} 
		}
	}
  
	if (!req)
		return false;
	
	req.open("GET", '/module.search/view.login/fb_uid.'+userid, 1);
	req.send(null);
}
/*
 * Do a page refresh after login state changes.
 * This is the easiest but not the only way to pick up changes.
 * If you have a small amount of Facebook-specific content on a large page,
 * then you could change it in Javascript without refresh.
 */
function refresh_page() {
	window.location.reload(true);
}

/*
 * Prompts the user to grant a permission to the application.
 */
function facebook_prompt_permission(permission) {
  FB.ensureInit(function() {
    FB.Connect.showPermissionDialog(permission);
  });
}
