/*
Requires:
- all.js
- jquery.js
*/

addDOMLoadEvent(CargarBarraUsuario);

function CargarBarraUsuario()
{
	// Usamos document.getElementById en lugar de JQuery para evitar un posible conflicto con prototype
	if ( (document.getElementById('registro-user') !== null) || (document.getElementById('comments_form') !== null) )
	{
		var ck_user = jQuery.cookie(cookie_nombre_usuario);
		if (ck_user !== null && ck_user != "")
		{
			jQuery.ajax({
				url: "/cabecera-identificacion/",
				type: "GET",
				dataType: "json",
				timeout: 5000,
				success: function(respuesta)
				{
					if (respuesta.code == 'ok')
					{
						CargarUsuarioPrivado(respuesta);
					}
					else
					{
						CargarUsuarioAnonimo();
					}
					jQuery('#registro-user').css('visibility', 'visible');
				},
				error: function(p1,p2,p3)
				{
					CargarUsuarioAnonimo();
					jQuery('#registro-user').css('visibility', 'visible');
				}
			});
		}
		else
		{
			CargarUsuarioAnonimo();
			jQuery('#registro-user').css('visibility', 'visible');
		}
	}
}

function CargarUsuarioAnonimo()
{
	CargarCabeceraAnonimo();
	CargarComentarioAnonimo();
	CargarDatosGaleria(false); // false -> anónimo
	CargarVotoPendienteComentario(false); // false -> no reenviar voto
}

function CargarUsuarioPrivado(datos)
{
	var user = datos.user;
	var blogoteca = datos.blogoteca;
	var concurso = datos.concurso;

	CargarCabeceraUsuario(user, blogoteca, concurso);
	CargarComentarioUsuario(user);
	CargarDatosGaleria(true); // true -> privado
	CargarFichaBlogUsuario(blogoteca);
	CargarVotoPendienteComentario(true); // true -> si reenviar voto
}

/* CABECERA SUPERIOR */

function CargarCabeceraAnonimo()
{
	if (document.getElementById('registro-user') !== null)
	{
		var html =
			'<a href="/usuarios/identificacion/" title="Login" class="thickbox">Iniciar sesi&oacute;n</a>' +
			' | <a id="lnkCabRegistro" href="'+url_web_20m+'usuarios/registro/">Reg&iacute;strate</a>' +
			'<form method="post" id="cabecera_identificacion" name="cabecera_identificacion" >' +
			'	<input id="url_volver" name="url_volver" value="" type="hidden">' +
			'</form>';

		jQuery('#registro-user').html(html);
		tb_activateLink('usuario');
	}
}

function CargarCabeceraUsuario(user, blogoteca, concurso)
{
	if (document.getElementById('registro-user') !== null)
	{
		var html =
			'Hola <strong>' + user.name + '</strong>' +
			' | <a id="lnkCabModificar" href="' + url_web_20m + 'usuarios/modificar/registro/" onclick="VolverUrlCabeceraIdentificacion(\'cabecera_identificacion\',\'url_volver\',\'' +
			url_web_20m + 'usuarios/modificar/registro/\'); return false;" title="Modificar los datos de registro">Cambiar mis datos</a>';

		// Enlaces adicionales en laBlogoteca
		if (typeof blogoteca != 'undefined')
		{
			if ( (blogoteca.length > 0) && (document.location.href.indexOf('lablogoteca') != -1) )
			{
				html += ' | <a href="/modificacion/blogs/" title="Modificar datos blogs">Gestionar mis blogs</a>';
				if (concurso == 'S')
				{
					html += ' | <a href="/premios-20blogs/mis-votos/" class="misvotos" title="Mis votos">Mis votos</a>';
				}
			}
		}

		html +=
			' |	<a href="/proc/desconexion/" title="Cerrar la sesi&oacute;n" class="thickbox">Cerrar sesi&oacute;n</a>' +
			'<form method=\"post\" id=\"cabecera_identificacion\" name=\"cabecera_identificacion\" >' +
			'	<input id=\"url_volver\" name=\"url_volver\" value=\"\" type=\"hidden\" />' +
			'</form>';
		jQuery('#registro-user').html(html);
		tb_activateLink('usuario');
	}
}

/* COMENTARIOS */

var elemComentarios = null;

