// Helper functions for FB Connect
// adapted from fb_connect.js in the demo site
// Requires FbHelperConfig
var FbHelper = {
  isInitialized: false,
  
  // called by various methods to ensure authentication
  ensureInit: function (callback) {
    if (FbHelper.isInitialized) {
      callback();
    } else {
      FB_RequireFeatures(["XFBML"], function() {
        FB.Facebook.init(FbHelperConfig.apiKey, FbHelperConfig.xdReceiverUrl);
        FbHelper.isInitialized = true;
        callback();
      });
    }
  },
  
  onload: function (already_logged_into_facebook) {
    // user state is either: has a session, or does not.
    // if the state has changed, detect that and reload.
    this.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;
            }
          });
      });
  },
  
  loginClickHandler: function (redirectUrl) {
    this.ensureInit(function () {
      FB.Facebook.get_sessionState().waitUntilReady(function() {
        var user = FB.Facebook.apiClient.get_session() ?
          FB.Facebook.apiClient.get_session().uid :
          null;
          // probably should give some indication of failure to the user
          if (!user) {
            return;
          }
        // refresh page after initial login
        FbHelper.loginStatusChange(redirectUrl, user);
      });
    });
  },

  setupUserForm: function () {
    this.ensureInit(function () {
      FB.Facebook.get_sessionState().waitUntilReady(function() {
        var uid = FB.Facebook.apiClient.get_session().uid;
        var name, firstName, lastName, uid, zip, pic;
        FB.Facebook.apiClient.users_getInfo(uid, [
          'name', 
          'first_name', 
          'last_name', 
          'current_location.city',
          'current_location.state',
          'current_location.country',
          'current_location.zip',
          'pic',
          'uid',
          'affiliations', // regional only
          'birthday',
          'work_history',
          'education_history'
          ],
          function(r,e){
            if (name = document.getElementById(FbHelperConfig.userFormIds.name)) name.value = r[0].name;
            if (lastName = document.getElementById(FbHelperConfig.userFormIds.lastName)) lastName.value = r[0].last_name;
            if (firstName = document.getElementById(FbHelperConfig.userFormIds.firstName)) firstName.value = r[0].first_name;
            if (uid = document.getElementById(FbHelperConfig.userFormIds.uid)) uid.value = r[0].uid;
			if (uid = document.getElementById(FbHelperConfig.userFormIds.additionalUid)) uid.value = r[0].uid;
            if (zip = document.getElementById(FbHelperConfig.userFormIds.zip)) zip.value = r[0].current_location.zip;
			if (school_year = document.getElementById(FbHelperConfig.userFormIds.school_year)) gradyear.value = r[0].school_year;
            if (pic = document.getElementById(FbHelperConfig.userFormIds.pic)) pic.value = r[0].pic;
            
            if (window.console) console.log();
            if (window.console) console.log(r[0].education_history);
            
            /**
             Other fields are available, even if we can't populate the form with them
             Perhaps you want to some extra info in new DB columns...
            */
			
            var affils = [];
            if (r[0].affiliations) {
              for (var i=0; i<r[0].affiliations.length; i++) {
                affils.push(r[0].affiliations[i].name)
              }
            }
            if (sample = document.getElementById('sample')) {
              if (r[0].work_history && r[0].work_history[0]) { var employer = r[0].work_history[0].company_name; }
              if (r[0].education_history && r[0].education_history[0]) { 
                var school = r[0].education_history[0].name; 
                var school_year = r[0].education_history[0].year; 
              }
              
              sample.innerHTML = "Other fields are available for the taking... <br>" + 
                'city: ' + r[0].current_location.city + '<br>' +
                'state: ' + r[0].current_location.state + '<br>' +  
                'affiliations: '+ affils.join(', ') + '<br> ' + 
                'most recent school name: '+ school + '<br> ' + 
                'grad year: ' + school_year + '<br>' +
                'birthday: '+ r[0].birthday + '<br>' +
                'most recent employer:' + employer;
            }
            
          }
        );
      });
    });
  },
  
  refreshPage: function () {
    window.location = window.location;
  },
  
  // Note: start page will redirect to index if logged in through FB connect
  loginStatusChange: function (redirectUrl, fb_uid) {
    if (redirectUrl) {
      window.location = redirectUrl;
    } else {
      window.location = FbHelperConfig.appRootDir + 'facebook_connector/director.php?facebook_uid='+fb_uid;
    }
  },
  
  /*
   * 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.
   *
   */
  publishFeedStory: function (form_bundle_id, template_data) {

    FbHelper.ensureInit(function() {
      FB.Connect.showFeedDialog(form_bundle_id, template_data);
      // hide the "Loading feed story ..." div
      // ge('feed_loading').style.visibility = "hidden";
    });
  }
  
  

};


