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;
}

//==============================================================================
function fbLoginAttempt(permissions,onSuccess,onFailure) {
	var permObject;
	fbLoginResponse.onSuccess = (onSuccess === undefined ? null : onSuccess);
	fbLoginResponse.onFailure = (onFailure === undefined ? null : onFailure);
	fbLoginAttempt.permissions = ((permissions !== undefined) && permissions ? {perms:permissions} : null);
	FB.login(function(response){fbLoginResponse(response);},fbLoginAttempt.permissions);
}

function fbLoginResponse(response) {
	var i,perms,query;
	fbLoginResponse.response = response;
	if (response.session) {
		// Test if permission requested && not given
		if ((fbLoginAttempt.permissions !== undefined) && fbLoginAttempt.permissions) {
			perms = fbLoginAttempt.permissions.perms;
			query = FB.Data.query("SELECT "+perms+" FROM permissions WHERE uid=me()");
			query.wait(function(rows) {fbCheckPermissionResponse(rows)});
			//FB.api({method:'users.hasapppermission',ext_perm:'publish_stream'},function(response){ fbCheckPermissionResponse(response); });
		}
		else {
			fbLoginSuccess();
		}
	}
	else {
		fbLoginFailure();
	}
}

function fbLoginSuccess() {
	var fbId;
	if ((fbLoginResponse.onSuccess !== undefined) && fbLoginResponse.onSuccess) {
		fbLoginResponse.onSuccess();
	}
	fbId = ((fbLoginResponse.response !== undefined) && fbLoginResponse.response ? fbLoginResponse.response.session.uid : null);
	setFbLoginPicture(fbId);
}

function fbLoginFailure() {
	if ((fbLoginResponse.onFailure !== undefined) && fbLoginResponse.onFailure) {
		fbLoginResponse.onFailure();
	}
}

function setFbLoginPicture(loggedInfbId) {
	var divPtr;
	divPtr = document.getElementById('menuFbProfilePic');
	if (divPtr && loggedInfbId) {
		divPtr.innerHTML = '<fb:profile-pic facebook-logo="true" uid="'+loggedInfbId+'"></fb:profile-pic>';
		FB.XFBML.parse(divPtr);
	}
}

function fbCheckPermissionResponse(rows) {
	var i,perms,allPerms,errors,thisErrors;
	fbLoginResponse.rows = rows;
	allPerms = false;
	errors = { publish_stream:'post to your wall', offline_access:'post to your wall at any time' };
	thisErrors = [];
	if ((rows.length !== undefined) && (rows.length > 0)) {
		allPerms = true;
		perms = fbLoginAttempt.permissions.perms.split(',');
		for (i=0; i<perms.length;++i) {
			if (rows[0][perms[i]]==0) {
				allPerms = false;
				if (errors[perms[i]] !== undefined) {
					thisErrors[thisErrors.length] = errors[perms[i]];
				}
			}
		}
	}
	if (allPerms) {
		fbLoginSuccess()
	}
	else {
		fbLoginFailure();
		alert("I'm sorry, Facebook requires you to give eLife permission to "+thisErrors.join(' and '));
	}
}

function fbInit(API_KEY,status,cookie,xfbml,args,onSuccess,onInit) {
	args = (args === undefined ? null : args);
	onSuccess = (onSuccess !== undefined ? onSuccess : function(){ facebookLogin(null,args) });
	onInit = (onInit === undefined ? null : onInit);
	FB.init({appId:API_KEY, status:status, cookie:cookie, xfbml:xfbml});
	fbLoginResponse.onSuccess = onSuccess;
	FB.Event.subscribe('auth.login',(onSuccess ? function(response){fbLoginResponse(response);} : null));
	if (onInit) {
		onInit();
	}
}

function fbLinkToElife(cId,fbId) {
	loadContent('linkToFacebook.php','cId='+cId+'&fbId='+fbId,'get');
}
//==============================================================================
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
function fbCheckLoggedIn(onSuccess,onFailure) {
	fbLoginResponse.onSuccess = (onSuccess === undefined ? null : onSuccess);
	fbLoginResponse.onFailure = (onFailure === undefined ? null : onFailure);
	FB.getLoginStatus(function(response){fbLoginResponse(response);});
}

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;
}

