		var jQueryScriptOutputted 	= 	false;
		function initJQuery() {
			
			//if the jQuery object isn't available
			if (typeof(jQuery) == 'undefined') {
			
			
				if (! jQueryScriptOutputted) {
					//only output the script once..
					jQueryScriptOutputted = true;
					
					//output the script (load it from google api)
					document.write("<scr" + "ipt type=\"text/javascript\" src=\"/js/jquery-1.3.2.min.js\"></scr" + "ipt>");
				}
				setTimeout("initJQuery()", 50);
			} else {
								
				$(function() {  
					//do anything that needs to be done on document.ready
				});
			}
					
		}
		
		initJQuery();

		//	System variables
		
		var	FaceBookStatus				= 	null;
		var	FBUserAccount				=	0;
		var	BrainDashUserID				=	0;
		var ThirdPartyID				=	1;
		var	AffiliateID					=	PHP_AffiliateID;
		var ThisPage					=	location.href;
		var	LastStreamText				=	"";
		
		//	User variables
		
		var	BrainDashUserSessionID		=	"";
		
		var	facebook_friends			=	"";
		var	first_name					= 	"";
		var	last_name					= 	"";
		var	username					=	"";
		// var	name						= 	"";
		var	timezone					= 	"";
		var	birthday_date				= 	"";
		var	sex							= 	"";

		var	current_location			= 	"";
		var	locale						=	"";
		var	profile_url					=	"";
		var	pic_small_with_logo			=	"";
		var	pic_square_with_logo		= 	"";
		
		var	ShowLogin					=	false;
		var	ShowLogout					=	false;

		var	UpdatedUserInfo				=	false;
		var	DoneFacebookInit			=	false;
		var	AmLoggedIn					=	false;
		var	proxied_email				=	"";
		var	email						=	"";
		var	NextStory					=	"";
		var	GlobalMessageArray			=	new Array;
		var	FBCookieName				=	"UpdateFacebookInfo";


		// To show the buttons you need to make sure that the page finished loading completely. If you don't do that
		// The styles specified in the DIV may actually "come in" after the the update has finished.
		
		$(document).ready(function(){
			
			// alert("Loaded!");
			var	SLT	=	"0";
			var SOT	=	"0";
			
			if (ShowLogin) {
				SLT		=	"1";
				$('.FBC_LoginButtonClass').show();
				$('.FacebookNotLoggedIn').hide();
			}
			else {
				$('.FBC_LoginButtonClass').hide();
				$('.FacebookNotLoggedIn').show();
			}

			if (ShowLogout) {
				SOT		=	"1";
				$('.FBC_LogoutButtonClass').show();
				$('.FacebookLoggedIn').hide();
			}
			else {
				$('.FBC_LogoutButtonClass').hide();
				$('.FacebookLoggedIn').show();
			}
			
			/*
			if (typeof(ShowHTMLComment) == 'undefined') {
				document.write("<scr" + "ipt type='text/javascript'>function ShowHTMLComment(){}</scr" + "ipt>");
			}
			*/
			
			// $('.username_1').text("here: " + SLT + " " + SOT);
			// alert("Ready");
    	});
		
		
		/*
		
			This happens when you first load a page. It checks to see if you are logged in to Facebook.
			FaceBook status will contain your settings.
			
		*/

		function ShowDebug (Text)
		{
			return;
			if (PHP_Staging == 0) {
				return;
			}
			
			alert(Text);
			
		}
										   
		$(document).ready(function(){
			FB_RequireFeatures(["Api"], function() { 
					
					// "reloadIfSessionStateChanged":true,
																								
					FB.Facebook.init(PHP_FaceBook_App_APIKey, '/xd_receiver.htm'	,{	"ifUserConnected":fbLoginUser, 
																						"ifUserNotConnected":fbLogoutUser
																						});                                
					FB.ensureInit(function() { 
						FB.Connect.get_status().waitUntilReady( function( status ) { 
						DoneFacebookInit	=	true;
						switch ( status ) { 
							case		FaceBookStatus 	= FB.ConnectState.connected:		ShowDebug("Status: Connected"); 	
																							//	if (PHP_Staging == 1) 	alert("Case Connected");
																							OnUserConnected();
																							break; 
	
							case		FaceBookStatus = FB.ConnectState.appNotAuthorized: 	ShowDebug("Status: appNotAuth"); 	
										
							case		FaceBookStatus = FB.ConnectState.userNotLoggedIn: 	ShowDebug("Status: not Logged in"); 	
																							// 	if (PHP_Staging == 1) 	alert("Case NOT Connected");
																							OnUserNotConnected();						
																							//alert("Not logged in");
																							break;
						} 
					});
				}); 		
					// FB.Facebook.apiClient.requireLogin();	//	Forces facebook connect on login
			});
		});
		
		function inviteConnectUsers() {
				FB.Connect.inviteConnectUsers();
		}
		
		function getLoggedInUser() {
				alert(FB.Connect.get_loggedInUser());
		}

		function FacebookConnect_OK()
		{
			FBUserAccount = FB.Connect.get_loggedInUser();
		}
		
		function FacebookConnect_Cancel()
		{
			// alert("cancel");
		}
		
		function FacebookConnect_Logout()
		{
			FB.Connect.logout(FacebookDoneLogout);
		}	
		
		function FacebookDoneLogout()
		{
			// alert("logged out");
		}	
		
		//	If you want to request the email permission:
		//	You have the configure the Facebook application -> connect -> Connect URL!!!
		
		function	RequestPermission(permission) 
		{
			FB.Facebook.apiClient.users_hasAppPermission(permission,
															function(result) {
																// prompt offline permission
																if (result == 0) {
																	// ReadUserInfo(1);
																	// render the permission dialog
																	FB.Connect.showPermissionDialog(permission,
																	function(result){
																		FBUserAccount = FB.Connect.get_loggedInUser();
																		ReadUserInfo(1,1);	//	Read this user again and update the record																
																		PermissionGranted = 1;
																		if (null == result) {
																			PermissionGranted = 0;
																		}
																		
																		if (result.indexOf(permission) < 0) {
																			PermissionGranted = 0;
																		}

																		WriteThirdPartyLog(4,PermissionGranted,"Grant Permission: " + permission)
																	}, true, null);
																} else {
																	// permission already granted.
																	// alert("Already Present");
																}
															});
		}
		
		function ReadApplicationFriends()
		{
			FB.Facebook.apiClient.friends_getAppUsers(function(FriendArray, exception){ 
				facebook_friends		=	"";
				if (FriendArray != null) {
					for ( var i=0, len=FriendArray.length; i<len; ++i ){
						 if (i>0) facebook_friends 	+= ",";
						 facebook_friends		  	+= FriendArray[i];
					}					
				}
			}); 
		}
		
		//	This function reads the necesary data from facebook and sets global
		//	variables.
		
		function ReadFriends(FriendString)
		{
				FB.Facebook.apiClient.users_getInfo(FriendString,
													'first_name,last_name,name,profile_url,pic_small_with_logo,pic_small_with_logo',
													function(UserInfo, exception){
														ReadUserInfo(1);
														if (UserInfo.length > 0) {
															return UserInfo;
														}
														else {
															return NULL;
														}
													});			
		}
		
		function ReadUserInfo(UpdateUser,ForceUpdate)
		{
			
			if (ForceUpdate == undefined) {
				ForceUpdate = 0;
			}
			
			ShowDebug("Read User Info"); 	
			FB.Facebook.apiClient.users_getInfo(FBUserAccount,
												'first_name,last_name,name,timezone,birthday_date,sex,current_location,' +
												'locale,profile_url,pic_small_with_logo,pic_square_with_logo,email,proxied_email ',
												function(UserInfo, exception){
			try {
	
					if (UserInfo[0].first_name 		!= undefined) 	first_name				= UserInfo[0].first_name;
					if (UserInfo[0].last_name 		!= undefined) 	last_name				= UserInfo[0].last_name;
					if (UserInfo[0].name 			!= undefined) 	username				= UserInfo[0].name;					
					if (UserInfo[0].timezone 		!= undefined) 	timezone				= UserInfo[0].timezone;
					if (UserInfo[0].birthday_date 	!= undefined) 	{
						birthday_date			= UserInfo[0].birthday_date;
						if (birthday_date.length==10) {
							var	ReformatDate		=	"";
							ReformatDate			+=	birthday_date.substring(6,10);
							ReformatDate			+=	birthday_date.substring(0,2);
							ReformatDate			+=	birthday_date.substring(3,5);
							birthday_date			=	ReformatDate;						
						}
						else {
							birthday_date			=	"";
						}
					}
										
					if (UserInfo[0].sex != undefined) {
						sex						= UserInfo[0].sex;
						if (sex.length > 0) {
							sex					=	sex.toUpperCase().substr(0,1);
						}
					}
					
					if (UserInfo[0].proxied_email 	!= undefined) 	proxied_email			= UserInfo[0].proxied_email;
					if (UserInfo[0].email 			!= undefined) 	email					= UserInfo[0].email;

					if (email.substring(0,3) == "apps ") 			email			=	email.substring(4);
					if (proxied_email.substring(0,3) == "apps ") 	proxied_email	=	proxied_email.substring(4);
					
					// current_location		= UserInfo[0].current_location;
					if (UserInfo[0].locale 			!= undefined) 	locale					= UserInfo[0].locale;
					if (UserInfo[0].profile_url		!= undefined) 	profile_url				= UserInfo[0].profile_url;
	
					// var currentlocationcountry	= UserInfo[0].currentlocation.country;
	
					if (UserInfo[0].pic_small_with_logo 			!= undefined) 	pic_small_with_logo		= UserInfo[0].pic_small_with_logo;
					if (UserInfo[0].firstNpic_square_with_logoame 	!= undefined) 	pic_square_with_logo	= UserInfo[0].pic_square_with_logo;
					
					FB.Facebook.apiClient.friends_get(null, function(FriendArray, exception){ 
						facebook_friends		=	"";
						if (FriendArray != null) {						
							for ( var i=0, len=FriendArray.length; i<len; ++i ){
								 if (i>0) facebook_friends 	+= ",";
								 facebook_friends		  	+= FriendArray[i];
							}
						}					
						UpdatedUserInfo			=	false;
						if (UpdateUser == 1) {
							UpdateUserInfo(ForceUpdate);
						}			
					}); 
					/*
					
					//	If you do it here, it happens before the friends are set					
					if (UpdateUser == 1) {
						UpdateUserInfo();
					}			
					*/							
				}
				catch (e) {
					return;
				};
			});
			
		}

		function fbLoginUser()
		{
			// if (PHP_Staging == 1) alert("fbLoginuser");
			
			if (PHP_UseFacebookConnect == 1) {
				OnUserConnected();
				ReadUserInfo(0);
			}
			return;
		}
		
		function	RequestEmailPermision()
		{
			var	RequestEmailCount		=	parseInt(readCookie("AskForEmailCount"));

			if (PHP_Staging == 1) {
				RequestEmailCount		=	1;
			}
			
			if (RequestEmailCount > 0) {
				RequestEmailCount--;
				setCookie("AskForEmailCount",RequestEmailCount);
				// RequestPermission("email");
			}
			return;
		}
		
		function OnUserConnected()
		{
			/*
			if (Staging == 1) {
				alert("OnUserConnected");
			}
			*/
			
			// if (PHP_Staging == 1) alert("onUserCorrected");
			if (PHP_UseFacebookConnect == 1) {
				var	RequestEmailCount	=	parseInt(readCookie("AskForEmailCount"));
				if (PHP_Staging == 1) {
					RequestEmailCount 	=	1;
				}
				if (RequestEmailCount > 0) {
					var	TimeOut	=	15000;
					if (PHP_Staging == 1) {
						TimeOut	=	1000;
					}
					setTimeout('RequestEmailPermision()', 15000);	//	There's loads of page refreshing going on in 
																	//	FBC so if you do it straight away it looks pretty bad
				}
				
				AmLoggedIn			= true;
				FBUserAccount 		= FB.Connect.get_loggedInUser();
				ShowDebug("On User Connected"); 	
				if (!UpdatedUserInfo) {
					ReadUserInfo(1);	//	When read, it will update the UserInfo as well
				}
				
				$('.FBConnectButton_Text').text("Logout");
				
				$('.FBC_LoginButtonClass').hide();
				$('.FBC_LogoutButtonClass').show();
				$('.FacebookNotLoggedIn').hide();
				$('.FacebookLoggedIn').show();
				
				ShowLogin	=	false;
				ShowLogout	=	true;
			}
			return;
		}
		
		function fbLogoutUser()
		{
			// if (PHP_Staging == 1) alert("fbLogoutUser");
			if (PHP_UseFacebookConnect == 1) {
				OnUserNotConnected();
				/*
				Don't log out if you are not logged in as there are 2 different ways that you can get here (1) You get to the BrainDash site and
				you are not logged in to FaceBook but you ARE logged in to BrainDash. If we log you straight out that becomes a vicious circle or (2)
				You have been logged in (BD & Facebook) and you press the logout button.
				*/
				if (AmLoggedIn == true) {	
					setCookie(FBCookieName,"0");
					JSLogout(PHP_LogoutPage);
				}
			}
			return;
		}
		
		function OnUserNotConnected()
		{
			// if (PHP_Staging == 1) alert("OnUserNotConnected");
			if (PHP_UseFacebookConnect == 1) {
				UpdatedUserInfo	=	false;
				ShowDebug("On User NOT Connected"); 	
				$('.FBC_LoginButtonClass').show();
				$('.FBC_LogoutButtonClass').hide();
				$('.FacebookLoggedIn').hide();
				$('.FacebookNotLoggedIn').show();
				ShowLogin		=	true;
				ShowLogout		=	false;
				
				var	ButtonText	=	"Register";
				if (PHP_HasFacebookAccount == 1) {	//	We know you have a FB account
					ButtonText	=	"Login";
				}
				else {	// We don't know you have a facebook account
					if (PHP_UserID > 0) {			//	We know you have a User Account
						ButtonText	=	"Connect";
					}
				}
				
				$('.FBConnectButton_Text').text(ButtonText);
				
				// ShowFooterComment("User logged out: "+ FBUserAccount);
			}
			return;
		}
				
		function BrainDashApiCall(WebServer,WebService,ParamString,CallBack)
		{
			var	TheURL		=	PHP_BrainDashJSONWrapper;
			TheURL			+=	"WebService=" 	+ WebService + "&";
			TheURL			+=	"WebServer=" 	+ WebServer + "&";
			TheURL			+=	ParamString;
		
			TheURL		=	TheURL + "jsoncallback=?";		
			// if (PHP_Staging == 1) alert("BrainDashApiCall " + TheURL );

			$.getJSON(TheURL, CallBack);	
		}

		function	UpdateUserInfo(ForceUpdate)
		{
			
			if (ForceUpdate == undefined) {
				ForceUpdate	= 0;
			}
			
			if (ForceUpdate == 0) {
				if (UpdatedUserInfo == true) {	// Once per page only...
					return;
				}
	
				//	This logic prevents us updating our user account every page
				//	But only if you are logged in. If not, we'll continue.
				
				if (PHP_UserSessionID.length > 0) {			
					var	DidFacebookUpdate	=	parseInt(readCookie(FBCookieName));
					// if ((DidFacebookUpdate == 1) && (PHP_Staging == 0)) {
					if (DidFacebookUpdate == 1) {
						return;
					}
				}
			}
			setCookie(FBCookieName,"1");
			
			ShowDebug("Update User Info"); 	
			
			//	ShowFooterComment("Update Account: "+ FBUserAccount);
			
			UpdatedUserInfo			=	true;
			ParamString				=	"";
			
			if (AffiliateID == 0) {
				AffiliateID			=	1;
			}
			
			ParamString				+=	"AccountID=" 			+ escape(FBUserAccount) + "&";
			ParamString				+=	"ThirdPartyID=" 		+ escape(ThirdPartyID) + "&";
			ParamString				+=	"AffiliateID=" 			+ escape(AffiliateID) + "&";
			ParamString				+=	"CreateIfRequired="		+ "1&";
			ParamString				+=	"UpdateSession="		+ "1&";
			
			if (email.length > 0) {
				email				=	email.replace("+","%2B");
				ParamString		+=	"EmailAddress="		+ 	escape(email)			+ "&";
			}
			else {
				proxied_email		=	proxied_email.replace("+","%2B");
				if (proxied_email.length > 0) 	ParamString		+=	"EmailAddress="		+ 	escape(proxied_email)			+ "&";
			}
			
			if (last_name.length > 0) 			ParamString		+=	"LastName="			+ 	escape(last_name)				+ "&";
			if (first_name.length > 0) 			ParamString		+=	"FirstName="		+ 	escape(first_name)				+ "&";
			if (username.length > 0) 			ParamString		+=	"DisplayName="		+ 	escape(username)					+ "&";
			if (parseInt(timezone) > 0) 		ParamString		+=	"TimeZoneName="		+ 	escape(timezone)				+ "&";
			if (birthday_date.length > 0) 		ParamString		+=	"DateOfBirth="		+ 	escape(birthday_date)			+ "&";
			if (sex.length == 1) 				ParamString		+=	"Gender="			+ 	escape(sex)						+ "&";
			if (current_location.length > 0) 	ParamString		+=	"CurentLoccation="	+ 	escape(current_location)		+ "&";
			if (locale.length > 0) 				ParamString		+=	"CountryISACode="	+ 	escape(locale)					+ "&";
			if (profile_url.length > 0) 		ParamString		+=	"ProfileURL="		+ 	escape(profile_url)				+ "&";
			if (pic_small_with_logo.length > 0) ParamString		+=	"AvatarURL="		+ 	escape(pic_small_with_logo)		+ "&";
			if (facebook_friends.length > 0) 	ParamString		+=	"Friends="			+ 	escape(facebook_friends)		+ "&";
			
			if (PHP_ClientUniqueID.length > 0) {
				ParamString		+=	"UserUniqueID="			+ 	PHP_ClientUniqueID		+ "&";
			}

			// if (PHP_Staging == 1) alert("UpdateUserInfo " + ParamString );
			BrainDashApiCall		("user/UserServer.php","user.find_third_party_account",ParamString,Proc_UpdatedUserInfo);
		}	

		/*
		The way this works is a bit rediculous but I believe that our BrainDash json calls actually interfear with
		what Facebook is doing. If you try to specify a call to FaceBook from within a json_call back function the
		facebox box you are shown is actually empty.
		
		So the way we get around this is, we call our function and if we find something we push it on an array stack
		GlobalMessageArray. Whe then have a timed function which check the size of the array and if there is something
		on it, it display it. Mad but true
		
		*/
			
		function	ReadUserMessages(ServeLocationID)
		{
		
			
			if (PHP_ClientUniqueID.length == 0) {
				return;
			}
			ParamString				=	"";
			ParamString				+=	"UserUniqueID="			+ 	PHP_ClientUniqueID		+ "&";
			ParamString				+=	"ServeLocation=" 		+ 	ServeLocationID + "&";
			ParamString				+=	"UserLoggedIn=" 		+ 	0 + "&";
			BrainDashApiCall		("system/SystemServer.php","system.get_system_message",ParamString,function(json_data){
					Status		=	json_data['Status'];
					if (Status == "ERROR") {
						// ShowFooterComment("Error retrieving messages",false);
						DisplayErrors(json_data);
						return;
					}
					
					try {
						var	MessageArray		=	json_data['MessageArray'];
						var	DefaultMessage		=	parseInt(MessageArray['DefaultMessage']);
						if (DefaultMessage != 0) {
							return;
						}			
						GlobalMessageArray.push(MessageArray);			
					}
					catch (e) {
						return;
					}
			});
			return;
			
		}
		
		// setTimeout("CheckStory()", 100);
		
		function CheckStory()
		{
			if (GlobalMessageArray.length > 0) {
				var MessageArray	=	GlobalMessageArray.pop();
				var	Message				=	MessageArray['Message'];
				var CompanyURL			=	MessageArray['CompanyURL'];
				if (MessageArray['AwardInfo'] != undefined) {
					var	AwardInfo			=	MessageArray['AwardInfo'];
					var	Image_Icon_Path		=	AwardInfo['Image_Icon_Path'];
					var	Image_No_Icon_Path	=	AwardInfo['Image_No_Icon_Path'];
					var	Image_Path			=	AwardInfo['Image_Path'];
					var	Image_No_Path		=	AwardInfo['Image_No_Path'];							
				}
				// PostStory('','','');
				PublishFacebookFeed(Message,Message,Image_Icon_Path,CompanyURL,Caption);
				//NextStory	=	"";
			}
			setTimeout("CheckStory()", 100);
		}
		
		
		function 	PublishFacebookFeed(Text,StreamText,ImageURL,TargetURL,Caption,TargetFacebookID) {
			

			/* 
			
			There are 2 models here, the first forces you to use FBConnect so we know who you are and 
			which account you are associated with. The second (after the return statement) allows you to share
			comments with out chat. At the moment it works which way's used depends on if you use FBC. If you do,
			even sharing a commment will force you to connect. If not, you can just publish your story.
			
			*/
			/*			
			try	{
				$.facebox.close();	
			}
			catch(e){};
			*/
			
			var	target_id	=	null;
			var	EventLabel	=	"Publish My Wall";
			if ((TargetFacebookID != undefined) && (TargetFacebookID.length > 0)) {
				EventLabel	=	"Publish Friends Wall";
				target_id	=	TargetFacebookID;
			}
			
			TrackGoogleEvent("Facebook",EventLabel,Text);
			
			if (ImageURL == undefined) {
				ImageURL = "";
			}
			
			if (TargetURL == undefined) {
				TargetURL = "";
			}
			
			if (ImageURL.indexOf("http") < 0) {
				ImageURL = "";
			}
			
			if (TargetURL.indexOf("http") < 0) {
				TargetURL = "";
			}
			
			ImageURL	=	CleanURL(ImageURL);
			TargetURL	=	CleanURL(TargetURL);
			
			if ((PHP_UseFacebookConnect != undefined) && (PHP_UseFacebookConnect == 1)) {
				
				LastStreamText	=	Text;
				
				FB_RequireFeatures(["Connect"], function() {
					FB.Facebook.init(PHP_FaceBook_App_APIKey, '/xd_receiver.htm');
					FB.ensureInit(function() {
						FB.Connect.requireSession(function () {
													ReadUserInfo(1);	//	Read and update the user info
													if (
														(TargetURL != undefined) && 
														(ImageURL != undefined) && 
														(ImageURL.length > 0) && 
														(TargetURL.length > 0) )
													{
													
														var attachment = {
															// 'name': 'Brain Power!',
															'href': 		TargetURL, 
															'caption': 		Caption,
															'description': 	StreamText,
															"media": [{ "type": "image", 
																		"src": 	ImageURL, 
																		"href": TargetURL
																	}]
														};
														FB.Connect.streamPublish(Text, attachment,null,target_id,null,publish_stream_callback);
													}
													else {
														FB.Connect.streamPublish(Text, null,null,target_id,null,publish_stream_callback);
													}
												  },
												  function () {
												  },
												  true);
					});
				});
			
			}
			else { // No force connect
			
				FB_RequireFeatures(["Connect"], function() {
	
					FB.Facebook.init(PHP_FaceBook_App_APIKey, '/xd_receiver.htm');
	
					FB.ensureInit(function() {
	
					// ShowDebug("Publish Message: " + Text); 	
					
					if ((ImageURL.length > 0) && (TargetURL.length > 0) && (TargetURL != undefined) && (ImageURL != undefined)) {
					
						var attachment = {
							// 'name': 'Brain Power!',
							'href': 		TargetURL, 
							'caption': 		Caption,
							'description': 	StreamText,
							"media": [{ "type": "image", 
										"src": 	ImageURL, 
										"href": TargetURL
									}]
						};
						/*
						var attachment = {'media': [{'type':'image',
													 'src':ImageURL,
													 'href':TargetURL}]};
						*/

						//	Graham,BrainDash: 754803622,1153059105
						//  Params: UserMessage, Attachement, Action Links, Targetid, UserMessagePrompt,Callback,auto_publish,actor_id
						
						FB.Connect.streamPublish(Text, attachment,null,target_id,null,publish_stream_callback);
					}
					else {
						FB.Connect.streamPublish(Text, null,null,target_id,null,publish_stream_callback);
					}
					});
				});
				
			}	//	End else no Force Connect
			
			function publish_stream_callback(post_id, exception) {
			
				// RequestPermission("publish_stream");	//	Try to gain permissions to do this automatically next time
			
				if (LastStreamText.length == 0) {
					return;
				}
				var	PostOK = 1;
				if (post_id == "null") {
					PostOK = 0;
				}
				
				WriteThirdPartyLog(1,PostOK,LastStreamText);
				LastStreamText = "";				
			}	
		}
		
		/*
			Param1:	1 = Post message
					2 = Connect
					3 = Invite Friends
					4 = Grant Permissions
					
			Param 2: 1 = OK 0 = reject
		*/
		
		function	WriteThirdPartyLog(Param1,Param2,Message)
		{
			ParamString				=	"";
			ParamString				+=	"ThirdPartyID="			+ 	"1&";	//	Facebook
			ParamString				+=	"AccountID="			+ 	escape(FBUserAccount) + "&";
			ParamString				+=	"Param1=" 				+ 	escape(Param1) + "&";
			ParamString				+=	"Param2=" 				+ 	escape(Param2) + "&";
			ParamString				+=	"Message=" 				+ 	escape(Message) + "&";
			BrainDashApiCall		("system/SystemServer.php","system.write_third_party_log",ParamString,function(json_data){
																Status		=	json_data['Status'];
												});			
		}
		
		function	Proc_UpdatedUserInfo(json_data){
			
			// if (PHP_Staging == 1) alert("Proc_UpdatedUserInfo " + json_data['Status'] );

			Status		=	json_data['Status'];
			if (Status == "ERROR") {
				// ShowFooterComment("Update User Error: " + FBUserAccount,true);
				DisplayErrors(json_data);
				return;
			}		
			try {
				
				BrainDashUserID				=	parseInt(json_data['UserID']);				
				NewUser						=	parseInt(json_data['NewUser']);				
				UserSessionID				=	json_data['UserSessionID'];
				UniqueID					=	json_data['UniqueID'];
				var	UserWarning				=	json_data['UserWarning'];

				// alert("NewUser: " + NewUser);
				
				if (NewUser == 1) {
					TrackGoogleEvent("Register Player","Register with Facebook Connect -  " + PHP_AffiliateName);
				}
				
				if (UserWarning.length > 0) {
					// alert(UserWarning);
				}
				
				// AffiliateID					=	json_data['AffiliateID'];
				
				//	ShowFooterComment("Update User OK: " + FBUserAccount,true);
				
				var	LogoutPos = ThisPage.toLowerCase().indexOf("logout=y");
				if (LogoutPos < 0) {
					LogoutPos = ThisPage.toLowerCase().indexOf("logout.php");
				}
				
				if (LogoutPos < 0) { // If are loging out from BrainDash - don't log you back in again.
					// if (PHP_Staging == 1) alert("Before JSLogin: " + UniqueID + " - " + UserSessionID + " - " + AffiliateID + " - " + ThisPage);
					JSLogin(UniqueID,UserSessionID,AffiliateID,ThisPage);
				}
				// -- Don't JSLogin(UniqueID,UserSessionID,AffiliateID,"/index.php");
								
			} catch (e) {};
			return;
		}		
		
		function DisplayErrors(json_data)
		{
			if (PHP_Staging == 0) {
				return;
			}
			
			var	ErrorCount	=	json_data['ErrorCount'];
			var ShowError	=	"";
			for (EP=1;EP<=ErrorCount;EP++) {
				var	ThisError	=	json_data['Errors']['Error_' + EP];
				ShowError +=	ThisError['ErrorMessage'] + " (" + ThisError['ErrorCode'] + ")" ;
			}
			
			if (ShowError.length == 0) {
				ShowError		=	"No Errors Found";
			}
			
			alert("XML Errors: " + ShowError,1);
			return;
			
		}
	
		function	AddParameter(InString,ParamName,ParamValue)
		{
			InString	+=	ParamName + "=" + escape(ParamValue);
			return InString;
		}
		
		function	PublishFacebookNotification(Text) {
			if (FBUserAccount.length > 0) {
				FB.ApiClient.notifications_send(FBUserAccount,Text);
			}
		}

		function GetNonAppUsers()
		{
			var FQL	=	"SELECT uid, pic_square,pic_square_with_logo, name " +
								" FROM user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1='" + FBUserAccount + "') AND is_app_user = 0";
			FB_RequireFeatures(["Connect"], function() {
				FB.Facebook.init(PHP_FaceBook_App_APIKey, '/xd_receiver.htm');
				FB.ensureInit(function() {
					FB.Connect.requireSession(function () {
												FB.Facebook.apiClient.fql_query(FQL,function(FriendArray, exception){
													return	FriendArray; 
												});
											  },
											  function () {
											  },
											  true);
				});
			});			
		}
		
		function InviteFacebookFriends(HideFaceBoxID)
		{
			var	Param	=	"";
			Param		+=	"AccountID=" + 		escape(FBUserAccount) + "&";
			Param		+=	"CompanyName=" + 	escape(PHP_CompanyName) + "&";
			Param		+=	"CompanyURL=" + 	escape(PHP_CompanyURLPlain) + "&";

			Param		+=	"Staging=" + 		escape(PHP_Staging) + "&";			
			Param		+=	"Key=" + 			escape(PHP_FaceBook_App_APIKey) + "&";
			Param		+=	"Canvas=" + 		escape(PHP_FaceBook_Canvas_Page) + "&";
			
			if (HideFaceBoxID != undefined) {
				$.facebox.close()
			}
			FB_RequireFeatures(["Connect"], function() {
				FB.Facebook.init(PHP_FaceBook_App_APIKey, '/xd_receiver.htm');
				FB.ensureInit(function() {
					FB.Connect.requireSession(function () {
												FB.Facebook.apiClient.friends_getAppUsers(function(FriendArray, exception){ 
													facebook_friends		=	"";
													if (FriendArray != null) {													
														for ( var i=0, len=FriendArray.length; i<len; ++i ){
															 if (i>0) facebook_friends 	+= ",";
															 facebook_friends		  	+= FriendArray[i];
														}
													}					
													if (PHP_Staging == 0) {
														Param		+=	"PlayingFriends=" + 		escape(facebook_friends) + "&";
													}
													PopUpScrollBarSize("/includes/facebook_invite.php?" + Param, 'InviteFriends', 775, 700);
												});
												// PopUpScrollBarSize("/includes/facebook_invite.php?" + Param, 'Invite Friends', 775, 700);
											  },
											  function () {
											  },
											  true);
				});
			});			
		}		
		
		/*
		Some of our callers seem to use the wrong URL format and use achors instead. This function attempts to clean up any URL given to it.
		
		*/
		
		function	FacebookLogin()
		{
			FB.Connect.requireSession(FacebookConnect_OK,FacebookConnect_Cancel,true); return false;
		}
		
		
		function CleanURL(URL)
		{
			var myPos	=	URL.toUpperCase().indexOf("<A");
			
			if (myPos >= 0) {
				
				myPos	=	URL.toUpperCase().indexOf("HREF=");
				URL		=	URL.replace("\"","'");
				if (myPos < 0) {
					return "";
				}
				
				var	FirstQuote	=	URL.indexOf("'",myPos);
				if (FirstQuote < 0) {
					return;
				}
				
				URL	=	URL.substr(FirstQuote+1);
				FirstQuote	=	URL.indexOf("'");
				if (FirstQuote < 0) {
					return;
				}
				
				URL	=	URL.substr(0,FirstQuote);
				return URL;						
			}
			
			return URL;
		}
