(function(context,$) {
    "use strict";

    context.JK = context.JK || {};
    context.JK.FacebookHelper = function(app) {
        var logger = context.JK.logger;
        var loginStatusDeferred = null;
        var $self = $(this);
        var connected = false;

        function deferredLoginStatus() {
            return loginStatusDeferred;
        }

        // wrap calls in FB JS API calls in this
        // if the user is not logged in, they will be prompted to log in to facebook
        // if they are already logged in, the deferred object is immediately returned
        // returns a deferred object that never calls .fail().  Just call .done(function(response)),
        // and check:   if(response && response.status == "connected") to know if you should carry on wih the FB JS API call
        function promptLogin() {

            if(connected) {
                // instantly return previous login info
                return loginStatusDeferred;
            }

            loginStatusDeferred = $.Deferred();

            FB.login(function(response) {
                handle_fblogin_response(response);
            }, {scope:'publish_stream'});

            return loginStatusDeferred;
        }

        function handle_fblogin_response(response) {

            logger.debug("facebook login response: status=" + response.status)

            if(response.status == "connected") {
                connected = true;
            }

            $self.triggerHandler('fb.login_response', {response: response});

            loginStatusDeferred.resolve(response);
        }

        function initialize(fbAppID) {
            loginStatusDeferred = $.Deferred();
            var fbAppID_ = fbAppID;
              window.fbAsyncInit = function() {
                FB.init({
                    appId      : fbAppID_,
                    // channelUrl : '//WWW.YOUR_DOMAIN.COM/channel.html',
                    status     : true, // check the login status upon init?
                    cookie     : true, // set sessions cookies to allow server to access the session?
                    xfbml      : true,  // parse XFBML tags on this page?
                    oauth      : true // enable OAuth 2.0
                });

                // listen to see if the user is known/logged in
                FB.getLoginStatus(function(response) {
                    handle_fblogin_response(response);
                });
            };

            // Load the SDK Asynchronously
            (function(d){
                var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}
                js = d.createElement('script'); js.id = id; js.async = true;
                js.src = "//connect.facebook.net/en_US/all.js";
                d.getElementsByTagName('head')[0].appendChild(js);
            }(document));

          deferredLoginStatus()
            .done(function() {
              FB.Event.subscribe('edge.create', function(response) {
                JK.GA.trackJKSocial(JK.GA.Categories.jkFollow, JK.GA.JKSocialTargets.facebook, JK.clientType());
              });
            });

        }

        this.initialize = initialize;
        this.promptLogin = promptLogin;
        this.deferredLoginStatus = deferredLoginStatus;
        this.ready = deferredLoginStatus; // shorter alias for deferredLoginStatus
    };
})(window, jQuery);