var userID;
var userInfo;
var friendInfo;

//LIVE API Key
var api_key = "5179635e18c767f7c566e52163dc023e";
var template_bundle_id = "54433133541"; 			//http://developers.facebook.com/tools.php?feed 

//DEV API Key
//var api_key = "5179635e18c767f7c566e52163dc023e";
//var template_bundle_id = "54433133541"; 			//http://developers.facebook.com/tools.php?feed 
  	
function loginConnect(){	
	checkConnect();
	FB.Connect.requireSession();
}
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,'uid,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,'uid,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["flashcontent"]:document["flashcontent"];
	flash.returnProfile(userInfo);		
	statusMsg("Finished loading profile!");
}

function sendFriends(){
	//writeFriends();
	var flash = (navigator.appName.indexOf ("Microsoft") !=-1)?window["flashcontent"]:document["flashcontent"];
	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, postname) {

	var postData = {
			 "posttitle":posttitle,
			 "postbody":postbody,
			 "postname":postname,
			 "images":[{"src":"http://www.imaginethatmovie.com/facebookicon.jpg", "href":"http://www.imaginethatmovie.com/"}]
			};

	FB.Connect.showFeedDialog(template_bundle_id, postData, null, null, null, FB.RequireConnect.promptConnect);
}


function publishStoryforFS(posttitle, postbody, imglink) {

	var postData = {
			 "posttitle":posttitle,
			 "postbody":postbody,			
			 "images":[{"src":imglink, "href":"http://www.imaginethatmovie.com/"}]
			};

	FB.Connect.showFeedDialog("72374583541", postData, null, null, null, FB.RequireConnect.promptConnect);
}
