var k1fb = {
  authorized: false,
  settings: {
	scope: 'publish_stream,email',
    appId: null,
    loggedIn: false,
    postLoginUrl: '/fbAuth/postFbLogin'
  },
  
  
   
  init: function(config, loggedIn){
    
    $.extend(k1fb.settings, config);
        
    FB.init({
      appId: k1fb.settings.appId,
      status: true, // check login status
      cookie: true, //enable cookies to allow the server to access the session
      xfbml: true, // parse XFBML
      oauth: true
    });
    
    
    
    
    // fetch the status on load
    FB.getLoginStatus(function(response){
      if (response.session) {
        k1fb.authorized = true;
      }
    });
    
    if(typeof fbCallback != 'undefined'){
      console.log('executing callback');
      fbCallback();
    }
    else{
      console.log('no callback defined!');
    }
    
    FB.XFBML.parse();
  },
    
  
  events: {
    
    /**
     * handles clicks on fb login button
     */
    onLoginClick: function(){
      if(k1fb.authorized === false){
        FB.login(
          function(response){
            // if we dont have a session, show login link or trigger click on it
        	  if (response.authResponse) {
        		  k1fb.authorized = true;
        		  var accessToken = response.authResponse.accessToken;
        		  var uid = response.authResponse.userID;
        		  var signedRequest = response.authResponse.signedRequest;
        		  document.location.href = k1fb.settings.postLoginUrl+'?expiresIn='+response.authResponse.expiresIn+'&accessToken='+accessToken+'&uid='+uid+'&signedRequest='+signedRequest;
        		  }
        	 
          }, 
          {
        	  scope:'email'
          }
        );        
      }
      else{
        document.location.href = k1fb.settings.postLoginUrl;
      }
    },
    
    /**
     * 
     * handle clicks on fb logout button
     * 
     */
    onLogoutClick: function(){
      if(k1fb.authorized == true){
        FB.logout(function(){
          k1fb.authorized = false;
          document.location.href = this.href;
        });
        
      }
    },    
    
    /**
     * handles clicks on disconnect button
     */
    onDisconnectClick: function(){
      if (k1fb.authorized == true) {
        FB.api({
          method: 'Auth.revokeAuthorization'
        }, function(response){
          document.location.href = this.href;
        });
      }
    }
  }
};
