
/*
 * 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
 *
 */
fbBaseUrl = window.location.protocol+'//'+window.location.host+'/';

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();
        });
    });
}

/*
 * Our <fb:login-button> specifies this function in its onlogin attribute,
 * which is triggered after the user authenticates the app in the Connect
 * dialog and the Facebook session has been set in the cookies.
 */
function facebook_onlogin_ready() {
  // In this app, we redirect the user back to index.php. The server will read
  // the cookie and see that the user is logged in, and will deliver a new page
  // with content appropriate for a logged-in user.
  //
  // However, a more complex app could use this function to do AJAX calls
  // and/or in-place replacement of page contents to avoid a full page refresh.  
  refresh_page();
}

/*
 * 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 = 'index.php';
}

function showResult(postId)
{
	if (postId != null && postId != 'null') 
	{
		ge('shareOnFB').innerHTML = 'Your message has been sent';
	}
}
/*
* Opens a new window in which we'll handle all the facebook sharing
*
*/
function open_fb_share()
{
	window.location = '/fb_share.php';
}

function do_login_fb()
{
	document.getElementById('handlerID').value = 'facebook_login';
	document.getElementById('loginForm').submit();
}

function do_login_charity_fb()
{
	document.getElementById('handlerID').value = 'facebook_charityLogin';
	document.getElementById('loginForm').submit();
}

function do_login_event_fb()
{
	document.getElementById('handlerID').value = 'facebook_eventLogin';
	document.getElementById('loginForm').submit();
}

function link_account(onSuccess, onFail)
{	
	document.location = 'includes/frontResult.php?handlerID=facebook_linkAccount&onSuccess='+onSuccess+'&onFail='+onFail;
}

function link_account_charity(onSuccess, onFail)
{	
	document.location = 'includes/frontResult.php?handlerID=facebook_linkAccountCharity&onSuccess='+onSuccess+'&onFail='+onFail;
}


//We can't redirect from the fund page create because it breaks process so we need this
function link_account_fund_page(onSuccess, onFail)
{
	var myAjax = new Ajax(fbBaseUrl+'includes/facebook/link_account_ajax.php', {method: 'get', onComplete:link_account_fundpage_cb}).request();
	myAjax.request();
}

function link_account_fundpage_cb(result)
{
	if(result == 0)
	{
		//linking was successful, inject the facebook options
		$('fbConnectOptions').innerHTML = '<input type="checkbox" name="fb_publish_story" id="fb_publish_story" value="1" />Publish a story about this on my facebook profile.<br /><input type="checkbox" name="fb_comment_box" id="fb_comment_box" value="1" />Create a facebook comment box on your fund raiser page.';
	}
	else
	{
		//linking failed, display error message and kill the facebook session
		FB.Connect.Logout();
		$('fbConnectMsg').innerHTML = "Connecting your accounts failed. Please try again";
	}
}

//links accounts silently if the user is prompted by a require connect
function link_account_congrats(onSuccess, onFail)
{
	var myAjax = new Ajax(fbBaseUrl+'includes/facebook/link_account_ajax.php', {method: 'get', onComplete:link_account_congrats_cb}).request();
	myAjax.request();
}
//confirms message has been sent on facebook. 
function link_account_congrats_cb(result)
{
	if(result == 0)
	{
		//linking was successful, inject the facebook options
		$('shareOnFB').innerHTML = 'Your message has been sent';
	}
	else
	{
		//linking failed, display error message and kill the facebook session
		
	}
}



/*
 * 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(templateId, data) {
  // Load the feed form
  FB.ensureInit(function() {         
		  FB.Connect.showFeedDialog(templateId, data, null, null, null, FB.RequireConnect.promptConnect, showResult, 'Publish to your profile')
     
     
  });
}

function facebook_publish_feed_story_congrats(templateId, data) {
  // Load the feed form
  FB.ensureInit(function() {         
		  FB.Connect.showFeedDialog(templateId, data, null, null, null, FB.RequireConnect.promptConnect, link_account_congrats, 'Publish to your profile')
     
     
  });
}

/*
 * 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";
            }
          }
        });
    });
}

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