var facebook_user= false;

var facebook = {
	/*
	facebook class
	*/
	user: facebook_user,
	initSession: false,
	/* This is data we require for the site*/
	req_data: new Array("uid","first_name", "middle_name", "last_name", "name","pic_small","pic_big","pic_square","pic","affiliations","profile_update_time","birthday","birthday_date","sex","hometown_location","email"),
	init: function(key,session){
		//FB.Event.subscribe('auth.login', bind(this,this.handleLogin));
		//FB.Event.subscribe('auth.logout', bind(this,this.handleLogout));
		
					/*console.log('session:');
					console.log(session);
					console.log('this.initSession:');
					console.log(this.initSession);
		//this.initSession = session;
					console.log('this.initSession2:');
					console.log(this.initSession);
		//FB.Event.subscribe('auth.sessionChange', this.sessionChange);	
					console.log('init fb session');*/
		FB.init(
			{ 
				apiKey: key,
				//session: (session==false?null:session),
				status : true, // check login status
				cookie : true, // enable cookies to allow the server to access the session	
				xfbml  : true,  // parse XFBML
				logging: false
			}
		);
		
		
	},
	logout: function(){
		$.cookie('facebook_user',null);
	},
	/*
	Deauthorizes the app from any permissions
	*/
	deauth: function(){
		FB.api({ method: 'Auth.revokeAuthorization' });
		$.cookie('facebook_user',null);
	},
	checkLogin: function(trueFunc,falseFunc,variable){
		FB.getLoginStatus(function(response) {
			if (response.session) {
				console.log('logged in');
				return trueFunc(variable);
			} else {
				console.log('NOT logged in');
				return falseFunc(variable);
			}
		});
	},
	getUserDetails: function(){
		/*
			Gets as much information as we can about the user, and stores it
			to a cookie as a method of local caching
		*/
		
		var user = FB.Data.query("SELECT " + facebook.req_data.join(',') + " FROM user WHERE uid={0}",facebook_user.uid);
		var profile = FB.Data.query("SELECT username,type FROM profile WHERE id={0}",facebook_user.uid);
		FB.Data.waitOn([user, profile], function(){		
			facebook_user.user = {};
			facebook_user.profile = {};
			FB.Array.forEach(user.value, function(row) {
				$.extend(facebook_user.user, row);
			});	
			FB.Array.forEach(profile.value, function(row) {
				$.extend(facebook_user.profile, row);
			});	
			/* 
				Cache the FQL Results in a cookie so we can load 
				faster without calling the API on next page loads			
			*/
					console.log('We got the users info, change UI stuff....');
			$.cookie('facebook_user',$.toJSON(facebook_user));
			facebook.postUserInfo();
		});
	},
	/*
		This function is called once the facebook_user is populated with 
		the needed information
	*/
	postUserInfo: function(){
		
		if(this.initSession == false)
			location.reload(true);
		facebook_user = FB.getSession();
		// Manage global UI elements
		facebook.uiElements();
		try
		{
			if(page != undefined && $.isFunction(page.facebookInit)) {
				// see if there is a page-specific function to run
				page.facebookInit();
			}
		}
		catch(err)
		{
		}
	},
	sessionChange: function(response){
		//location.reload(true);
	},	
	/*
	Called when a facebook user logs in
	*/
	handleLogin: function(response){
					console.log('handleLogin');
		if (response.session == undefined && facebook_user != false) {
			
					console.log('Logout!');
			handleLogout();
			return;
		} else {
			/*
				Check the local cache, see if we've already gotten user 
				information in a previous session			
			*/
			if(facebook_cache_cookie = $.cookie('facebook_user')){	
				/*
					 There is a cache, so let's grab it and set facebook_user
					 to it, while attempting to retain any new session data
				*/		
				var empty = {};
				facebook_cache_cookie = $.evalJSON(facebook_cache_cookie);
				$.extend(empty,facebook_cache_cookie,facebook_user);
				facebook_user = empty;
				//facebook.postUserInfo();
				console.log('cache set, session sterted, logged in.');
				console.log(this.initSession);
				
				if(this.initSession == false){
					console.log('initSession was false, now that we have a FB session, reload');
					//location.reload(true);
					
				}
					
				facebook_user = FB.getSession();
			} else {
				/*
					No cache was found, so query FQL/API for info
				*/
					console.log('no cache was found, get the information');
				facebook.getUserDetails();				
			}
			
		}
	},
	/* handle global UI Elements  */
	uiElements: function(){
          //window.location.reload();
		$(".user_name").html(facebook_user.user.name);
		$(".user_pic").html('<img src="http://external.ak.fbcdn.net/safe_image.php?url=' + facebook_user.user.pic_square + '&logo" width="50" height="50">');
	},
	/*
	Called when a facebook user logs out
	*/
	handleLogout: function(){
		facebook_user = false;
		$(".user_name").html('guest');
		$(".user_pic").html('');
	},
	getUserKey: function(key){
		if(eval("facebook_user[\"" + key+"\"]") == undefined){
			FB.api(
				{
					method: 'fql.query',
					query: 'SELECT ' + key + ' FROM profile WHERE uid=' + facebook_user.uid
				}, 
				facebook.handleFqlResult
			);
		}
		return eval("facebook_user." + key);
	}
};


function bind(scope, fn) {
    return function () {
        fn.apply(scope, arguments);
    };
}