function CargarComentarioAnonimo()
{
	if (document.getElementById('comments_form') !== null)
	{
		RecuperarComentarioAnonimo();
		tb_activateLink('comentarios');

		// Modifica el comportamiento del enlace de registro de la cabecera
		if(document.getElementById("registro-user") !== null)
		{
			document.getElementById('lnkCabRegistro').onclick = Registrarse;
		}

		jQuery('#preloadCom').hide();
		jQuery('#form_fieldset').show();
	}
}

function CargarComentarioUsuario(user)
{
	if (document.getElementById('comments_form') !== null) {

		// Guardamos (la primera vez) el HTML anónimo para recuperarlo más tarde si hiciera falta
		if(elemComentarios === null) {
			elemComentarios = {
				registro: jQuery('#cab_reg').html(),
				formulario: jQuery('#iidd_form_reg > *')
			};
		}

		var html =
			'<a href="/proc/desconexion/" title="Cerrar la sesi&oacute;n" class="thickbox">Cerrar sesi&oacute;n</a> | ' +
			'<a href="'+url_web_20m+'usuarios/modificar/registro/" onclick="CambiarDatos(\'#nuevo_comentario\'); return false;">Cambiar datos personales</a>';
		jQuery('#cab_reg').html(html);
		tb_activateLink('comentarios');

		CargarFormularioComentarioUsuario(user);

		// Modifica el comportamiento del enlace de modificación de datos de la cabecera
		if(document.getElementById("cabecera_identificacion") !== null) {
			document.getElementById('lnkCabModificar').onclick=CambiarDatos;
		}

		jQuery('#preloadCom').hide();
		jQuery('#form_fieldset').show();
	}
}

// Recuperamos el formulario anónimo que teníamos originalmente
// Sólo se utilzia cuando pasamos de privado a anónimo
// También se utiliza en la navegación de galerías, cuando se detecta que cambia de privado a anónimo
function RecuperarComentarioAnonimo()
{
	if(elemComentarios !== null)
	{
		// Línea superior derecha
		jQuery("#cab_reg").empty().append(elemComentarios.registro);

		// Formulario del usuario
		jQuery("#nombre", elemComentarios.formulario).val(jQuery("#nombre_ok").val());
		jQuery("#email", elemComentarios.formulario).val(jQuery("#email_ok").val());
		jQuery("#url", elemComentarios.formulario).val(jQuery("#url_ok").val());
		if(jQuery("#html_marcado_ok").val() != "")
		{
			jQuery("#mostrarInformacion", elemComentarios.formulario).attr("checked", true);
		}
		else
			{
			jQuery("#mostrarInformacion", elemComentarios.formulario).removeAttr("checked");
		}
		jQuery('#iidd_form_reg').empty().append(elemComentarios.formulario);
	}
}

function CargarFormularioComentarioUsuario(user)
{
	var nombre = document.getElementById('nombre_ok').value;
	var email = document.getElementById('email_ok').value;
	var url = document.getElementById('url_ok').value;
	var html_marcado = document.getElementById('html_marcado_ok').value;

	var html =  '<div class="a50" >';
	html += '	<div class="iidd">';
	html += '		<span class="avatar">';
	html += '			<img id="img_avatar" src="' + user.avatar_url + '" />';
	html += '		</span>';
	html += '		<fieldset class="ptt ptt2" >';
	html += '			<label class="iidd" for="registrado_on"><input name="registrado" id="registrado_on" type="radio" value="yes" class="chk" checked="checked" onclick="Unregistered(false, \''+user.avatar_url+'\');" /> <span style="font-size:160%;">' + user.name + '</span> </label>';
	html += '			<label class="iidd" for="registrado_off"><input name="registrado" id="registrado_off" type="radio" value="no" class="chk" onclick="Unregistered(true, \''+url_estaticos+'avatares/reducido/generico.jpeg\');" /> Usar otro nombre</label>';
	html += '		</fieldset><br />';

	//Si el usuario tiene avatar no aparece el enlace Cambiar imagen
	if (!user.avatar_existe)
	{
		html += '	<p class="cambiar_img"><a href="' + url_web_20m + 'usuarios/modificar/registro/#subir_imagen" onclick="CambiarImagen(\'#nuevo_comentario\'); return false;">Cambiar imagen</a></p>';
	}

	html += '		<fieldset class="ptt a100">';
	html += '			<div id="reg_fields" style="display:none"><label>Nombre <b>(Obligatorio)</b> <input class="inp_txt" name="nombre" id="nombre" type="text" value="' + nombre + '" /></label>';
	html += '				<label>Correo electr&oacute;nico <b>(Obligatorio)</b><input class="inp_txt"  name="email" id="email" type="text" value="' + email + '" /></label>';
	html += '				<label>P&aacute;gina web (si tienes)<input class="inp_txt"  name="url" id="url" type="text" value="' + url + '" /></label>';
	html += '				<label><input name="mostrarInformacion" id="mostrarInformacion" type="checkbox" ' + html_marcado + ' class="chk" /> Mostrar mis datos </label>';
	html += '			</div>';
	html += '		</fieldset>';
	html += '	</div>';
	html += '</div>';

	jQuery('#iidd_form_reg').html(html);
	CaptchaImage.addUpdate('#nombre', 'focus').addUpdate('#email', 'focus');
}

