// TODO: namespace this
var me = null;

$(function() {

	// TODO: check this doesn't intefere when connection is OK
	if (typeof(FB) == 'undefined') {
		return;
	}

	FB.init({ 
		appId: $('#fbAppId').val(),
		cookie: true, 
		status: true,
		xfbml: true 
	});
		
	FB.api('/me', function(response) {
	  me = response;
	});

	$('.facebookLogoutLink').live('click', function(e) {
		e.preventDefault();
		$(this).html('Logging out...');
		var thisHref = $(this).attr('href');
		FB.logout(function() {
			// Proceed to standard logout
			window.location = thisHref;
		});
	});

	$('.sendRequest').live('click', function(e) {
		e.preventDefault();
		sendRequest();	
	});

	$('#facebookFriends a').live('click', function(e) {
		e.preventDefault();
		var imgSrc = 'http://graph.facebook.com/'+$(this).attr('rel')+'/picture?type=large';
		//console.log(imgSrc);
		$('#facebookPic').attr('src', imgSrc);
	});

});

var redirectDivHtml = '<div class="dialog loginSuccessful facebookRedirect">'
	+ '<h1>Facebook login successful.</h1>'
	+ '<img src="/images/ajax-loader.gif">'
	+ '<h1>Redirecting Now...</h1>'
	+ '</div>';

function facebookLoginCallback()
{
	FB.getLoginStatus(function(response) {
		if (response.session) { 
			$('#blackOverlay').fadeIn();
			$('body').append(redirectDivHtml);
			$('.loginSuccessful').fadeIn();

			$.get('/authentication/facebookLogin', function(d) {
				window.location = '/authentication/facebookLogin';
			});
		}
	}); 
}

function sendRequest() {
	FB.ui({
		method: 'apprequests',
		message: 'Wickets is a multiplayer, stats-based cricket game! Play for free now.',
		title: 'Send your friends an application request'
	},
	function (response) {
		if (response && response.request_ids) {
			var requests = response.request_ids.join(',');
			$.post('/account/handleRequests',{ uid: me.id, request_ids: requests },function(resp) {
				//console.log(resp);
			});
		} else {
			//console.log('canceled');
		}
	});
	return false;
}

