//
// Facebook object
//
// Flow:
//
// +---------------+      +---------------+
// | JS Not Loaded |      | JS Loaded     |
// | FB Logged Out |      | FB Logged Out |
// +---------------+      +---------------+
//
//
// +---------------+      +---------------+
// | JS Not Loaded |      | JS Loaded     |
// | FB Logged In  |      | FB Logged In  |
// +---------------+      +---------------+
//
var Facebook = (function() {
	var initalized = false;  // Flag to lazy load then Facebook JS library.
	var session;             //
	var FB_Api;              //
	var loggedIn = false;    //
	var userData;            //

	//
	// Function: _init
	//
	// Description:
	// This will check if Facebook JS Library has been initalize or not.
	// Should be called with every function en ensure the FeatureLoader is loaded.
	//
	function _init(callback, appsettings) {
		if (initalized) {
			if (typeof callback === "function") {
				callback();
			}
		} else {
			// Prevents _init from being called twice.
			initalized = true;

			// Load the Facebook connect JavaScript dynamically after a user requests it.
			// Take note of this, that is in the Facebook documentation
			// add this script in the <body> of your page (it may write directly to the document, so including it in the <head> can be problematic)
			// http://wiki.developers.facebook.com/index.php/FeatureLoader.js.php
			var body = document.getElementsByTagName("body")[0];
			var script = document.createElement("script");
			script.src = (document.location.protocol === "https:" ? "https://ssl.connect" : "http://static.ak") + ".facebook.com/js/api_lib/v0.4/FeatureLoader.js.php";
			script.onload = script.onreadystatechange = function(foo) {
				// Need this typeof because IE sometimes called onreadystatechange twice, and the first time the script isn't loaded.
				if(typeof FB_RequireFeatures === "function") {
					FB_RequireFeatures(["Connect"], function() {
						FB.Facebook.init(Facebook.api_key, "/xd_receiver.html", appsettings);
						FB_Api = FB.Facebook.apiClient;
						session = FB_Api.get_session();

						if (typeof callback === "function") {
							callback(session);
						}
					});
				}
			}

			body.insertBefore(script, body.firstChild);
		}
	}

	return {

		// This key identifies your application to Facebook. You pass it with all your API calls.
		// Facebook.api_key = "1426fd30a90c6fc2d0afe66a7c38f7b7";
		api_key: "",

		//
		// Function: initalize
		// Documentation: Loads the Facebook JavaScript library after the page is ready
		//                This way it doesnt block page load.
		// Usage:
		//   Facebook.initalize();
		//
		// Usage:
		//   Facebook.initalize(function(session){
		//   	alert(session);
		//   });
		//
		initalize: function(callback) {
			var originalOnload = window.onload;
			window.onload = function() {
				_init(function(){
					if(typeof callback === "function") {
						callback(session);
					}
				});
				if(typeof originalOnload === "function") {
					originalOnload();
				}
			}
		},

		//
		// Function: Connect
		// Documentation: http://wiki.developers.facebook.com/index.php/Logging_In_And_Connecting
		//                http://wiki.developers.facebook.com/index.php/Facebook_Connect_Login_Buttons
		//                http://wiki.developers.facebook.com/index.php/FB_RequireFeatures
		// Usage:
		//   Facebook.connect(function() {
		//     // Do whatever in here.
		//   });
		//
		connect: function(callback, appsettings) {
			_init(function(session) {
				FB_RequireFeatures(["Connect"], function() {
					// This will prompt the user with a facebook popup.
					FB.Connect.requireSession(function() {
						session = FB_Api.get_session();

						if (typeof callback === "function") {
							callback(session);
						}
					});
				});
			}, appsettings);
		},

		//
		// Function: logout
		//
		// http://forum.developers.facebook.com/viewtopic.php?pid=152209
		// http://bugs.developers.facebook.com/show_bug.cgi?id=5710
		//
		// Usage:
		//   Facebook.logout(function() {
		//     window.location = "/logout/";
		//   });
		//
		logout: function(callback) {
			_init(function(session) {
				FB.Connect.logout(function() {
					if (typeof callback === "function") {
						callback();
					}
				});
			});
		},

		//
		// Function: getUsers
		// Description:
		//
		// Documentation: http://developers.facebook.com/docs/?u=facebook.jslib.FB.ApiClient.users_getInfo
		//				  http://wiki.developers.facebook.com/index.php/Users.getInfo
		//
		// Usage:
		//   Facebook.getUsers([session.uid], function(data) {
		//		userData = data[0];
		//   });
		//
		getUsers: function(users, callback) {
			_init(function(session) {
				FB_Api.users_getInfo(users, ['name', 'pic_square', 'email', 'is_app_user'], function(data) {
					if (typeof callback === "function") {
						callback(data);
					}
				});
			});
		},

		//
		// Function: getFriends
		// Description:
		//
		// Documentation: http://wiki.developers.facebook.com/index.php/JavaScript_Client_Library
		//
		// Usage:
		//   Facebook.getFriends(function(data) {
		//		// do something with data
		//   });
		//
		getFriends: function(callback) {
			// Require user to be connect if you want their friends
			// But maybe we just want to return false if they aren't connected... hrmmm
			Facebook.connect(function() {
				FB_Api.friends_get(null, function(result, exception) {
					Facebook.getUsers(result, function(data) {
						if (typeof callback === "function") {
							callback(data);
						}
					});
				});
			});
		},

		//
		// Function: publish
		// Description: Publish some content to the user's wall
		//
		// Documentation:
		//    http://wiki.developers.facebook.com/index.php/Attachment_%28Streams%29
		//
		// @data:
		//    user_message: "Monkey just tracked a banana",
		//    attachment: null, <-- THIS IS HOW YOU PUT TEXT IN THIS MOFO
		//    action_links: [{"text": "Watch Video", "href": "http://www.myvideosite/videopage.html"},
		//                   {"text": "See More", "href": "http://www.mysite.com/seemore.html"}],
		//    target_id: null,
		//    user_message_prompt: "Share on Facebook:",
		//    callback: function() { ... },
		//    auto_publish: true
		//    actor_id: null,
		//
		// Usage:
		//  Facebook.publish({
		//     attachment: {
		//       name: "I just ate",
		//       href: "http://www.livestrong.com",
		//       description: "adsfsadf safsafd sadfsad fdsafsadfw fedfhfgjkfghds fe",
		//       media: [{
		//         type: "image",
		//         src: "http://msn.mess.be/data/thumbnails/17/frog.gif",
		//         href: "http://bit.ly/hifZk"
		//         }]
		//     }
		//  });
		//
		publish: function(data) {
			if (typeof data.user_message_prompt === "undefined") {
				data.user_message_prompt = "Share on Facebook:";
			}

			_init(function(session) {
				FB_RequireFeatures(["Connect"], function() {
					FB.Connect.get_status().waitUntilReady(function(status) {
						FB.Connect.streamPublish(
							data.user_message,
							data.attachment,
							data.action_links,
							data.target_id,
							data.user_message_prompt,
							data.callback,
							data.auto_publish,
							data.actor_id);
					});
				});
			});
		},

		//
		// Function: shareNumber
		//
		// Documentation:
		//    http://wiki.developers.facebook.com/index.php/Link_stat_%28FQL%29
		//
		shareNumber: function(url, callback) {
			_init(function(session) {
				FB.Facebook.apiClient.fql_query('SELECT share_count, like_count, comment_count, total_count FROM link_stat WHERE url="'+url+'"',
				function(rows) {
					if (typeof callback === "function") {
						callback(rows[0]);
					}
				});
			});
		},

		//
		// Function: share
		//
		share: function() {
			var id = "facebookShare";
// 			printd(window);
			var url = window.location.href;
			document.write('<a id="' + id + '"></a>');
			var span = document.getElementById(id);
			span.onclick = function() {
				window.open('http://www.facebook.com/sharer.php?u=' + encodeURIComponent(url) + '&t=' + 'asfdsaf');
			}

			Facebook.shareNumber(url, function(data) {
				span.innerHTML = data.total_count;
			});
		},





/*

	//
	// Function: _getUserData
	//
	// Not sure when to call this.
	// Tried to put in "_init" when the library is loaded,... but what if they are NOT connected.
	// You can't get user data
	//
	// Should this be public?
	//
	function _getUserData() {
		// Get the user's data
		// http://developers.facebook.com/docs/?u=facebook.jslib.FB.Connect.get_status
		FB.Connect.get_status().waitUntilReady(function(status) {
			if (status === FB.ConnectState.connected) {
				// Get the users information
				session = FB_Api.get_session();
				if (session) {
					loggedIn = true;
					Facebook.getUsers([session.uid], function(data) {
						// Store the user's data in this object somewhere.
						userData = data[0];
					});
				};
			}
		});
	}
*/



		//
		// Function: isFan
		//
		extendedPermissions: function() {
			Facebook.connect(function() {
				FB.Connect.showPermissionDialog("email");
			});
		}

	}
})();
