var login_box = document.getElementById('header_user_info');
function handleFacebook() {
login_box.style.visibility = "hidden";
var api = FB.Facebook.apiClient;
var userID = api.get_session().uid;
login_box.innerHTML = "<span>"
+ "Bienvenid@, "+"<fb:name uid=loggedinuser useyou='false'></fb:name>"+'</span> (<a href="javascript:void(0)" onclick="FB.Connect.logout(function(obj){handleFacebookLogout()})">Salir</a>)'
+ "</span>";
FB.ensureInit(function() {
FB.XFBML.Host.parseDomElement(document.getElementById('header_user_info'));
});

api.fql_query('SELECT sex,first_name,last_name,email,proxied_email,birthday_date,current_location,hometown_location FROM user WHERE uid='+userID,
function(result){
echo(result,userID);
});
$("span#FB_profile_pic").append('<img id="fbc_loading" style="margin-left:-15px" src="'+pspath+'/modules/facebookconnect/ajax-loader.gif" />');
login_box.style.visibility = "visible";
}

function echo (obj,uid) {
var hlocate = obj[0]['hometown_location'];
var clocate = obj[0]['current_location'];
if (hlocate != null) {
obj[0]['hcity'] = (hlocate['city'] != null) ? hlocate['city'] : '';
obj[0]['hcountry'] = (hlocate['country'] != null) ? hlocate['country'] : '';
obj[0]['hstate'] = (hlocate['state'] != null) ? hlocate['state'] : '';
obj[0]['hzip'] = (hlocate['zip'] != null) ? hlocate['zip'] : '';
}
if (clocate != null) {
obj[0]['ccity'] = (clocate['city'] != null) ? clocate['city'] : '';
obj[0]['ccountry'] = (clocate['country'] != null) ? clocate['country'] : '';
obj[0]['cstate'] = (clocate['state'] != null) ? clocate['state'] : '';
obj[0]['czip'] = (clocate['zip'] != null) ? clocate['zip'] : '';
}
obj[0]['userid'] = uid;

$.post(pspath+"/modules/facebookconnect/capture_request.php",obj[0],
		  function(data){
			eval(data);
});
	}

function handleFacebookLogout(stat) {
$("img#fbc_loading").css("visibility","visible");
if (stat) {
$.get(pspath+"/modules/facebookconnect/capture_request.php",{action:"status",rand: "" + new Date().getTime()},
			function(result){
				if (result == 1) {
				doLogout(); }
			});
	}
else {
doLogout();
	}
}

function updateLink() {
$("p.logout").before('<img src="'+pspath+'/modules/facebookconnect/facebook-logo-small.png" style="float:left" height="22px" width="22px"/>');
$("p.logout a").attr({href:"javascript:void(0)",onClick:"FB.Connect.logout(function(){handleFacebookLogout();})"});
}

function doLogout() {
$.get(pspath+"/index.php",{rand: "" + Math.random(),mylogout:""},
		function(data) {
			$.get(pspath+"/modules/facebookconnect/capture_request.php",{rand: "" + Math.random(),action:"logout"});
    		$("div.myaccount").css("display","none");
			var inf = $('#header_user_info',data);
    		$("p#header_user_info").replaceWith(inf);
			FB.XFBML.Host.parseDomElement(document.getElementById('header_user_info'));
  		});
}