var uscc = uscc || {};
uscc.sng = uscc.sng || {};
uscc.sng.socnet = uscc.sng.socnet || {};

/**
 * @class SimpleAuthentication
 *
 * SocialNetworkSettings : Allows a user to authenticate and deactivate their account through SNG
 *
 *      var simpleAuth = new uscc.sng.socnet.SimpleAuthentication(containerSelector, options);
 *
 *      options:
 *          {...
 *
 *          containerSelector: <selector to div element containing form element>,
 *          options : {...
 *
 *                  ...
 *          ...}
 *
 *
 * @events onAuthenticated.FacebookGraph
*/


uscc.sng.socnet.FacebookGraph = (function(){

    var _self = {};

    _self.authenticateUser = function(callback){
       if(FB._userStatus === "connected"){
           _self.logout();
       }
        
     /*  FB.login(function(response) {
           if (response.session) {
                SngAPI.storeSession(
                    {
                        session:JSON.stringify(response.session),
                        method:"fb_access_token"
                    },
                    {
                        "sns.uid" : "FB"
                    },

                        callback

                    , {});
          } else {
                //handle the error
          }
        }, {perms:'publish_stream,offline_access'});//need to confirm the permissions needed, persume its only publish and offline access

    };
	*/
	//new correct code from breffni
    FB.login(function(response) {
        
           if (response.status === "connected") {

  var activeSNJson = JSON.stringify({"access_token": response.authResponse.accessToken, uid: response.authResponse.userID, "expires": response.authResponse.expiresIn});
                SngAPI.storeSession ({session:activeSNJson, method:"fb_access_token"}, {"sns.uid" : "FB"}, callback, {});       
          }
   else {
                //handle the error
          }
   
        }, {scope:'publish_stream,offline_access'});
	};

    _self.disableAccount = function(callback){
        SngAPI.deactivateAccount({},{"sns.uid" : "FB"}, callback, {} );
        _self.logout ();
    };

    _self.logout = function(){
        FB.logout(function(response){

        });
    };
    
    var _init = function(){

        //load in the facebook library Asynchronously
        var e = document.createElement('script');
            e.async = true;
            e.src = document.location.protocol +'//connect.facebook.net/en_US/all.js';
            try{
                //this needs to change to be loaded only on the settings page.
                document.getElementById('fb-root').appendChild(e);
            }catch(e){

            }
        window.fbAsyncInit = function() {
            FB.init({oauth:true, appId: newbay.facebookAppId, status: true, cookie: true});
        };
    }

    $(document).ready(function(){
        _init ();
    });

    return _self;
        
}());

