/**
 * @modifier Leegorous
 */

var LOGOUT_URL;
var WP_URL;

// Send request to FC with request for uesr properties
function initAllData(securityToken) {
  var req = opensocial.newDataRequest();
  var opt_params = {};
  opt_params[opensocial.DataRequest.PeopleRequestFields.PROFILE_DETAILS] =
	[ opensocial.Person.Field.ID, opensocial.Person.Field.THUMBNAIL_URL,
	  opensocial.Person.Field.PROFILE_URL, opensocial.Person.Field.URLS, opensocial.Person.Field.NAME ];
  req.add(req.newFetchPersonRequest('VIEWER', opt_params), 'viewer');
  req.send(setupData);
};   

// The password is simply the profileId as of now.
// Modify this to get a new password scheme
function getPassword(profilestr) {
  var newString = profilestr.split('&');
  if (newString.length < 1) 
	return profilestr;
  return newString[1];
}

function setupData(data) {
  viewer = data.get('viewer').getData();

  if (viewer) {
	// We have a valid user. SetUp the display profile. Everything except the
	// SignOut link as we dont yet want the user to click on it. This is because
	// the user is not yet loged in. Create a div instead so that we can come back
	// and replace it with the SignOut link once the user does get logged in.
	var profile = document.getElementById('profile');
	if (!profile) return;

	profile.innerHTML =
	  '<img align="left" src="' +  viewer.getField("thumbnailUrl") + '">' +
	  '<b>Hello ' +  viewer.getField("displayName") + '!</b><br>' +
	  '<a href="#" onclick="google.friendconnect.requestSettings()">Settings</a><br>' +   
	  '<a href="#" onclick="google.friendconnect.requestInvite()">Invite</a><br>' +
	  '<div id="loadprof"></div>';


	profile_id_url = viewer.getField("profileUrl");
	profileurl = viewer.getField(opensocial.Person.Field.URLS)[0].getField('address');

	// Remove spaces in name
	var nameString = viewer.getField("displayName").split(' ');
	username = nameString.join('');

	// If we are logging in for he first time, create an AJAX
	// request to login/create this user in wp
	if (document.getElementById("author") != null) {
	  document.getElementById("loadprof").innerHTML=
		"Loading profile...";

	  passwd = getPassword(profile_id_url);
	  image_url = viewer.getField("thumbnailUrl");
	  CreateRequest(username, passwd, profileurl, profile_id_url, image_url);
	} else {
	  // If we are already logged in, simply replace the original
	  // html with our custom html
	  replaceText();
	}
  } else {
	google.friendconnect.renderSignInButton({ 'id': 'profile' });
  }
};

// This function will be called on the completion of the user
// logging AJAX call
function loadedProfile() {
  replaceText();
  window.location.reload();
}

// Remove the logout button around the comment and add our own logout mechanism.
// We implement a non-recursive DOM tree traversal as recursion seems to
// be expensive in javascript
function replaceText() {
  root = document.getElementById('commentform');
  var nodeArray = new Array();
  var parArray = new(Array);
  nodeArray.push(root);
  parArray.push(root.parentNode);
  while(nodeArray.length > 0) {
	curNode = nodeArray.pop();
	parNode = parArray.pop();
	if (curNode.nodeName == "a" || curNode.nodeName == "A") {
	  href_comp = curNode.href.split('wp-login.php');
	  if (href_comp.length > 1)
		parNode.removeChild(curNode);
	}
	children = curNode.childNodes;
	for (i = 0; i < children.length; i++) {
	  nodeArray.push(children[i]);
	  parArray.push(curNode);
	}
  }
  document.getElementById("loadprof").innerHTML=
	   '<a href="' + LOGOUT_URL + '" onClick="google.friendconnect.requestSignOut()"> Sign out</a>';
}

// The call to the SACK library to send an AJAX request to the 
// server side for user logging/creation
function CreateRequest(username, passwd, profileurl, profile_id_url, image_url) {
  var mysack = new sack(WP_URL + "/wp-content/plugins/fc_plugin/server_code.php" );         
  mysack.execute = 1;
  mysack.method = 'POST';
  mysack.setVar( "username", username );
  mysack.setVar( "passwd", passwd );
  mysack.setVar( "profileurl", profileurl);
  mysack.setVar( "profile_id_url", profile_id_url);
  mysack.setVar( "image_url", image_url);
  mysack.onError = function() { alert('Ajax error in user' )};
  mysack.onCompletion = function() { loadedProfile(); };
  mysack.runAJAX();
  return true;
};