/* @SD
 * H
 *
 * TODO enum perms
 * other graph & fql function
 *
 */ 

$(function(){
    $('<div/>').attr('id', 'fb-root').appendTo($('body'));
    $('<script/>').attr({
        'type': 'text/javascript',
        'src': document.location.protocol + '//connect.facebook.net/en_US/all.js',
        'async': true
    }).appendTo($('#fb-root'));
});

$(function() {
	window.fbAsyncInit = function() {
		FB.init({appId: FB_APP_ID, status: true, cookie: true, xfbml: true});

		facebook.initialized = true;
		facebook.triggerInit();

		// All the events registered 
		//FB.Event.subscribe('auth.login', function(response) {
		//	facebook.login();
		//});

		//FB.Event.subscribe('auth.logout', function(response) {
			// do nothing for now
			//facebook.postLogout();
		//});
	};
});

var facebook = {
    'init': function(callback) {
		$(this).one('initialized', callback);
		this.triggerInit();
    },

	'initialized': false,

	'triggerInit': function() {
		if(facebook.initialized) {
			$(this).trigger('initialized');
		}
	},

    // params format { key: value, key1: value1 }
    'api': function (path, method, params, callback) {
        FB.api(path, method, params, function(data) {
            if(jQuery.isFunction(callback)) {
                callback(data);
            }
        });
    },

    'get': function(path, params, callback) {
        this.api(path, 'GET', params, callback);
    },

    'publish': function() {
		 FB.ui({
				method: 'stream.publish',
				message: '',
				attachment: {
					name: name,
					caption: '',
					description: (description),
					href: hrefLink
				},
				action_links: [
					{ text: hrefTitle, href: hrefLink }
				],
				user_prompt_message: userPrompt
			},
			function(response) {

			});
    },

    'user': function(callback) {
        this.get('/me', {}, callback);
    },

    'picture': function(type, callback) {
        //type = { small, normal, large }
        this.get('/me/picture', {'type': type}, callback);
    },

    'login': function(callback) {
        if(LOGGED_IN) {
            //donothing
        }
        else {
            FB.getLoginStatus(function(response) {
                if (response.session) {
                    data = response;
                    // connected user -> automatically log in 
                    facebook.postLogin();

                    if(jQuery.isFunction(callback)) {
                        callback(data);
                    }
                }
                else {
                    // not connected
                }
            });
        }
    },

    'loginStatus': function(callback) {
        FB.getLoginStatus(function(response) {
            // [ connected, notConnected, unknown ]
            data = response;

            if(jQuery.isFunction(callback)) {
                callback(data);
            }
        });
    },

    'postLogin': function() {
        loginByFb();
    },

    'postLogout': function() {
        $('#login').hide();
    },

    'requestPerm': function(callback) {
        FB.login(function(data) {
            if (data.session) {
                if (data.perms) {
                    // user is logged in and granted some permissions.
                    // perms is a comma separated list of granted permissions
                    if(jQuery.isFunction(callback)) {
                        callback(data);
                    }
                } else {
                    // user is logged in, but did not grant any permissions
                    // copywriting needed
                    alert('Please grant us permission for your Facebook Connect');
                }
            } else {
                // user is not logged in
                // copywriting needed
                alert('Please grant us permission for your Facebook Connect');
            }
        }, {perms: this.permissions.join(',') });
    },

	'tryLogin': function(callbacks) {
		var doCallback = function(name, data) {
			//console.debug("calling ", name, data);
			if(jQuery.isFunction(callbacks[name])) {
				(callbacks[name])(data);
			}
		};

		facebook.loginStatus(function(data) {
			if(data.status == 'connected') {
				loginByFb(function(isLoggedIn) {
					if(isLoggedIn) {
						//doCallback("loggedIn", data);
                        window.location.reload();
					} else {
						//doCallback("register", data);
                        alert('Log in by Facebook was unsuccesful.');
					}
				});
			} else if(data.status == 'unknown') {
				facebook.requestPerm(function(data) {
					if(data.status == 'connected') {
						//doCallback("register", data);
                        window.location.reload();
					}
				});
			}
		});
	},

    'permissions': [
        'read_stream',
        'publish_stream',
        'email'
     ]

}

