-------------------------------------------------------
-- facebook_functions
-------------------------------------------------------

------------------- MAKE LINKS ------------------------

--- Create an FB tag for an image; pass it to stream.media;
function facebook_make_image(url, link)
	return '[{"type":"image", "src":"'..url..'", "href":"'..link..'"}]';
end

--- Create an FB tag for an actionlink; pass it to stream.action_links;
function facebook_make_action_link(text, link, num)
	return '"link'..num..'":{"text":"'..text..'", "href":"'..link..'"}';
end

--- Create an FB tag for a single actionlink; pass it to stream.action_links;
function facebook_make_action_link_1(text1, link1)
	return '{'..facebook_make_action_link(text1, link1, 1)..'}';
end

--- Create an FB tag for a dual actionlink; pass it to stream.action_links;
function facebook_make_action_link_2(text1, link1, text2, link2)
	return '{'..facebook_make_action_link(text1, link1, 1)..', '..facebook_make_action_link(text2, link2, 2)..'}';
end

function FB_IsVersionTwo()
	-- if we're executing this updated lua script on a version-one executable then 
	-- Facebook_IsVersionTwo would be nil
	return Facebook_IsVersionTwo and Facebook_IsVersionTwo();
end;

------------------- LOOKUP STRINGS ---------------------------------
-- These functions are used in the construction of stream entries
-- They generally expect to pull from 
--		/assets/facebook/common/facebook_common_strings.xml and 
--		/assets/facebook/game/facebook_game_strings.xml
--
-- stream entry IDs take the form
--	facebook_stream_{membertype}_{streamname}
-- 
-- where membertype can be
--	'phrase'
--	'postdescription'
--	'postcaption'
--	'postname'
--  'postimageurl'
--  'usertext'
--  'dlg_title'
--	'metricstype'
-- 
-- and streamname is 
--	'generic' (the default values)
--	'userpost' (a simple user news feed)
--	'screenshot' (an ingame screenshot upload)
--	'photo' (an alternate ingame image upload)
--  medal_medalname (eg medal_wandering_willows_bff)
--  goal_something	(eg goal_0)
--  or any other game-defined stream
--------------------------------------------------------------------

--- Create a string for a dialog title; pass it to stream.ingametitle;
--- This starts with the string 'facebook_stream_dlg_body' and subsitutes facebook_stream_phrase_{streamname} for <achievement>.
function facebook_make_in_game_title(streamname)
	-- local format = GetString('facebook_stream_dlg_body');
	-- local answer = string.gsub(format, '<achievement>', GetString('facebook_stream_phrase_' .. streamname));
	local answer = GetString('facebook_stream_phrase_' .. streamname);
	return answer;
end


--- Look up a stream's metricstype; [pass it to stream.metricstype]
function facebook_get_stream_metricstype(streamname)
	return GetString('facebook_stream_metricstype_'..streamname);
end

--- Create a stream's href - current format is
---		kFBApplicationURL?facebook_format_metrics
--- which amounts to
---		http://www.playfirst.com/game/wandering-willows?cm_mmc=Social-_-Facebook-_-<metricstype>_-wandering-willows
---
function facebook_get_stream_href(streamname)
	local metricsformat = GetString('facebook_format_metrics');
	local metricspart = string.gsub(metricsformat, '<metricstype>', facebook_get_stream_metricstype(streamname));
	return kFBApplicationURL .. metricspart;
end;

--- Look up a stream's postdescription; pass it to stream.description;
function facebook_get_stream_postdescription(streamname)
	return GetString('facebook_stream_postdescription_'..streamname);
end

--- Look up a stream's postname; pass it to stream.name;
function facebook_get_stream_postname(streamname)
	return GetString('facebook_stream_postname_'..streamname);
end

--- Look up a stream's postcaption; pass it to stream.caption;
function facebook_get_stream_postcaption(streamname)
	return GetString('facebook_stream_postcaption_'..streamname);
end

