
/*
 * API key, this should be initialized before any another function in this file is called.
 */
var is_initialized = false;
var tCallback = null;
var loginTimer;


/*
 * Ensure Facebook app is initialized and call callback afterward
 *
 */
function ensure_init(callback) {
  if(!window.api_key) {
    window.alert("api_key is not set");
  }

  if(window.is_initialized) {
	  trace("We're already initialized. Just call back.");
    callback();
  } else {
	  trace("Loading features...");
      FB_RequireFeatures(["XFBML", "CanvasUtil"], function() {
        FB.Facebook.init(api_key, "xd_receiver.php");
        window.is_initialized = true;
	trace("Features are loaded...calling back.");
	callback();
      });
  }
}
//_____________________________________________________________________________________
function facebook_onload(already_logged_into_facebook) {
  // user state is either: has a session, or does not.
  // if the state has changed, detect that and reload.
  ensure_init(function() {
      FB.Facebook.get_sessionState().waitUntilReady(function(session) {
          var is_now_logged_into_facebook = session ? true : false;
		  
		  //alert("state changed - logged in? " + is_now_logged_into_facebook)

          // if the new state is the same as the old (i.e., nothing changed)
          // then do nothing
          if (is_now_logged_into_facebook == already_logged_into_facebook) {
            return;
          }

          // otherwise, refresh to pick up the state change
          trace("Facebook is loaded.");
	  //refresh_page();
        });
    });
}
//_____________________________________________________________________________________
function facebook_button_onclick() {

  ensure_init(function() {
      FB.Facebook.get_sessionState().waitUntilReady(function() {
          var user = FB.Facebook.apiClient.get_session() ? FB.Facebook.apiClient.get_session().uid : null;

          // probably should give some indication of failure to the user
          if (!user) return;
         
          // The Facebook Session has been set in the cookies,
          // which will be picked up by the server on the next page load
          // so refresh the page, and let all the account linking be
          // handled on the server side

          // This could be done a myriad of ways; for a page with more content,
          // you could do an ajax call for the account linking, and then
          // just replace content inline without a full page refresh.
          
		  trace("we're logged in?");
        });
    });
}
// if user doesn't login within the specified time do timeout -- basically reset
//_____________________________________________________________________________________
function loginTimeout(timeoutInit) {
	//alert("do timeout")
	if(timeoutInit)timeoutInit();
}
//_____________________________________________________________________________________
function login(actionHint,callback,loginInit,timeoutInit) {
	trace("BrowserDetect:"+BrowserDetect.browser);
	//var useActionHint = getQueryParamValue("useActionHint");
	useActionHint = actionHint;

	var callback = (!callback) ? function(){alert(4444)} : callback 
	tCallback = callback;

	
	if(useActionHint == "true"){
		trace("actionHint enabled and set to:"+actionHint);
		if(BrowserDetect.browser == "Safari"){
			actionHint = false;
		}
	}else{
		trace("actionHint is disabled.");
		actionHint = false;
	}
	
    ensure_init(function() {
		trace("getting session state." + tCallback);
		
		loginTimer = setTimeout(loginTimeout,8000,timeoutInit);
		if(loginInit)loginInit();
		
		
		FB.Facebook.get_sessionState().waitUntilReady(function() {
			clearTimeout(loginTimer)
			session_is_ready(tCallback);
      });
	FB.Connect.requireSession(actionHint);
    });
}
//_____________________________________________________________________________________
function logout(callback) {
	tCallback = callback;
	FB.Connect.logout(function() {
	   tCallback();
	});
}
//_____________________________________________________________________________________
function session_is_ready(callback) {
	var user = FB.Facebook.apiClient.get_session() ? FB.Facebook.apiClient.get_session().uid : null;
	if (!user)return;
	callback(user)
	
  // let flash know we're logged in!
  //loggedIn(user); --> flash
}
//_____________________________________________________________________________________
function hideFacebookConnect() {
	
}
//_____________________________________________________________________________________
function getUID(){
	return(FB.Facebook.apiClient.get_session().uid);
}
//_____________________________________________________________________________________
function getUser(callback){
	getUserData(getUID(),callback);
}
//_____________________________________________________________________________________
function getFriends(){
	getFriendData(getUID());
}
//_____________________________________________________________________________________
function UserIsLoggedIn(){
	trace("user is logged in already")
	return true;
}
//_____________________________________________________________________________________
function getUserData(uid,callback) {
	
  var sequencer = new FB.BatchSequencer();
  var fields = new Array("pic_square", "first_name", "last_name");
 
  var pendingProfileResult = FB.Facebook.apiClient.users_getInfo([uid], fields, sequencer);
  
   tCallback = (!callback) ? function(){} : callback 

  sequencer.execute(function() {
  	//for(var i in pendingProfileResult.result[0])trace(pendingProfileResult.result[0][i])
  	//var str = "<img src='"+pendingProfileResult.result[0]["pic_square"] + "'/>";
  	tCallback(pendingProfileResult.result[0])
	pendingProfileResult = null;
	tCallback = null;
  });
}
//_____________________________________________________________________________________
function sendNotification(friend,message) {
  var sequencer = new FB.BatchSequencer();
  var cResult = FB.Facebook.apiClient.notifications_send([friend],message, sequencer);
  sequencer.execute(function() {
  	
  });
}
//_____________________________________________________________________________________
function sendStory(friend,message) {
  var sequencer = new FB.BatchSequencer();
  //var cResult = FB.Facebook.apiClient.feed_publishUserAction (number, {"images":[{ "src":""}]}, [friend], "", 1, "this is a user message", sequencer); ;
  sequencer.execute(function() {
  	//alert(cResult.result)
  });
}
//_____________________________________________________________________________________
function getFriendData(uid,callback) {
  var sequencer = new FB.BatchSequencer();
  var fields = new Array("pic_square", "first_name", "last_name");
  var pendingFriendsResult = FB.Facebook.apiClient.friends_get(null, sequencer);
  var friends = [];
  
  tCallback = (!callback) ? function(){alrt(5555)} : callback 

  sequencer.execute(function() {
	  
	var friendIDs = pendingFriendsResult.result;

  	FB.Facebook.apiClient.users_getInfo(friendIDs,fields, function(r){
		tCallback(r);
		tCallback = null;
  	})	
  });
  
}

//_____________________________________________________________________________________
function trace(msg) {
	return
	var div = document.getElementById('debug');
	if(div){
		div.innerHTML += msg + "<br/>";
	}
}
