function facebookLogin(page,args) {
	page = (page === undefined ? '' : page);
	args = (args === undefined ? '' : args);
  reloadPage(page,args);
}

showTable = 0;
function fbTableShow(base,inc) {
	var oldPtr,newPtr;
	newPtr = document.getElementById(base+(showTable+inc));
	if (newPtr) {
		oldPtr = document.getElementById(base+showTable);
		if (oldPtr) {
			oldPtr.className = 'noDisplay';
		}
		newPtr.className = '';
		showTable += inc;
	}
}
function reloadPage(page,args) {
	var loc;
	loc = ((page == undefined) || !page ? window.location.pathname : page);
	args = ((args !== undefined) && (args !== '') ? '?'+args : '');
	loc = loc.match(/[a-zA-Z0-9_.]+$/);
	if (!loc) {
		loc = 'default.php';
	}
  window.location = loc+args;
  return false;
}

//==============================================================================
function fbLoginAttempt(permissions,onSuccess,onFailure) {
	var permObject;
	if (window.FB !== undefined) {
		fbLoginResponse.onSuccess = (onSuccess === undefined ? null : onSuccess);
		fbLoginResponse.onFailure = (onFailure === undefined ? null : onFailure);
		fbLoginAttempt.permissions = ((permissions !== undefined) && permissions ? {scope:permissions} : null);
		FB.login(function(response){fbLoginResponse(response);},fbLoginAttempt.permissions);
	}
}

function fbLoginResponse(response) {
	var i,perms,query,success;
	fbLoginResponse.response = response;
	success = (response && (response.status !== undefined) && (response.status=='connected'));
	if (success && response.authResponse) {
		// Test if permission requested && not given
		if ((fbLoginAttempt.permissions !== undefined) && fbLoginAttempt.permissions) {
			perms = fbLoginAttempt.permissions.scope;
			query = FB.api('/me/permissions',function(response) {fbCheckPermissionResponse(response)});
		}
		else {
			fbLoginSuccess();
		}
	}
	else {
		fbLoginFailure();
	}
}

function fbLoginSuccess(response) {
	var fbId;
	if (response === undefined) {
		response = ((fbLoginResponse.response !== undefined) && fbLoginResponse.response ? fbLoginResponse.response : null);
	}
	fbId = (response && (response.authResponse !== undefined) && (response.authResponse.userID !== undefined) ? response.authResponse.userID : null);
	if ((fbLoginResponse.onSuccess !== undefined) && fbLoginResponse.onSuccess) {
		fbLoginResponse.onSuccess(fbId);
		fbLoginResponse.onSuccess = null;
	}
	setFbLoginPicture(fbId);
}

function fbLoginFailure() {
	var result;
	result = null;
	if ((fbLoginResponse.onFailure !== undefined) && fbLoginResponse.onFailure) {
		result = fbLoginResponse.onFailure();
		fbLoginResponse.onFailure = null;
	}
	return result;
}


function fbDefaultInit() {
	fbId = fbCheckLoggedIn();
	if (fbId) {
		reloadPage('login.php','fbId='+fbId);
	}
	else {
		fbShowDefaultLogin();
	}
}

function fbDefaultLoginEvent(response) {
	fbId = fbCheckLoggedIn(response);
	reloadPage('login.php','fbId='+fbId);
}

function fbLoginEvent(response) {
	fbId = fbCheckLoggedIn(response);
	setFbLoginPicture(fbId);
}

function fbOnInit(onInit) {
	fbId = fbCheckLoggedIn();
	setFbLoginPicture(fbId);
	if ((onInit !== undefined) && onInit) {
		onInit(onInitArgs);
	}
}

function fbShowDefaultLogin() {
	showDiv(document,'defaultElifeLogin','defaultElifeLogin');
}

function setFbLoginPicture(fbId) {
	var divPtr;
	fbId = (fbId === undefined ? null : fbId);
	if (fbId) {
		divPtr = document.getElementById('menuFbProfilePic');
		divPtr.innerHTML = '<fb:profile-pic facebook-logo="true" uid="'+fbId+'"></fb:profile-pic>';
		showDiv(document,'menuFbProfilePic','fbProfilePic');
		hideDiv(document,'menuFbLoginButton');
	}
	else {
		hideDiv(document,'menuFbProfilePic');
		showDiv(document,'menuFbLoginButton','fbProfilePic');
		divPtr = document.getElementById('menuFbLoginButton');
	}
	if (divPtr) {
		FB.XFBML.parse(divPtr);
	}
}

function fbCheckPermissionResponse(response) {
	var i,currentPerms,requestedPerms,requestedPerm,allPerms,errors,thisErrors;
	allPerms = false;
	if (response && (response.data !== undefined) && response.data) {
		currentPerms = response.data[0];
		errors = { publish_stream:'post to your wall', offline_access:'post to your wall at any time' };
		thisErrors = [];
		allPerms = true;
		requestedPerms = fbLoginAttempt.permissions.scope.split(',');
		for (i=0; i<requestedPerms.length;++i) {
			requestedPerm = requestedPerms[i];
			if ((currentPerms[requestedPerm] == undefined) || !currentPerms[requestedPerm]) {
				allPerms = false;
				if (errors[requestedPerm] !== undefined) {
					thisErrors[thisErrors.length] = errors[requestedPerm];
				}
			}
		}
	}
	if (allPerms) {
		fbLoginSuccess()
	}
	else if (fbLoginFailure()) {
		alert("I'm sorry, Facebook requires you to give eLife permission to "+thisErrors.join(' and '));
	}
}

