// Request FC for user information
// if (valid user) {
//   Send a request to server_code.php to create/login this user
//   Once request comes back, Modify the HTML to show credentials of new user
//   Show the SignOut link  
// } else {
//   Show the SignIn link
// }

// Send request to FC with request for user 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.
     document.getElementById('profile').innerHTML =
     '<img align="left" src="http://www.google.com/friendconnect/scs/images/googleicon.gif" alt="avatar"/>' +
     //'<img align="left" src="' +  viewer.getField("thumbnailUrl") + '" alt="avatar"/>' +
     '<strong>' +  viewer.getField("displayName") + '</strong>, ' +
     '<a href="#" onclick="google.friendconnect.requestSettings()">Settings</a>, ' +   
     '<a href="#" onclick="google.friendconnect.requestInvite()">Invite</a>, ' +
     '<a href="#" onclick="google.friendconnect.requestSignOut()">Sign out</a>';
     //'<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 || FC_USER == 0) {
       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() {
   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="'+FC_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( FC_PLUGIN_URL + "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;
 };
