/* 
 * Facebook scripts.
 */
window.fbAsyncInit = function(){
	FB.init({
		//appId      : '296687947018846', // App ID
		appId      : '228733727197323',
		channelURL : 'channel.php', // Channel File
		status     : true, // check login status
		cookie     : true, // enable cookies to allow the server to access the session
		oauth      : true, // enable OAuth 2.0
		xfbml      : true  // parse XFBML
	});

	FB.Event.subscribe('edge.create',
		function(response) {
			socialInc();
		}
	);

	FB.Event.subscribe('auth.login',
		function(response) {
			fbDetails();
		}
	);
};

// Load the SDK Asynchronously
(function(d){
	var js, id = 'facebook-jssdk';if (d.getElementById(id)) {return;}
	js = d.createElement('script');js.id = id;js.async = true;
	js.src = "//connect.facebook.net/en_GB/all.js";
	d.getElementsByTagName('head')[0].appendChild(js);
}(document));

socialInc = function(){
	var sinc = $('#sinc'),
	sincv = parseInt(sinc.val() || 0) + 1;
		sinc.val(sincv);
		console.log(sincv);
}

	var fbdetails = false;

	fbDetails = function(){
		jQuery(function($){
			if (fbdetails) {
				FB.logout(function(response){
					$('#name').val('');
					$('#email').val('');
					$('#fbid').val(null);
					$('#details-fb').hide();
					$('#submit-details').show();
					fbdetails = false;
				});
			} else {
				FB.api('/me', function(response) {
					$('#name').val(response.name);
					$('#email').val(response.email);
					$('#fbid').val(response.id);
					$('#submit-details').hide();
					$('#details-fb').show();
					$('#tmys').hide();
					fbdetails = true;
				});
			}
		});
	}

jQuery(function($){


	//$('#submit-fb').click(function() {
		//$.fn.fbDetails();
		/*FB.getLoginStatus(function(response) {
			if (response.authResponse) {
				$.fn.fbDetails();
			} else {
				FB.login(function(response) {
					if (response.authResponse) {
						$.fn.fbDetails();
					}
				}, {scope: 'email'});
			}
		});*/
	//});

	$('#logout-fb').click(function(){
		fbDetails();
	})

	$('#share').live('click', function(e){
		e.preventDefault();
		var feedData = {
			method: 'feed',
			link: $('#fb-like').attr('data-href'),
			picture: '',
			name: 'EMI Christmas',
			caption: 'I just played EMI Christmas and spotted ' + $('#correct').text() + ' out of 59 artists.',
			description: 'Can you top it and win?'
        };

		FB.ui(feedData, function(response) {
			if (!response || response.error) {
				//console.log('Error posting to Facebook feed.');
			} else {
				//console.log('Post ID: ' + response['post_id']);
			}
		});
	});

	$('#enter').click(function(){
		$('#entry').dialog('open');
		FB.getLoginStatus(function(response) {
			if (response.authResponse) {
				fbDetails();
			}
		});
	});

});

