var TBB = TBB || {};

TBB.FB = {
	initFBSSO: function(params) {
		var instance = this;

		instance.namespace = params.namespace;
		instance.templateURL = params.templateURL;
	},

	cancelLinking: function() {
		var instance = this;

		jQuery.ajax(
			{
				url: instance.templateURL,

				data: {
					cmd: 'cancel'
				},
				dataType: 'json',
				success: function(message) {
					window.location = "/home";
				}
			}
		);
	},

	deauthorize: function() {
		var instance = this;
		jQuery.ajax(
			{
				url: instance.templateURL,

				data: {
					cmd: 'disconnect'
				},
				dataType: 'json',
				success: function(message) {
					FB.api({ method: 'Auth.revokeAuthorization' }, function(response) { location.reload(); });
				}
			}
		);
	},

	loadSessionParam: function(session) {
		var instance = this;

		jQuery.ajax(
				{
					url: instance.templateURL,

					data: {
						cmd: 'session',
						access_token: session.access_token
						
					},
					dataType: 'json',
					success: function(message) {
						
					}
				}
			);
	},
	
	disconnect: function() {
		var instance = this;

		jQuery.ajax(
			{
				url: instance.templateURL,

				data: {
					cmd: 'disconnect'
				},
				dataType: 'json',
				success: function(message) {
				}
			}
		);
	},

	getUserEmail: function(emailInput1, emailInput2) {
		FB.login(function(response) {
			if (response.session) {
				FB.api('/me', function(response) {
					if (response && response.verified) {
						jQuery('#' + emailInput1).val(response.email);
						jQuery('#' + emailInput2).val(response.email);
					}
					else {
						Liferay.CornerPop.helpDialog(jQuery('#fb-import-email'), 'fb-invalid-email');
					}
				});
			}
		}, {perms:'email'});
	},

	getUserInfo: function(firstNameInput, lastNameInput, maleRadio, femaleRadio) {
		FB.api('/me', function(response) {
			if (response) {
				jQuery('#' + firstNameInput).val(response.first_name);
				jQuery('#' + lastNameInput).val(response.last_name);

				if (response.gender) {
					if (response.gender == 'female') {
						jQuery('#' + maleRadio).attr('checked', false);
						jQuery('#' + femaleRadio).attr('checked', true);
					}
				}
			}
		});
	},

	loadParam: function(authResponse) {
		var instance = this;
		jQuery('#' + instance.namespace + 'accessToken').val(authResponse.accessToken);
		jQuery('#' + instance.namespace + 'expiresIn').val(authResponse.expiresIn);
		jQuery('#' + instance.namespace + 'userID').val(authResponse.userID);
		jQuery('#' + instance.namespace + 'signedRequest').val(authResponse.signedRequest);
	}
}
