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



/*
 * 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;

          // 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() {
trace("facebook_button_onclick()");

  ensure_init(function() {
      FB.Facebook.get_sessionState().waitUntilReady(function() {
		      trace("ok we're ready.");
          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) {
		  trace("no 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?");
        });
    });
}



/*
 * Temp (or maybe not so temp) login function
 */

function login(actionHint) {
	trace("BrowserDetect:"+BrowserDetect.browser);
	//var useActionHint = getQueryParamValue("useActionHint");
	useActionHint = "true";
	
	if(useActionHint == "true"){
		trace("actionHint enabled and set to:"+actionHint);
		if(BrowserDetect.browser == "Safari"){
			//ignore for safari.
			actionHint = false;
		}
		//use whatever is passed in.
	}else{
		trace("actionHint is disabled.");
		actionHint = false;
	}
  ensure_init(function() {
		trace("getting session state.");
		FB.Facebook.get_sessionState().waitUntilReady(function() {
		session_is_ready();
      });
	FB.Connect.requireSession(actionHint);
    });
}

function logout() {
	FB.Connect.logout(function() {
	  // Let flash know we're logged out
	  loggedOut();
	});
}

function session_is_ready() {
	var user = FB.Facebook.apiClient.get_session() ? FB.Facebook.apiClient.get_session().uid : null;
  
  if (!user) {
    return;
  }
  
  // let flash know we're logged in!
  loggedIn(user);
}

function getData(uid) {
  var sequencer = new FB.BatchSequencer();
  var fields = new Array("pic_square", "first_name", "last_name", "affiliations");
  
  var pendingFriendsResult = FB.Facebook.apiClient.friends_get(null, sequencer);
  var pendingProfileResult = FB.Facebook.apiClient.users_getInfo([uid], fields, sequencer);
  
  sequencer.execute(function() {
    gotData(pendingProfileResult.result[0], pendingFriendsResult.result);
  });
}

function publishStory(feedID, comment, sitename, siteurl, posttitle,  postlink, postimage, synopsis) {
	//sitename = "funkytown";
	var template_data = {
			  "comment":comment,
			  "sitename": sitename,
			  "siteurl": siteurl,
			  "posttitle":posttitle,
			  "postlink":postlink,
			  "postimage": postimage,
			  "synopsis": synopsis,
			  "images":[{'src':postimage,
                                     'href':postlink}]
			};
	var attachment = {
	    media: 
	    [
	        { 
	            type: 'image',
	            src: postimage,
	            href: postlink
	        }
	    ], 
	    name: posttitle,
	    href: postlink,
	    caption: '{*actor*} wrote "' + comment + '" about this article on ' + sitename + '.'
	};
	var actionLinks = [
	    { 
	        text: sitename,
	        href: siteurl
	    }
	];
			//trace("comment:"+comment+"<br/>sitename:"+sitename+"<br/>posttitle:"+posttitle+"<br/>postlink:"+postlink+"<br/>postimage:"+postimage+"<br/>synopsis:"+synopsis);
			//FB.Connect.showFeedDialog(feedID, template_data);
	FB.Connect.streamPublish(
	    comment,
	    attachment,
	    actionLinks
	    );
}

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