--- Look up a stream's postimageurl; pass it to facebook_make_image, which feeds stream.media
function facebook_get_stream_postimageurl(streamname)
	return GetString('facebook_stream_postimageurl_'..streamname);
end

--- Look up a stream's usertext; pass it to stream.defaultusertext
function facebook_get_stream_usertext(streamname)
	return "<i>" .. GetString('facebook_stream_usertext_'..streamname) .. "</i>";
end

--- Look up a stream's dialog title; pass it to stream.title
function facebook_get_stream_dlg_title(streamname)
	return GetString('facebook_stream_dlg_title_'..streamname);
end

--- Create a combined media entry for a stream
function facebook_get_stream_media(streamname)
	return facebook_make_image(facebook_get_stream_postimageurl(streamname), facebook_get_stream_href(streamname));
end;

---------------------------------------------------------------------
-- All-in-one: create a 'goal' stream
--  required strings:
--      facebook_stream_phrase_{goalname} + facebook_stream_dlg_body
--		facebook_stream_postname_{goalname}
--		facebook_stream_postcaption_{goalname}
--		facebook_stream_postimageurl_{goalname}
--  required local images
--		assets/facebook/game/medal_{goalname}.png
--  required web images
--      facebook_stream_postimageurl_{goalname}
---------------------------------------------------------------------
function facebook_make_goal_stream(goalname)
	local defer_eval = function(goalname)
		return
		{
			dialogfile = 'dlg_post_medal',
			href = facebook_get_stream_href('medal'),
			
			ingametitle = facebook_make_in_game_title(goalname),
			name = facebook_get_stream_postname(goalname),
			caption = facebook_get_stream_postcaption(goalname),
			media = facebook_make_image(facebook_get_stream_postimageurl(goalname), facebook_get_stream_href('goal'));
			iconname = goalname,
			metrics_on_success = 'FBMedalPostSubmits',
		};	
	end;
	return defer_eval(goalname);
end;

---------------------------------------------------------------------
-- All-in-one: create a 'medal' stream
--  required strings:
--      facebook_stream_phrase_{medalname} + facebook_stream_dlg_body
--		facebook_stream_postname_{medalname}
--		facebook_stream_postcaption_{medalname}
--  required local images
--		assets/facebook/game/medal_{medalname}.png
--  required web images
--      kFBBaseMedalURL/{medalname}
---------------------------------------------------------------------
function facebook_make_medal_stream(medalname)
	local defer_eval = function(medalname)
		return
		{
			dialogfile = 'dlg_post_medal',
			href = facebook_get_stream_href('medal'),
			
			ingametitle = facebook_make_in_game_title(medalname);
			name = facebook_get_stream_postname(medalname),
			caption = facebook_get_stream_postcaption(medalname),
			media = facebook_make_image(kFBBaseMedalURL .. medalname .. ".png", facebook_get_stream_href('medal'));
			iconname = medalname,
			metrics_on_success = 'FBMedalPostSubmits',

		};	
	end;
	return defer_eval(medalname);
end;

------------------- LOOKUP GLOBAL STRINGS ------------------------

