/**
 *  This file is part of Pontealaire.
 *
 *  Pontealaire is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  Pontealaire is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with Pontealaire.  If not, see <http://www.gnu.org/licenses/>.
 *
 * @package public
 * @subpackage js
 * @author Óscar Palacios <oscarpalacious@gmail.com>
 * @copyright Copyright (c) 2010, Óscar Palacios
 * @license http://www.gnu.org/licenses/gpl.html GNU Public License
 *
 */
var Fbook = {
	config : null,
	sesion : null,

	/**
	 * Inicializador del API de Facebook.
	 */
	init : function(config) {
		Fbook.config = config;
		FB.init({
			appId  : Fbook.config.apikey,
			status : true,
			cookie : true,
			xfbml  : true,
			oauth  : true
		});
		Fbook.switchSesion();
	},

	/**
	 * Cambia el despliegue entre un botón de
	 * login y la foto y el nombre del usuario.
	 */
	switchSesion : function() {
		if(jq(Fbook.config.contenedorLogin).length > 0) {
			var facebookHTML = '';
			FB.getLoginStatus(function(respuesta) {
				Fbook.sesion = respuesta.authResponse;
				if(respuesta.status == 'connected') {
					facebookHTML  = '<fb:profile-pic width="25" height="25" uid="loggedinuser" facebook-logo="true" ></fb:profile-pic>';
					facebookHTML += '<span>Bienvenido, <fb:name uid="loggedinuser" useyou="false"></fb:name>';
					facebookHTML += '&nbsp;&#124;&nbsp;<a href="javascript:Fbook.logout();">';
					facebookHTML += '<font color="#CCCCCC">Cerrar sesi&oacute;n</font></a></span>';
					if(jq(Fbook.config.contenedorComentarios).length > 0) {
						jq('#comentario_contenido').removeAttr('disabled');
						jq('#comentario_contenido').html('');
						jq('#postear').removeAttr('disabled');
						jq('#cancelar').removeAttr('disabled');
						jq('#publicar_wall').removeAttr('disabled');
					}
					if(jq(Fbook.config.contenedorComentarios).length > 0) {
						jq('#comentario_contenido').removeAttr('disabled');
						jq('#comentario_contenido').html('');
						jq('#postear').removeAttr('disabled');
						jq('#enviarWallContenedor').show();
						jq('#comentario_connect').html('');
						jq('#comentariosImagenContenedor').html('');
						jq('#comentariosImagenContenedor').html('<fb:profile-pic uid="loggedinuser" facebook-logo="true" ></fb:profile-pic>');
						jq('.fbInt').hide();
					}
				} else {
					facebookHTML = '<fb:login-button style="float: left;" onlogin="Fbook.switchSesion();" scope="publish_stream,offline_access"></fb:login-button><span>Comenta usando tu cuenta de Facebook</span>';
					if(jq(Fbook.config.contenedorComentarios).length > 0) {
						jq('#comentario_contenido').attr('disabled', 'disabled');
						jq('#comentario_contenido').html('Inicia sesi&oacute;n para dejar tu comentario');
						jq('#postear').attr('disabled', 'disabled');
						jq('#enviarWallContenedor').hide();
						jq('#comentariosImagenContenedor').html('');
						jq('#comentariosImagenContenedor').html('<img src="/img/misc/noPhoto.jpg" alt="" />');
						jq('.fbInt').show();
					}
				}
				jq(Fbook.config.contenedorLogin).html('');
				jq(Fbook.config.contenedorLogin).html(facebookHTML);
				FB.XFBML.parse(null, function() {
					jq('.fb_link').css('color', '#CCCCCC');
				});
			});
		}
	},

	comentarioEnviar : function() {
		var comentario = jq('#comentario_contenido').val();
		var enviarWall = jq('input[id=publicar_wall]:checked').length;
		if(comentario.length > 0) {
			FB.getLoginStatus(function(respuesta) {
				if(respuesta.status == 'connected') {
					if(enviarWall > 0) {
						FB.api('/'+Fbook.sesion.userID+'/feed', 'post', { message: comentario }, function(respuesta) {
							if(!respuesta || respuesta.error) {
								alert('Hubo un error al intentar enviar tu comentario a Facebook.');
							}
						});
					}
					jq.ajax({
						'url'      : '/comentarios/comentarioGuardar',
						'type'     : 'post',
						'data'     : {
							'comentario'  : jq('#comentario_contenido').val(),
							'contexto'    : jq('#contexto').attr('name'),
							'contexto_id' : jq('#contexto').val(),
							'facebook_id' : Fbook.sesion.userID
						},
						'dataType' : 'html',
						'success'  : function(response) {
							jq('#comentarios_lista').prepend(response);
							jq('#comentario_contenido').val('');
							FB.XFBML.parse();
						}
					});
				} else {
					//
				}
			});
		} else {
			alert('Nos interesa su comentario. De veras.');
		}
	},

	logout : function() {
		FB.logout(function(response) {
			Fbook.switchSesion();
		})
	}

};