function fbLogout() {
	if (fbCheckLoggedIn()) {
		FB.logout(function(){ setFbLoginPicture();reloadPage('logoff.php'); });
	}
	else {
		reloadPage('logoff.php');
	}
	return false;
}

function fbLinkToElife(cId,fbId) {
	loadContent('linkToFacebook.php','cId='+cId+'&fbId='+fbId,'get');
}

function fbInit(API_KEY,status,cookie,xfbml,loginArgs,onLoginEvent,onInit) {
	loginArgs = (loginArgs === undefined ? null : loginArgs);
	onLoginEvent = ((onLoginEvent !== undefined) && onLoginEvent ? onLoginEvent : function(response){fbLoginEvent(response,loginArgs);});
	FB.init({appId:API_KEY, status:status, cookie:cookie, xfbml:xfbml});
	FB.getLoginStatus(function(response){fbCheckLoggedIn(response);fbOnInit(onInit);});
	if (onLoginEvent) {
		FB.Event.subscribe('auth.login',onLoginEvent);
	}
}

function fbCheckLoggedIn(response) {
	if (fbCheckLoggedIn.fbLoggedIn === undefined) {
		fbCheckLoggedIn.fbLoggedIn = false;
		fbCheckLoggedIn.fbConnected = false;
	}
	if ((response !== undefined) && response && (response.status !== undefined)) {
		if (response.status == 'connected') {
			fbCheckLoggedIn.fbLoggedIn = fbResponseUserId(response);
			fbCheckLoggedIn.fbConnected = true;
		}
		else if (response.status == 'not_authorized') {
			fbCheckLoggedIn.fbLoggedIn = fbResponseUserId(response);
			fbCheckLoggedIn.fbConnected = false;
		}
		else {
			fbCheckLoggedIn.fbLoggedIn = false;
			fbCheckLoggedIn.fbConnected = false;
		}
	}
	return fbCheckLoggedIn.fbLoggedIn;
}

function fbResponseUserId(response) {
	return (response && (response.authResponse !== undefined) && (response.authResponse.userID !== undefined) ? response.authResponse.userID : null);
}

function fbStreamCheck(thisPtr,yesNoId,fbPublishStream) {
	if (fbStreamCheck.fbPublishStream === undefined) {
		fbStreamCheck.fbPublishStream = fbPublishStream;
		fbStreamCheck.thisPtr = thisPtr;
		fbStreamCheck.yesNoPtr = (yesNoId ? thisPtr.form[yesNoId] : null);
	}
	else {
		fbPublishStream = fbStreamCheck.fbPublishStream;
	}
	if (!fbPublishStream && (!thisPtr || (thisPtr.selectedIndex != 0))) {
		if (confirm("eLife needs your permission to post your activity on your Facebook Wall.")) {
			FB.Connect.showPermissionDialog("publish_stream,offline_access",fbStreamResponse);
		}
		else {
			fbStreamResponse(false,true);
		}
	}
}

function fbStreamResponse(yes,notFb) {
	var parentPtr,opId,placeholderId,placeholderPtr,re;
	if ((notFb === undefined) || !notFb) {
		fbStreamCheck.fbPublishStream = yes;
	}
	if (!yes) {
		if (fbStreamCheck.thisPtr) {
			fbStreamCheck.thisPtr.selectedIndex = 0;
			parentPtr = fbStreamCheck.thisPtr.parentNode.parentNode;
			parentPtr.className = 'noDisplay';
			re = /[A-Za-z]+/;
			opId = parentPtr.getAttribute('id');
			if (opId) {
				placeholderId = opId.replace(re,'placeHolder');
				if (opId != placeholderId) {
					placeholderPtr = document.getElementById(placeholderId);
					if (placeholderPtr) {
						placeholderPtr.className = 'placeHolder';
					}
				}
			}
		}
		if (fbStreamCheck.yesNoPtr) {
			fbStreamCheck.yesNoPtr[0].checked = false;
			fbStreamCheck.yesNoPtr[1].checked = true;
		}
	}
}

function fbStreamPublish(targetId,name,caption,description,prompt,href,callback) {
	var attachment;
	caption = caption.replace('&#39;',"'");
	description = description.replace('&#39;',"'");
	links = [{'text':'Check out eLife Adventure','href':'http://www.elifeadventure.org/'}];
	attachment = {'name':name,'caption':caption,'description':description,'properties':{'Join me and my eLife friends at':{'text':'eLife Adventure, your premier activities network!','href':'http://www.elifeadventure.org'}}};
	attachment.media = [{ 'type': 'image', 'src': 'http://www.elifeadventure.org/catalog/images/streamLogo.gif', 'href': 'http://www.elifeadventure.org'}];
	if ((href !== undefined) && href) {
		attachment.href = href;
	}
	callback = ((callback !== undefined) && (typeof callback == 'function') ? callback : null );
	FB.Connect.streamPublish('', attachment,links,targetId,prompt,callback);
	return false;
}



