var userFbAuth = false;
var $btFbLogin;
var _initFbLoginText;
function initFb() {
    FB.init({
      appId      : '283455381685840', // App ID
      channelUrl : WP_URL+'/channel.html', // 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.getLoginStatus(function(response) {
		if (response.status === 'connected') {
			var uid = response.authResponse.userID;
			var accessToken = response.authResponse.accessToken;
			userFbAuth = true;
			configFbUser();
			configBtLogin();
		} else if (response.status === 'not_authorized') {
			//alert('logado sem permissao');
			// the user is logged in to Facebook, 
			//but not connected to the app
		} else {
			//alert('deslogado');
			// the user isn't even logged in to Facebook.
		}
	});
	
	$btFbLogin.click(function(e){
		if(userFbAuth){
			fbLogout();
		} else {
			fbLogin();
		}
		e.preventDefault();
	});
};

function fbLogin(){
	FB.login(function(response) {
		if (response.authResponse) {
			//alert(var_dump(response));
			userFbAuth = true;
			configFbUser();
			configBtLogin();
		} else {
			console.log('User cancelled login or did not fully authorize.');
		}
	}, {scope: 'email,publish_stream'});
}

function fbLogout(){
	FB.logout(function(response) {
		userFbAuth = false;
		configBtLogin();
		$('.fb_name:first').html('');
		$('.placaFb').fadeOut('normal',function(){
			$('.detalhe02').fadeIn();
		});
		
		if($('.commentsDefault').size()>0){
			configFormComments(response);
		}
	});
}

function configFbUser(){
	FB.api('/me', function(response) {
		//alert(var_dump(response));
		//topo
		$('.fb_name:first').html(' '+response.name);
		
		//placa
		var $placa = $('.placaFb');
		$placa.show().fadeOut(0);
		$('.detalhe02').fadeOut('normal',function(){
			$placa.fadeIn();
		});
		
		$placa.find('div:first').append('<img src="http://graph.facebook.com/'+response.id+'/picture?type=square" />');
		$placa.find('h5').text(response.name);
		
		//rodape
		$('#Rodape input[name="nome"]').val(response.name);
		$('#Rodape input[name="email"]').val(response.email);
		
		if($('.commentsDefault').size()>0){
			configFormComments(response);
		}
	});
}

function configFormComments(response){
	var $form = $('.commentsDefault form:first').addClass('fb');
	if(userFbAuth){
		$form.prepend('<input type="hidden" name="fb_id" value="'+response.id+'" />');
		$form.prepend('<div class="avatar"><img height="50" width="50" src="http://graph.facebook.com/'+response.id+'/picture?type=square"></div>');
		
		$form.find('input#author').val(response.name).hide();
		$form.find('input#email').val(response.email).hide();
		
		$form.find('button.enviar').click(function(e){
			$(this).append('<small>(aguarde...)</small>');
			var _tempParams = {
				message: $form.find('textarea#comment').val(),
				link: document.location.toString(),
				name: document.title.toString(),
				caption: "Conheça a nossa selva!"
			};
			FB.api('/me/feed', 'post', _tempParams, function(response){
				//alert(var_dump(response));
				$form.submit();
			});
	
			e.preventDefault();
		});
		
	} else {
		$form.removeClass('fb').find('input[name="fb_id"], .avatar').remove();
		$form.find('input:text').val('').show();
		$form.find('button.enviar').unbind('click');
	}
}

function configBtLogin(){
	if(userFbAuth){
		$btFbLogin.html('sair').addClass('logout');
	} else {
		$btFbLogin.html(_initFbLoginText).removeClass('logout');
	}
}

$(document).ready(function(){
	$btFbLogin = $('.login-fb a');
	_initFbLoginText = $btFbLogin.html();
	window.fbAsyncInit = initFb;
});