/* GALERIA */

function CargarDatosGaleria(privado)
{
	if(document.getElementById("cabecera_identificacion") !== null && (typeof url_paginacion_galeria) != 'undefined')
	{
		document.cabecera_identificacion.url_volver.value=url_paginacion_galeria;

		if(privado)
		{
			document.getElementById('lnkCabModificar').onclick = function () {
				document.getElementById("cabecera_identificacion").action = url_web_20m + 'usuarios/modificar/registro/';
				document.getElementById("cabecera_identificacion").submit();
				return false;
			};
		}
		else // anónimo
		{
			document.getElementById('lnkCabRegistro').onclick = function Registrarse() {
				document.getElementById("cabecera_identificacion").action = url_web_20m + 'usuarios/registro/';
				document.getElementById("cabecera_identificacion").submit();
				return false;
			};
		}
	}
}

/* FICHA BLOG EN LABLOGOTECA */
function CargarFichaBlogUsuario(blogoteca)
{
	if (typeof blogoteca != 'undefined' && blogoteca.length > 0 && document.getElementById('ficha_blogs') !== null)
	{
		// Si el blog de la ficha es del usuaro identificado le ponemos el enlace para la modificación
		var id_blog = document.location.href.replace(/http:\/\/[^\/]+\/([^\/]+).*/, '$1').replace(/.*-([^\-]+)$/, '$1');
		for (var i=0; i<blogoteca.length; i++)
		{
			if(id_blog == blogoteca[i])
			{
				var url_href = '/modificacion/' + id_blog + '/';
				jQuery('#boton_modificacion').html('<p class=\"modificar\"><a href=" ' + url_href + ' ">Modifica el blog</a></p>');
				break;
			}
		}
	}
}

/* VOTACION COMENTARIOS - VOTOS PENDIENTES DE ENVÍo */

function CargarVotoPendienteComentario(reenviar)
{
	if (typeof comentarioVotado ==  'object' && comentarioVotado !== null)
	{
		if (reenviar)
		{
			VotarComentarioAjax(comentarioVotado.idComentario, comentarioVotado.voto, comentarioVotado.posicion, comentarioVotado.comentario_id_contenido, comentarioVotado.comentario_pagina, comentarioVotado.valoracion, comentarioVotado.total_valoracion);
			// Una vez procesado el voto, vaciamos el objeto de voto pendiente
			comentarioVotado = null;
		}
		else // no reenviar
		{
			var idComentario = comentarioVotado.idComentario;
			jQuery('#comments_enviando_' + idComentario)
				.removeClass("enviando")
				.addClass("enviando_error")
				.html('Hubo alg&uacute;n problema en el proceso de identificaci&oacute;n, vu&eacute;lvalo a intentar<br />')
				.show();
			jQuery('#comments_votador_' + idComentario).show();
		}

	}
}

/* FORMULARIO AÑADIR COMENTARIO - MENSAJE CARGANDO INICIAL */

function CargandoLoginComentarios()
{
	jQuery('#form_fieldset').hide();
	jQuery('#preloadCom').html('<p>Proceso de verificaci&oacute;n de autentificaci&oacute;n.</p><img src="'+url_css3+'i/loading_news.gif" alt=\"Espere, por favor\" width=\"107\" height=\"41\"/></p>');
	jQuery('#preloadCom').show();
}

/* COMENTARIOS AUXILIARES */

function Unregistered(b, user_avatar_url)
{
	if(b)
	{
		jQuery('#reg_fields').show();
		jQuery('#img_avatar').attr({src: user_avatar_url});
		jQuery('.cambiar_img').hide();
	}
	else
	{
		jQuery('#reg_fields').hide();
		jQuery('#img_avatar').attr({src: user_avatar_url});
		jQuery('.cambiar_img').show();
	}
}