$(function() {

	$('#signup').click(function(e) {
		e.preventDefault();
		FB.login(function(r) {
			if (r.authResponse) $.post('/beta', {
				fb: r.authResponse.accessToken,
				ref: fbref ? fbref : ''
			}, function(d) {
				if (d.success) {
					var g = getMe();
					$('#dv-tell-me').fadeOut(500, function() {
						g.ok();
					});
					if (fbref) {
						FB.api(fbref, 'delete');
					}
				}
			});
		}, {scope:'email'});
	});
	
	$(document).bind('fbready', function() {
		FB.getLoginStatus(function(r) {
			if (r.status == 'connected') {
				$('#dv-tell-me').hide();
				getMe().ok();
				$.post('/beta', {
					fb: r.authResponse.accessToken,
					ref: fbref ? fbref : ''
				});
			}
		});
	});
	
	function getMe() {
		var fetched = false;
		var ready = false;
		
		FB.api('/me', function(r) {
			if (r) {
				$('#mypic').attr('src','//graph.facebook.com/' + r.id + '/picture');
				$('#myname').text(r.first_name);
				ok();
			}
		});
		
		function ok() {
			if (ready) $('#dv-on-list').fadeIn(500);
			else fetched = true;
		}
		return {
			ok: function() {
				ready = true;
				if (fetched) ok();
			}
		}
		
	}
	
	$('#share').click(function(e) {
		e.preventDefault();
		FB.ui({
			method: 'apprequests',
			message: 'Sign up for private beta of Dramaville, the game where you build a team of celebrity misfits and earn points when they cause drama.'
		}, function(r) {
			if (r.request) {
				$.post('/invite', {
					id: r.request
				});
			}
		});
	});
});
