
/*
 * API key, this should be initialized before any another function in this file is called.
 */
var is_initialized = false;

/*
 * Ensure Facebook app is initialized and call callback afterward
 *
 */
function ensure_init(callback) {
  if(!window.api_key) {
    window.alert("api_key is not set");
  }

  if(window.is_initialized) {
    callback();
  } else {
    FB_RequireFeatures(["XFBML", "CanvasUtil"], function() {
        FB.FBDebug.LogLevel = 4;
        FB.Facebook.init(window.api_key, "/comments/xd_receiver.php");
        window.is_initialized = true;
        callback();
      });
  }
}

function showDocAfterRender() {
  ensure_init(function() {
      FB.XFBML.Host.get_areElementsReady().waitUntilReady(show_document);
    });
}

/*
 * "Session Ready" handler. This is called when the facebook
 * session becomes ready after the user clicks the "Facebook login" button.
 * In a more complex app, this could be used to do some in-page
 * replacements and avoid a full page refresh. For now, just
 * notify the server the user is logged in, and redirect to home.
 *
 * @param link_to_current_user  if the facebook session should be
 *                              linked to a currently logged in user, or used
 *                              to create a new account anyway
 */
function facebook_session_is_ready(link_to_current_user) {
  var user = FB.Facebook.apiClient.get_session().uid;

  if (!user) {
    // probably should give some indication of failure to the user
    return;
  }


  // don't pass the user back raw to the server - it's too easy to spoof
  // better to just tell them that the session is ready, and let facebook
  // figure it out based on the cookies and signature
  //var params = 'save=1';

  //if (link_to_current_user) {
  //  params += '&link_to_current_user=1';
  //}

  //ajax('/comments/ajax.php', params, function(text) {
  //    if (text) {
  //      window.location = 'red-bull-big-wave-africa-set-f.php';
  //    }
  //  });
}

/*
 * Onclick handler for "facebook login" button. This will register
 * a handler for when the session becomes available, and then
 * start the process of getting a user's session (via popup, ajax
 * dialog, or just checking that they are already authenticated).
 *
 */
function facebook_button_onclick(link_to_current_user, login_verb) {
  var facebook_button = ge('facebook_button_loading');
  facebook_button.style.display = "block";
  ensure_init(function() {
      facebook_button.style.display = "none";
      FB.Facebook.get_sessionState().waitUntilReady(function() {
          facebook_session_is_ready(link_to_current_user);
          getUserInfo();
        });
      FB.Connect.requireSession(login_verb);
    });
}

/*
 * Onclick handler for "facebook logout" button. This will register
 * a handler for when the session becomes available, and then
 * log the user out).
 *
 */
function facebook_logout_button_onclick(link_to_current_user, login_verb) {
  	var facebook_button = ge('facebook_logout_button_loading');
	facebook_button.style.display = "block";
	
	FB.Connect.logout(function(){
		var anonData = document.getElementById("post-comments-anon-data");
		var fbData = document.getElementById("post-comments-fb-data");
		facebook_button.style.display = "none";
		fbData.style.display = "none";
		anonData.style.display = "block";
		showCaptcha();	// Anonymous users must complete the captcha, so we need to show it again on logout
	});
}

function getCookie(c_name)
{
if (document.cookie.length>0)
  {
  c_start=document.cookie.indexOf(c_name + "=");
  if (c_start!=-1)
    {
    c_start=c_start + c_name.length+1;
    c_end=document.cookie.indexOf(";",c_start);
    if (c_end==-1) c_end=document.cookie.length;
    return unescape(document.cookie.substring(c_start,c_end));
    }
  }
return "";
}

function removeAllChildNodes(parentObject)
{
	while (parentObject.hasChildNodes())
    {
        parentObject.removeChild(parentObject.firstChild);       
    }
}

function getUserInfo()
{
	hideCaptcha();	// Connect Authenticated users are not required to complete a captcha
	
	var facebookid = document.getElementById("facebookid");
	var firstname = document.getElementById("firstname");
	var lastname = document.getElementById("lastname");
	var location = document.getElementById("location");
	var imagepath = document.getElementById("imagepath");
	var anonData = document.getElementById("post-comments-anon-data");
	var fbData = document.getElementById("post-comments-fb-data");
	var fbImage = document.getElementById("fbImage");
	var fblocation = document.getElementById("fblocation");
	var fbName = document.getElementById("fbName");
	var facebookCookieId = getCookie(window.api_key + '_user');
	var uids=new Array(facebookCookieId);
	var fields=new Array("first_name", "last_name", "pic_square", "affiliations");
	
	removeAllChildNodes(fbImage);
	removeAllChildNodes(fblocation);
	removeAllChildNodes(fbName);
	facebookid.value = facebookCookieId;

	FB.Facebook.apiClient.users_getInfo(uids, fields, function(result, ex)
	{
		firstname.value = result[0]['first_name'];
		lastname.value = result[0]['last_name'];
		fbImage.src = result[0]['pic_square'];
		imagepath.value = result[0]['pic_square'];
		
		fbName.innerHTML = "";
		fbName.appendChild(document.createTextNode(result[0]['first_name'] + " " + result[0]['last_name']));
		
		if (result[0]['affiliations'] != null)
		{
			if (result[0]['affiliations'][0] != null)
			{
				if (result[0]['affiliations'][0]['name'] != null)
				{
					fblocation.innerHTML = "";
					fblocation.appendChild(document.createTextNode(result[0]['affiliations'][0]['name']));
					location.value = result[0]['affiliations'][0]['name'];
				}
				else
				{
					fblocation.appendChild(document.createTextNode(""));
					location.value = "";
				}
			}
			else
			{
					fblocation.appendChild(document.createTextNode(""));
					location.value = "";
			}
		}
		else
		{
			fblocation.appendChild(document.createTextNode(""));
			location.value = "";
		}
		
		anonData.style.display = "none";	
		fbData.style.display = "block";
	});
	
}

//function getUserInfoFields(uids, fields) {
//	ensure_init(function() {
//		FB.Facebook.get_sessionState().waitUntilReady(function()
//		{
//			FB.Facebook.apiClient.users_getInfo(uids, fields, function(result, ex) {
//				//window.alert("Info: " + result[0]['name']);
//				return result;
//			});
//		});
//	});
//}

/*
 * 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
  ensure_init(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() {
  ensure_init(function() {
      FB.Connect.get_status().waitUntilReady(function(status) {
          if (status != FB.UserLoginState.userNotLoggedIn) {
            // If the user is currently logged into Facebook, but has not
            // authorized the app, then go ahead and show them the beacon form + upsell
            checkbox = ge('publish_fb_checkbox');
            if (checkbox) {
              checkbox.style.visibility = "visible";
            }
          }
        });
    });
}
