var userID;
var userInfo;
var friendInfo;
var api_key = "fb343f23f22e90b7fcf690585f140e53";
var template_bundle_id = "38054272953"; 			//http://developers.facebook.com/tools.php?feed 
  	
function loginConnect(){
	FB.Connect.requireSession();
	checkConnect();
}
function logoutConnect(){
	FB.Connect.logout();
}

function checkConnect(){
	FB_RequireFeatures(["XFBML"], function()
	{
	  FB.Facebook.init(api_key, "xd_receiver.htm");
	  FB.Facebook.get_sessionState().waitUntilReady(function()
	  {
		userID = FB.Facebook.apiClient.get_session().uid;
		
		//window.alert(userID);
		
		if (!userID) {
			statusMsg("NOT LOGGED IN!");
		}else{      
			getProfile();
		}
	  });
	});  	  	
}

function getProfile(){
	//Get the user's info	
	statusMsg("Loading profile..." + userID);
		
	FB.Facebook.apiClient.users_getInfo(userID,'first_name,name,pic_square,is_app_user',function(result, ex) {
		userInfo = result.slice();
		sendProfile();
		getFriends();
	});     	
}

function getFriends(){
	statusMsg("Loading friends...");
	
	//Get the friend's and their info        
	FB.Facebook.apiClient.friends_get(null, function(result, ex) {
		
		
		var ids = result.slice();
		
		FB.Facebook.apiClient.users_getInfo(ids,'first_name,name,pic_square,is_app_user',function(result, ex) {
			friendInfo = result.slice();
			sendFriends();
		});
	});    	
}

function sendProfile(){   
	//writeProfile();
	var flash = (navigator.appName.indexOf ("Microsoft") !=-1)?window["container"]:document["container"];
	flash.returnProfile(userInfo);		
	statusMsg("Finished loading profile!");
}

function sendFriends(){
	//writeFriends();
	var flash = (navigator.appName.indexOf ("Microsoft") !=-1)?window["container"]:document["container"];
	flash.returnFriends(friendInfo,friendInfo.length); 	
	statusMsg("Finished loading friends!");
}

function statusMsg(msgIn){
	var fb_status = document.getElementById('fb_status');  	
	if (fb_status){
		fb_status.innerHTML += "<br />" + msgIn;
	}
}


function publishStory(posttitle,postbody,postlink,postimage) {
	//	To update a template_feed go to...
	//	http://developers.facebook.com/tools.php?feed 

	var postData = {
			  "posttitle":posttitle,
			  "postbody":postbody,
			  "images":[{'src':postimage, 'href':postlink}]
			};
	statusMsg("POST: XXX" + posttitle + "<br />XXX" + postbody + "<br />" + postlink + "<br />" + postimage);		
	FB.Connect.showFeedDialog(template_bundle_id, postData, null, null, null, FB.RequireConnect.promptConnect);
}


function sendNotification(uids,msg){
	//Notifications do not work in Connect according to FB!
	//If uids is blank it will send to current user
	
	//alert(uids);
	
	//FB.Facebook.apiClient.notifications_send(uids,msg,'user_to_user');
}

