function ge(elem) {
  return document.getElementById(elem);
}

function facebook_register() {
	window.location = '/register/facebook';
}

function facebook_link() {
	window.location = '/facebook/add';
}

function facebook_login(url) {
	if(url) { url = '/login/facebook?redirect='+url; }
	else { url = '/login/facebook'; }	
	window.location = url;
}

function facebook_checkPermission(form,permission) {
	if(form && form.facebook && form.facebook.checked == false) {
		// alert('facebook checked');
		form.submit();
		return false;
	}

	FB.ensureInit(function() {
		// alert('fb init ' + permission);

		FB.Facebook.apiClient.users_hasAppPermission(permission, function (hasPermissions) {
			// alert('fb permission (s)');
			
			if(!hasPermissions) {
				// alert('does not have permission (s)');
				
				FB.Connect.showPermissionDialog(permission,function (status) {
					// alert('show permission dialog (s)');
					if(status) {
						// alert('permission granted');
						if(permission == 'offline_access') {
							// alert('save session key for offline access');
							// save session
						}

						if(form) { form.submit(); }
						return false;
					}
					else {
						// alert('permission denied');
						if(form) { form.submit(); }
						return false;
					}
				
					// alert('show permission dialog (e)');
					return false;
				});
			
				// alert('does not have permission(e)');
				return false;
			}
			else {
				// alert('has permission');
				if(form) { form.submit(); }
				return false;
			}
			
			// alert('fb permission (e)');
			return false;
		});
		
		return false;
	});

	// alert('fb end');
	return false;
}

function facebook_logout() {
	FB.ensureInit(function() {
		FB.Connect.logout(function() {
			window.location = '/logout/facebook';
		});	
	});	
}

function refresh_page() {
	window.location = '/member/home';
}

/*
 * 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
 *
 */
function facebook_onload(already_logged_into_facebook) {
  // 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 the new state is the same as the old (i.e., nothing changed) then do nothing
          if (is_now_logged_into_facebook == already_logged_into_facebook) {
            return;
          }

          // otherwise, refresh to pick up the state change
			refresh_page();
        });
    });
}

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

/*
 * Show the feed form. This would be typically called in response to the onclick handler of a "Publish" button,
 *  or in the onload event after the user submits a form with info that should be published.
 */
function facebook_publish_feed_story(form_bundle_id, template_data) {
  // Load the feed form
  FB.ensureInit(function() {
          FB.Connect.showFeedDialog(form_bundle_id, template_data);
          //FB.Connect.showFeedDialog(form_bundle_id, template_data, null, null, FB.FeedStorySize.shortStory, FB.RequireConnect.promptConnect);

      // hide the "Loading feed story ..." div
      ge('feed_loading').style.visibility = "hidden";
  });
}

/*
 * If a user is not connected, then the checkbox that says "Publish To Facebook" is hidden in the "add run" form.
 * This function detects whether the user is logged into facebook but just not connected, and shows the checkbox if that's true.
 */
function facebook_show_feed_checkbox() {
  FB.ensureInit(function() {
      FB.Connect.get_status().waitUntilReady(function(status) {
          if (status != FB.ConnectState.userNotLoggedIn) {
            // If the user is currently logged into Facebook, but has not
            // authorized the app, then go ahead and show them the feed dialog + upsell
            checkbox = ge('publish_fb_checkbox');
            if (checkbox) {
              checkbox.style.visibility = "visible";
            }
          }
        });
    });
}
