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

// euro beta
//var api_key = "d5f4ada37e93c799644ec738000f63ca";

// ef
var api_key = "78864521b0b5819af16e36cfe4a614b2";

var receiver = "xd_receiver.htm";
var movieID = "ef";


/*
 * Ensure Facebook app is initialized and call callback afterward
 *
 */
function ensure_init(callback) {
	if(!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, receiver);
			is_initialized = true;
			trace("Features are loaded...calling back.");
			callback();
		});
	}
}


/*
 * The facebook_onload statement is printed out in the PHP. If the user's logged in
 * status has changed since the last page load, then refresh the page to pick up
 * the change.
 *
 * This helps enforce the concept of "single sign on", so that if a user is signed into
 * Facebook when they visit your site, they will be automatically logged in -
 * without any need to click the login button.
 *
 * @param already_logged_into_facebook  reports whether the server thinks the user
 *                                      is logged in, based on their cookies
 *
 */
function facebook_onload(already_logged_into_facebook) {
	trace("- - - - - - - - - - - - - - - - - - - - - - - - ");
	trace("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.
	FB.ensureInit(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("");
	trace("- - - - - - - - - - - - - - - - - - - - - - - - - - - - ");
	trace("> 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() {
	trace("");
	trace("- - - - - - - - - - - - - - - - - - - - - - - - - - - - ");
	trace("> logout");
	
	FB.Connect.logout(function() {
	  // Let flash know we're logged out
	  loggedOut();
	});
}


//----------------------------------------------------------------------------------------
function session_is_ready() {
	trace("");
	trace("- - - - - - - - - - - - - - - - - - - - - - - - - - - - ");
	trace("> session_is_ready");
	
	var user = FB.Facebook.apiClient.get_session() ? FB.Facebook.apiClient.get_session().uid : null;
  
  if (!user) {
    return;
  }
  
	
	FB.Facebook.apiClient.users_hasAppPermission("publish_stream",
	function(result) {
			// prompt offline permission
			if (result == 0) {
					// show the facebook permission dialog
					FB.Connect.showPermissionDialog("publish_stream",
					function(result){
							if (!result) {
									// no permisson granted, pop up facebook dialog to post;
									//FB.Connect.streamPublish('', attachment, action_links, null, "Post this:", jscallback);
							} else {
									// permission granted, post without facebook dialog
									FB.Connect.forceSessionRefresh();
							}
					}, true, null);
			} else {
					// permission already granted, post suddenly
					// without facebook dialog
					//FB.Connect.streamPublish('', attachment, action_links, null, "Post this:", jscallback,true);
			}
	});
	
	
	
  // let flash know we're logged in!
  loggedIn(user);
}


//----------------------------------------------------------------------------------------
function getData(uid) {
	trace("");
	trace("- - - - - - - - - - - - - - - - - - - - - - - - - - - - ");
	trace("> 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 pubblica(objComm) {
	trace("");
	trace("- - - - - - - - - - - - - - - - - - - - - - - - - - - - ");
	trace("> pubblica");
	
	trace("titolo " + objComm['titolo']);
	trace("link " + objComm['link']);
	trace("capt " + objComm['capt']);
	trace("desc " + objComm['desc']);
	trace("img " + objComm['img']);
	
	
	var attachment = {
		'name': objComm['titolo'],
		'href': objComm['link'],
		'caption': objComm['capt'],
		'description': objComm['desc'],
		'media': [{
			'type': 'image',
			'src' : objComm['img'],
			'href': objComm['link']
		}]

	};
	
	
	FB.Facebook.apiClient.users_hasAppPermission("publish_stream",
	function(result) {
			// prompt offline permission
			if (result == 0) {
					// show the facebook permission dialog
					FB.Connect.showPermissionDialog("publish_stream",
					function(result){
							if (!result) {
									// no permisson granted, pop up facebook dialog to post;
									FB.Connect.streamPublish('', attachment, null, null, null, null);
							} else {
									// permission granted, post without facebook dialog
									FB.Connect.forceSessionRefresh(function() {
											FB.Connect.streamPublish('', attachment, null, null, null, null,true);
									});
							}
					}, true, null);
			} else {
					// permission already granted, post suddenly
					// without facebook dialog
					FB.Connect.streamPublish('', attachment, null, null, null, null,true);
			}
	});
	
	
	
	
	FB.Connect.streamPublish(message, attachment, null, null, null, null, true);
	

}


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

if(!("console" in window) || !("firebug" in console)) {
    var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml", "group", "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"];
    window.console = {};
    for(var i = 0; i < names.length; ++i) window.console[names[i]] = function() {};
}
function trace(msg) {
	// alert(msg);
	if(console)	
		console.debug(msg);
}
function inspect(obj) {
	if(console)	
		console.dir(obj);
}
			



function loggedIn(user)
{
	movie().loggedIn(user);
}

function loggedOut()
{
	movie().loggedOut();
}

function gotData(profileData, uids)
{
	movie().gotData(profileData, uids);
}

function onReady(){
	movie().onReady();
}

function movie() {
		if (navigator.appName.indexOf("Microsoft") != -1) {
	return window[movieID]
		}
		else {
	return document[movieID]
		}
}