--kFBApplicationAppURL = "http://www.facebook.com/apps/application.php?id=115373356878";
--kFBApplicationFanPageURL = "http://www.facebook.com/Cooking-Dash-DinerTown-Studios/156701848556";
--kFBApplicationAppURL = "http://www.facebook.com/apps/application.php?id=308336335595";
--kFBApplicationFanPageURL = "http://www.facebook.com/pages/Diner-Dash-Hometown-Hero/190117350870";
--kFBApplicationAppURL = http://www.facebook.com/apps/application.php?id=184928405279";
--kFBApplicationFanPageURL = http://www.facebook.com/pages/Wedding-Dash-Ready-Aim-Love/155470532709";
--kFBApplicationAppURL = "http://www.facebook.com/apps/application.php?id=115373356878";
--kFBApplicationFanPageURL = "http://www.facebook.com/pages/wanderingwillows";
--kFBApplicationHandle = GetString('facebook_application_handle');				-- PF URL		"wandering-willows"
--kFBApplicationAppURL = GetString('facebook_stream_postlinkurl_fbapp);			-- "http://www.facebook.com/apps/application.php?id=#########";

kFBApplicationName = GetString('facebook_application_name');					-- USER NAME	"Wandering Willows"
kFBBaseMedalURL = "http://p.playfirst.com/img/misc/fb/the-fifth-gate/";

kFBApplicationURL = GetString('facebook_stream_postlinkurl_pfapp');				-- "http://www.playfirst.com/game/".. kFBApplicationHandle;
kFBApplicationFanPageURL = GetString('facebook_stream_postlinkurl_fanpage');	-- "http://www.facebook.com/pages/gamename/############";

---------------------------------------------------------------
-- NOW it's safe to evaluate facebook_streams.lua
---------------------------------------------------------------

facebookstreams_common =
{
	-- This defines all the defaults for all the streams. If you don't specify
	-- a value for a specific section, it will use the one from this defaults table
	default = 
	{
		dialogfile = 'dlg_post_comment',
		ingametitle = facebook_get_stream_dlg_title('generic'),			-- Tell your facebook friends about your accomplishment
		defaultusertext = facebook_get_stream_usertext('generic'),		-- Look, I did it
		clearcaption = true,
		name = facebook_get_stream_postname('generic'),
		href = facebook_get_stream_href('generic'),
		caption = facebook_get_stream_postcaption('generic'),					-- {*actor*} is playing gamename.
		description = facebook_get_stream_postdescription('generic'),			-- This game is soooo wonderful.
		media = facebook_make_image(facebook_get_stream_postimageurl('generic'), facebook_get_stream_href('generic'));
--[[		action_links = facebook_make_action_link_2(
				GetString('facebook_postlink_game'),	kFBApplicationURL,
				GetString('facebook_postlink_fanpage'),	kFBApplicationFanPageURL );	
--]]				
		action_links = 
			facebook_make_action_link_1( GetString('facebook_postlink_fanpage'),	kFBApplicationFanPageURL );	
			
	};

	userpost =
	{
		ingametitle = facebook_get_stream_dlg_title('userpost'),		-- Share your adventure with your friends.
		defaultusertext = facebook_get_stream_usertext('userpost'),		-- Enter text to post to your Facebook wall.
		clearcaption = true,
		name = kFBApplicationName,										-- Game Name
		caption = facebook_get_stream_postcaption('userpost'),			-- {*actor*} is currently exploring gamename.
		href = facebook_get_stream_href('userpost'),
		media = facebook_make_image(facebook_get_stream_postimageurl('generic'), facebook_get_stream_href('userpost'));
		metrics_on_success = 'FBRandomPostSubmits',
	};
	
	screenshot =
	{
		ingametitle = facebook_get_stream_dlg_title('screenshot'),
		defaultusertext = facebook_get_stream_usertext('screenshot'),
		dialogfile = 'dlg_post_screenshot',
		clearcaption = true,
		filename_to_upload = 'user:screenshot.jpg',
		href = facebook_get_stream_href('screenshot'),
		metrics_on_success = 'FBScreenshotPostSubmits',
	};

	photo =
	{
		ingametitle = facebook_get_stream_dlg_title('photo'),
		defaultusertext = facebook_get_stream_usertext('photo'),
		dialogfile = 'dlg_post_screenshot',
		clearcaption = true,
		filename_to_upload = 'user:facebook.jpg',
		href = facebook_get_stream_href('photo'),
		metrics_on_success = 'FBAvatarPostSubmits',
	};
	
	score =
	{
		dialogfile = 'dlg_post_score',
		ingametitle = facebook_get_stream_dlg_title('score'),
		defaultusertext = facebook_get_stream_usertext('score'),
		clearcaption = true,
		name = kFBApplicationName;									-- Game Name
		caption = facebook_get_stream_postcaption('score');			-- {*actor*} is currently exploring gamename.
		href = facebook_get_stream_href('score'),
		media = facebook_make_image(facebook_get_stream_postimageurl('generic'), facebook_get_stream_href('score'));
		metrics_on_success = 'FBScorePostSubmits',
	};
};

require('facebook/game/facebook_streams.lua');

---------------------------------------------------------------
--
---------------------------------------------------------------


function FB_Hideaway()
	local ww = FB_GetTopModalWindow();
	EnableWindow(ww, false);
	return ww;
end;

function FB_Unhideaway(ww)
	EnableWindow(ww, true);
end;


function facebook_hidewawaydialog(dlgspec)
	local ww = FB_Hideaway();
	local result = DisplayDialog(dlgspec);
	FB_Unhideaway(ww);
	return result;
end;


----- 
-- Functions intended to be called by game code
-----

-- This function asks the user if they want to post
-- a news stream to facebook.
--
-- Parameters:
--		* stream: the name of the stream to post. This should be a value in the facebookstreams
--					table, in facebook/game/facebook_streams.lua
--		* overrides: a table that overrides anything that would normally come from the streams table
function Facebook_PostStreamUI(stream, overrides)

	if (not IsFacebookEnabled()) then 
		return false;
	end;
	
	if (gInFacebookPostStream == true) then
		return false;
	end
	gInFacebookPostStream = true;

	local facebookstream = facebook_getstream(stream, overrides);
	local dialogfile = facebookstream.dialogfile;
	
	if (dialogfile == nil) or (dialogfile == "") then 
		dialogfile = 'dlg_post_comment';
	end;
	
	local result = DisplayDialog {
		"facebook/common/" .. dialogfile .. ".lua",
		stream = stream,
		overrides = overrides
	};
	DebugOut('DisplayDialog returned'..tostring(result));
	
	gInFacebookPostStream = false;
	return result;
end

function Facebook_PostStreamUI_Paused(stream, overrides)
	if (Facebook_Callback_EnterPause) then Facebook_Callback_EnterPause(); end;
	result = Facebook_PostStreamUI(stream, overrides);
	if (Facebook_Callback_ExitPause) then Facebook_Callback_ExitPause(); end;
    return result;
end;

function Facebook_GiveGift(friendpickertitle, stream, giftinfo)
	if (gInFacebookGiveGift == true) then
		return;
	end
	gInFacebookGiveGift = true;
	friendpicker = Facebook_FriendPickerUI(friendpickertitle, true);
	if (friendpicker ~= nil) then
		overrides = {};
		overrides.target_id = friendpicker[1];
		overrides.gift = giftinfo;
		Facebook_PostStreamUI(stream, overrides);
	end
	gInFacebookGiveGift = false;
end

function Facebook_FriendPickerUI(title, onlyOne)
	returnVal = nil;
	if (gInFacebookFriendPicker == true) then
		return returnVal;
	end
	gInFacebookFriendPicker = true;
	local result = facebook_getfriendlist(false);
	if (result[1] == true) then
		returnVal = DisplayDialog {
			"facebook/common/facebook_friendpicker.lua",
			title = title,
			onlyOne = onlyOne,
			requestid = result[2]
		};
	end
	gInFacebookFriendPicker = false;
	return returnVal;
end














---- 
-- Helper functions called within the facebook code
----

kFacebookError_NotLoggedIn = 102;
kFacebookError_InvalidPermissions = 200;
kFacebookError_FeedLimitReached = 340;


function facebook_logout()
	local id = PushModal("DoFBLogout");

	-- Facebook_StartLogout(FB_GetScreenWidth() - 5, FB_GetScreenHeight() - 5, kHAlignRight + kVAlignBottom);
	Facebook_StartLogout(FB_GetScreenWidth() / 2, FB_GetScreenHeight() - 5, kHAlignCenter + kVAlignBottom);
		
	while (true) do
		local message = WaitForMessage(1);	-- Get message pauses the script and waits for a message of some kind, or a delay
		if (Facebook_UpdateLogout() ~= 0) then
			break;
		end
	end
		
	Facebook_StopLogout();

	PopModal(id);
end


function facebook_login(foreceLogin)
	if (foreceLogin == false and Facebook_IsLoggedIn()) then
		return true;
	else
	
		local id = PushModal("DoFBLogin");
		
		Facebook_StartLogin(FB_GetScreenWidth() / 2, FB_GetScreenHeight() - 5, kHAlignCenter + kVAlignBottom);
		
		while (true) do
			local message = WaitForMessage(1);	-- Get message pauses the script and waits for a message of some kind, or a delay
			if (Facebook_UpdateLogin() ~= 0) then
				break;
			end
		end
		
		Facebook_StopLogin();

		PopModal(id);
		if (Facebook_IsLoggedIn()) then
			return true;
		else
			Facebook_LogoutCurrentUser();
			return false;
		end
	end	
end

------------------------------------------------------------------
--- helper for facebook_getstream: add all source pairs to target
------------------------------------------------------------------
function facebook_combine_table(source, target)
	if (source ~= nil) then
		for key,pair in pairs(source) do
			target[key] = pair;
		end
	end
end

---------------------------------------------------------------------------------
--- Combine commondefault, gamedefault, commonstream, gamestream, and overrides
---------------------------------------------------------------------------------
function facebook_getstream(stream, overrides)
	local result = {};
	
	-- first put in all the common-default values
	facebook_combine_table(facebookstreams_common['default'], result);
	
	-- first put in all the game-default values
	facebook_combine_table(facebookstreams['default'], result);

	-- Next put in overrides from common-stream file
	facebook_combine_table(facebookstreams_common[stream], result);

	-- Next put in overrides from game-stream file
	facebook_combine_table(facebookstreams[stream], result);
	
	-- Next put in overrides from function call
	facebook_combine_table(overrides, result);
	
	return result;
end

-------------------------------------------------------------------------------------------------
--- Put up a results dialog [hopefully 'Your X was posted.'] with a 'remain logged in' checkbox
-------------------------------------------------------------------------------------------------
function facebook_results_dialog(body_message, title_message)
	return DisplayDialog 
	{
	   "facebook/common/dlg_posted.lua",
	   facebook_ok_title = title_message,
	   facebook_ok_body = body_message,
	};
end;

-------------------------------------------------------------------------------------------------
--- Put up a dialog [ often an error ] with an OK button only
-------------------------------------------------------------------------------------------------
function facebook_ok_dialog(body_message, title_message)
	return DisplayDialog 
	{
	   "facebook/common/dlg_ok.lua",
	   facebook_ok_title = title_message,
	   facebook_ok_body = body_message,
	};
end;

-------------------------------------------------------------------------------------------------
--- Put up a 'we need permission dialog' with a yes/no choice.
-------------------------------------------------------------------------------------------------
function facebook_get_permission()
	return DisplayDialog 
	{
	   "facebook/common/dlg_yesno.lua",
	   facebook_yesno_body = 'facebook_msg_needpermissions_body',
	   facebook_yesno_title = 'facebook_msg_needpermissions_title',
	   facebook_yes = 'facebook_btn_yes',
	   facebook_no = 'facebook_btn_no',
	};
end;

-------------------------------------------------------------------------------------------------
--- Post a Facebook stream entry (either news or photo).
---  parameters
---		postfunction: either Facebook_PostNewsStream or Facebook_PostPhoto [a function that returns a requestId]
---		usermessage: passed to postfunction [userMessage]
---		stream: passed to postfunction [stream]
---	    forcelogin: do we have to run the FB login UI?
---		stringid_success_dlg_body: a stringId for successfull post body ['Your photo was posted to your album']
---		stringid_success_dlg_title: a stringId for successfull post title ['Successfully posted']
-------------------------------------------------------------------------------------------------
function facebook_dopost(postfunction, usermessage, stream, forcelogin, stringid_success_dlg_body, stringid_success_dlg_title)


	local was_in = Facebook_IsLoggedIn();
	
	if not was_in then
		FB_SetState("++FBIGConnectTry");
	end;
	
	if (facebook_login(forcelogin)) then
		
		local is_in = Facebook_IsLoggedIn();
		if (is_in and not was_in) then
			FB_SetState("++FBIGConnectLogin");
		end;
		
		-- Create post request
		local requestid = postfunction(usermessage, stream);
		
		-- See what happens when we upload it
		result = DisplayDialog 
		{
	       "facebook/common/dlg_connecting.lua",
	       requestid = requestid
	    };
	    
	    if (result == "facebook_success") then
	    
			if stream.metrics_on_success then
				FB_SetState("++" .. tostring(stream.metrics_on_success));
			end;
			FB_SetState("++FBPostSubmitted");
			
			facebook_results_dialog(stringid_success_dlg_body, stringid_success_dlg_title);
			return true;
		elseif (result == "facebook_networkerror") then
			facebook_results_dialog('facebook_msg_error_general_body', 'facebook_msg_error_general_title');
			return false;
		else
			-- Parse out the error code from facebook_protocolerror:<errorCode>
			local colon = string.find(result, ':');
			if (colon == nil) then
				facebook_results_dialog('facebook_msg_error_general_body', 'facebook_msg_error_general_title');
				return false;
			else
				
				local lastError = tonumber(string.sub(result, colon+1));
				if (lastError == kFacebookError_NotLoggedIn) then
					return facebook_dopost(postfunction, usermessage, stream, true, stringid_success_dlg_body, stringid_success_dlg_title);
				elseif (lastError ==  kFacebookError_InvalidPermissions) then
					local permresult = facebook_get_permission();
					if (permresult == 'yes') then
						return facebook_dopost(postfunction, usermessage, stream, true, stringid_success_dlg_body, stringid_success_dlg_title);
					else
						return false;
					end
				elseif (lastError == kFacebookError_FeedLimitReached) then
					facebook_results_dialog('facebook_msg_streamlimitreached_body', 'facebook_msg_streamlimitreached_title');
					return false;
				else
					facebook_results_dialog('facebook_msg_error_general_body', 'facebook_msg_error_general_title');
					return false;
				end
			end
		end
	else
		return false;
	end
end;

-------------------------------------------------------------------------------------------------
--- Post a Facebook stream NEWS entry
-------------------------------------------------------------------------------------------------
function facebook_dopoststream(usermessage, stream, forcelogin)
	return facebook_dopost(Facebook_PostNewsStream, usermessage, stream, forcelogin, 'facebook_msg_streamposted_body', 'facebook_msg_streamposted_title');
end;

-------------------------------------------------------------------------------------------------
--- Post a Facebook stream PHOTO entry
-------------------------------------------------------------------------------------------------
function facebook_dopostphoto(usermessage, stream, forcelogin)
	return facebook_dopost(Facebook_PostPhoto, usermessage, stream, forcelogin, 'facebook_msg_photoposted_body', 'facebook_msg_photoposted_title');
end;

function facebook_getfriendlist(forcelogin)
	
	local returnvalue = {false, nil};
	if (facebook_login(forcelogin)) then
		local requestid = Facebook_FriendList({'uid', 'name', 'pic_small'});
		returnvalue[2] = requestid;
		result = DisplayDialog {
	       "facebook/common/dlg_connecting.lua",
	       requestid = requestid,
	       removerequest = false
	    };
	    
	    if (result == "facebook_success") then
			returnvalue = {true, requestid};
		elseif (result == "facebook_networkerror") then
			facebook_results_dialog('facebook_msg_error_general_body', 'facebook_msg_error_general_title');
			Facebook_RemoveRequest(requestid);
		else
			Facebook_RemoveRequest(requestid);
			-- Parse out the error code from facebook_protocolerror:<errorCode>
			local colon = string.find(result, ':');
			if (colon == nil) then
				facebook_results_dialog('facebook_msg_error_general_body', 'facebook_msg_error_general_title');
			else
				
				local lastError = tonumber(string.sub(result, colon+1));
				if (lastError == kFacebookError_NotLoggedIn) then
					returnvalue = facebook_getfriendlist(true);
				elseif (lastError ==  kFacebookError_InvalidPermissions) then
					local permresult = facebook_get_permission();
					if (permresult == 'yes') then
						returnvalue = facebook_getfriendlist(true);
					end
				else
					facebook_results_dialog('facebook_msg_error_general_body', 'facebook_msg_error_general_title');
				end
			end
		end
	end

	return returnvalue;
end

----- 
-- Wrapper functions for posting and causing posts
-----


-----------------------------------------------------------------------------------------
-- This is done as an injected/delayed event; it's an ingame popup, so it pauses things.
-----------------------------------------------------------------------------------------
function DoFacebookPost(stream, overrides)
	DebugOut("DoFacebookPost("..tostring(stream)..")");
	return
		function()
			if Facebook_IsLoggedIn() then
				if (Facebook_Callback_EnterPause) then Facebook_Callback_EnterPause(); end;
				Facebook_PostStreamUI(stream, overrides);
				if (Facebook_Callback_ExitPause) then Facebook_Callback_ExitPause(); end;
			end;
		end
end

function InjectFacebookPost(stream, overrides)
	if (table.getn(gCommandQueue) == 0) then
		table.insert(gCommandQueue, DoFacebookPost(stream, overrides));
	end
end

-----------------------------------------------------------------------------------------
-- Willows does this stuff.
-----------------------------------------------------------------------------------------
function DelayedEvent(endtime, theFunction)
	if (IsModalWindowOpen('thegame')) then
		if (GetModalWindowTime('thegame') > endtime) then
			theFunction();
		else
			if (table.getn(gCommandQueue) == 0) then
				table.insert(gCommandQueue, DoDelayedEvent(endtime, theFunction));
			end	
		end
	end
end

function DoDelayedEvent(endTime, theFunction)
	return function()
		DelayedEvent(endTime, theFunction);
	end
end

function InjectDelayedEvent(endTime, theFunction)
	if (table.getn(gCommandQueue) == 0) then
		table.insert(gCommandQueue, DoDelayedEvent(endTime, theFunction));
	end
end;


function Facebook_CreateShareButton(style)
	if IsFacebookEnabled() then
	
		if style == nil then
			style = facebook_ingame_style;
		else 
			style.parent = facebook_ingame_style;
		end;

		local graphics = {'facebook/common/facebook_connect_medium'};
		if style.graphics then
			graphics = style.graphics;
		end;
		
		return Group
			{
				SetStyle(style),
				FBButton
				{
					name = 'fb_connect_post',
					graphics = graphics,
					command = 
						function()
							FB_SetState("FBTriedIt", "1");
							if not Facebook_IsLoggedIn() then
								-- FB_SetState("++FBIGConnectTry");
							end;
							DoModal('facebook/common/dlg_share_menu.lua');
						end
				},
			};
	else
		return Group {};
	end;
end;

function FB_CanDoRandomPost()
	return true;
end;

function Facebook_SetScoreData(streamname, overrides)
	DebugOut("Facebook_SetScoreData(" .. tostring(streamname) .. ", " .. tostring(overrides) .. ")" );
	FB_gScoreOverrides = overrides;
end;

function FB_CanDoScorePost()
	return FB_gScoreOverrides ~= nil;
end;

function FB_CanDoScreenshotPost()
	return CreateScreenshot ~= nil;
end;

function FB_CanDoPhotoPost()
	return CreateFacebookImage  ~= nil;
end;
