/*
	---------------------------------------------------------------------------
	Empresa			: Proconsi S.L.
	Fecha creación	: 08-07-2010
	Fecha ult.modif.: 10-11-2010 - David González
	Módulo			: Funciones Ajax (peticiones y callbacks) para el módulo usuariosweb en entorno WEB
	----------------------------------------------------------------------------
	Historial de modificaciones:
	[1] - 09-07-2010 - David González 
	Unificación de todas las comprobaciones de campos en una única función
	ComprobarCamposUsuarioWeb, que se llamará desde otras funciones
	[2] - 12-07-2010 - David González
	Nuevo parámetro opcional lMensajeSimpleModal en TestUsuario para mostrar el mensaje
	de usuario incorrecto en una ventana SimpleModal de JQuery
	[3] - 14-07-2010 - David González
	Nueva función anónima de jQuery para poner y quitar automáticamente el "Introduzca"
	[4] - 16-07-2010 - David González
	Meter los mensajes de respuesta de alta de usuario y recuperación de clave dentro de 
	un div propio
	[5] - 05-08-2010 - David González
	Mejora de estilos simplemodal
	[6] - 30-09-2010 - David González
	Nuevo campo firma (Sólo si el foro está activo)
	[7] - 13-10-2010 - David González
	Comentada función creada en [3] puesto que se han añadido eventos onBlur y onFocus
	a los campos de usuariosWeb y con esto deja de ser necesaria
	[8] - 15-10-2010 - David González
	Si hay apellidos en los formularios de usuariosweb y se deja el valor por defecto,
	grabarlos en blanco
	[9] - 09-11-2010 - David González
	Modificado campo DNI para que no sea obligatorio elegir entre NIF o NIE. En 
	caso de que no exista el selector de NIF / NIE, comprobar NIF
	[10] - 10-11-2010 - David González
	Renombradas funciones y variables para login en modo página completa.
	Nueva variable redir en login página completa
	[11] - 14-12-2010 - David González
	Indicar el formato de DNI correcto en caso de que el DNI no sea válido.
	El DNI no es obligatorio
	----------------------------------------------------------------------------
*/
///
/// Testea el usuario y la contraseña introducidos
///
function TestUsuario( lMensajeSimpleModal )
{
	var cUser = document.getElementById( "usuarioLogin" ).value;
    var cPass = document.getElementById( "passwordLogin" ).value;
    var lRecordar = "false";
	if( document.getElementById( "recordarUsuario" ) )
		lRecordar = document.getElementById( "recordarUsuario" ).checked;
	var cParameters = "usuario=" + cUser + "&password=" + cPass + "&recordar=" + lRecordar;  
    var cParameters = "usuario=" + cUser + "&password=" + cPass + "&recordar=" + lRecordar;  
    if( lMensajeSimpleModal != undefined && lMensajeSimpleModal == true ) //[2]
    	AjaxRequest( app_BasePath + 'Modulos/usuariosweb/acceso.php' , cParameters , UserLoginSimpleModal ); //[2]
    else AjaxRequest( app_BasePath + 'Modulos/usuariosweb/acceso.php' , cParameters , UserLogin );
}
///
/// Testea el usuario y la contraseña introducidos (Para bloque de login en página específica) [10]
/// 
function TestUsuarioPag( lMensajeSimpleModal )
{
	 var cUser = document.getElementById( "usuarioLoginPag" ).value;
	 var cPass = document.getElementById( "passwordLoginPag" ).value;
	 var cUrlRedireccion = document.getElementById( "urlRedirLogin" ).value;
	 var lRecordar = "false";
	 if( document.getElementById( "recordarUsuarioPag" ) )
		 lRecordar = document.getElementById( "recordarUsuarioPag" ).checked;
	 var cParameters = "usuario=" + cUser + "&password=" + cPass + "&redir=" + cUrlRedireccion + "&recordar=" + lRecordar; //[10] 
	 if( lMensajeSimpleModal != undefined && lMensajeSimpleModal == true ) //[2]
	 	 AjaxRequest( app_BasePath + 'Modulos/usuariosweb/acceso.php' , cParameters , UserLoginSimpleModalPag ); //[2]
	 else AjaxRequest( app_BasePath + 'Modulos/usuariosweb/acceso.php' , cParameters , UserLoginPag );
}
///
/// Callback de Ajax para la respuesta al logueo del usuario
///
function UserLogin( xmlhttp )
{
    if( xmlhttp.readyState == 4 && xmlhttp.status == 200 )
    {
        if( xmlhttp.responseText != "OK" )
        {
            //
            // Error en el inicio de sesión. El motivo se muestra en el mensaje
            if( document.getElementById( "mensajeLoginWeb" ) != undefined )
            {
                document.getElementById( "mensajeLoginWeb" ).innerHTML = xmlhttp.responseText;
                document.getElementById( "mensajeLoginWeb" ).style.display = 'block';
            }
            else
                alert( xmlhttp.responseText );
            //
            document.getElementById( "passwordLogin" ).value = "";
            document.getElementById( "usuarioLogin" ).focus();
        }
        else
        {
            //
            // Usuario y contraseña aceptados. Recargamos la página
            window.location.reload();
        }
    }
    if( xmlhttp.readyState == 4 && xmlhttp.status == 500 )
    {
    	if( document.getElementById( "mensajeLoginWeb" ) != undefined )
        	document.getElementById( "mensajeLoginWeb" ).style.display = "block";
    }
}
///
/// Callback de Ajax para la respuesta al logueo del usuario (Para bloque de login en página específica) [10]
///
function UserLoginPag( xmlhttp )
{
	 if( xmlhttp.readyState == 4 && xmlhttp.status == 200 )
	 {
		 if( xmlhttp.responseText.substr( 0 , 2 ) != 'OK' ) 
	     {
	         //
	         // Error en el inicio de sesión. El motivo se muestra en el mensaje
	         if( document.getElementById( "mensajeLoginWebPag" ) != undefined )
	         {
	             document.getElementById( "mensajeLoginWebPag" ).innerHTML = xmlhttp.responseText;
	             document.getElementById( "mensajeLoginWebPag" ).style.display = 'block';
	         }
	         else
	             alert( xmlhttp.responseText );
	         //
	         document.getElementById( "passwordLoginPag" ).value = "";
	         document.getElementById( "usuarioLoginPag" ).focus();
	     }
	     else
	     {
	         //
	         // Usuario y contraseña aceptados. Cargamos la url especificada y si no viene ninguna, la página principal [10]
	    	 if( xmlhttp.responseText.length > 2 )
	    	 {	 
	    		 cRespuesta = xmlhttp.responseText.split( ';' );
	    		 cUrl = cRespuesta[1]; 
	    		 window.location.replace( cUrl );
	    	 }
	    	 else
	    		 window.location.replace(window.location.protocol + "//" + window.location.host);
	     }
	 }
	 if( xmlhttp.readyState == 4 && xmlhttp.status == 500 )
	 {
	 	if( document.getElementById( "mensajeLoginWebPag" ) != undefined )
	     	document.getElementById( "mensajeLoginWebPag" ).style.display = "block";
	 }
}
///
/// Callback de Ajax para la respuesta al logueo del usuario en ventana SimpleModal [2][5]
///
function UserLoginSimpleModal( xmlhttp )
{
 if( xmlhttp.readyState == 4 && xmlhttp.status == 200 )
 {
     if( xmlhttp.responseText != "OK" )
     {
         //document.getElementById( "passwordLogin" ).value = "";
         document.getElementById( "usuarioLogin" ).focus();
         //
		 // SimpleModal (jQuery)
         $.modal(
     			"<div id='mensajeLoginSimpleModal' class='mensajeLoginSimpleModal'>" + xmlhttp.responseText + "</div>" ,
     			{
     				overlay: 30,
     				overlayCss: { backgroundColor: "#fff" },
     				focus: true,
     				opacity: 60,
     				dataCss: {},
     				close: true,
     				closeHTML: '<div id="modalClose"><div id="modalClose_cont" class="modalClose_cont"><a href="#" class="modalClose_link" title="Cerrar ventana de aviso">CERRAR</a></div></div>',
     				closeClass: 'modalClose',
     				escClose: true
     			}
     		 );
     }
     else
     {
         //
         // Usuario y contraseña aceptados. Recargamos la página
         window.location.reload();
     }
 }
 if( xmlhttp.readyState == 4 && xmlhttp.status == 500 )
 {
 	if( document.getElementById( "mensajeLoginWeb" ) != undefined )
     	document.getElementById( "mensajeLoginWeb" ).style.display = "block";
 }
}
///
/// Callback de Ajax para la respuesta al logueo del usuario en ventana SimpleModal (Para bloque de login en página específica) [2][4][5][10]
///
function UserLoginSimpleModalPag( xmlhttp )
{
	if( xmlhttp.readyState == 4 && xmlhttp.status == 200 )
	{
		if( xmlhttp.responseText.substr( 0 , 2 ) != 'OK' ) 
	    {
	      //document.getElementById( "passwordLoginPag" ).value = "";
	      document.getElementById( "usuarioLoginPag" ).focus();
	      //
		  // SimpleModal (jQuery)
	      $.modal(
	     			"<div id='mensajeLoginSimpleModal' class='mensajeLoginSimpleModal'>" + xmlhttp.responseText + "</div>" ,
	     			{
	     				overlay: 30,
	     				overlayCss: { backgroundColor: "#fff" },
	     				focus: true,
	     				opacity: 60,
	     				dataCss: {},
	     				close: true,
	     				closeHTML: '<div id="modalClose"><div id="modalClose_cont" class="modalClose_cont"><a href="#" class="modalClose_link" title="Cerrar ventana de aviso">CERRAR</a></div></div>',
	     				closeClass: 'modalClose',
	     				escClose: true
	     			}
	     		 );
		  }
		  else
		  {
			  //
			  // Usuario y contraseña aceptados. Cargamos la url especificada y si no viene ninguna, la página principal [10]
			  if( xmlhttp.responseText.length > 2 )
			  {	 
				 cRespuesta = xmlhttp.responseText.split( ';' );
				 cUrl = cRespuesta[1]; 
				 window.location.replace( cUrl );
			  }
			  else
	    		 window.location.replace(window.location.protocol + "//" + window.location.host);
		  }
	}
	if( xmlhttp.readyState == 4 && xmlhttp.status == 500 )
	{
		if( document.getElementById( "mensajeLoginWebPag" ) != undefined )
	  	document.getElementById( "mensajeLoginWebPag" ).style.display = "block";
	}
}
///
/// Desconectar usuario
///
function UserLogout()
{
    AjaxRequest( app_BasePath + 'Modulos/usuariosweb/desconectar.php' , "" , CallbackLogoutUsuario );
}
///
/// CallBack de Ajax de desconexión de usuario
///
function CallbackLogoutUsuario( xmlhttp )
{
    if( xmlhttp.readyState == 4 && xmlhttp.status == 200 )
    {
        window.location.reload();
    }
}
//
// Oculta el aviso de usuario o contraseña incorrecta
//
function OcultarAviso()
{
	if( document.getElementById( "mensajeLoginWeb" ) != undefined )
    	document.getElementById( "mensajeLoginWeb" ).style.display = "none";
}
///
/// Crea un nuevo usuario
/// [1]
function CrearUsuarioWebEx()
{
	var cParameters = ComprobarCamposUsuarioWeb( false );
	if( cParameters )
		AjaxRequest( '../Modulos/usuariosWeb/crearUsuarioEx.php' , cParameters , CallBackCrearUsuarioWebEx );
	else return false;
}
///
/// CallBack de Ajax de creación de usuarios
///
function CallBackCrearUsuarioWebEx( xmlhttp )
{
	if( xmlhttp.readyState == 4 && xmlhttp.status == 200 )
	{
		if( xmlhttp.responseText.substr( 0 , 2 ) == 'OK' )
		{	
			document.getElementById( 'divFormAltaUsuarioWeb' ).innerHTML = '<div class="msgRespuestaUsuarioWeb" id="msgRespuestaAlta">' + xmlhttp.responseText.substr(3) + '</div>'; //[4]
		}
		else
		{							
			if( document.getElementById( 'msgUsuarioWeb' ) != undefined )
			{
				document.getElementById( 'msgUsuarioWeb' ).innerHTML = xmlhttp.responseText;
				document.getElementById( 'msgUsuarioWeb' ).style.display = "block";
			} 
		}
	}
}
///
/// Actualiza un usuario existente desde "Mi cuenta"
/// [1]
function ActualizarUsuarioWebEx()
{
	var cParameters = ComprobarCamposUsuarioWeb( true );
	if( cParameters )
		AjaxRequest( '../Modulos/usuariosWeb/actualizarUsuario.php' , cParameters , CallBackActualizarUsuarioWebEx );
	else return false;
}
///
/// CallBack de Ajax de actualización de usuarios
///
function CallBackActualizarUsuarioWebEx( xmlhttp )
{
	if( xmlhttp.readyState == 4 && xmlhttp.status == 200 )
	{
		if( xmlhttp.responseText.substr( 0 , 2 ) == 'OK' )
			cMensaje = "Los datos se han actualizado correctamente";
		else cMensaje = xmlhttp.responseText
		//							
		if( document.getElementById( 'msgUsuarioWeb' ) != undefined )
		{
			document.getElementById( 'msgUsuarioWeb' ).innerHTML = cMensaje;
			document.getElementById( 'msgUsuarioWeb' ).style.display = "block";
		} 
	}
}
///
/// Comprobación de los diferentes formularios de usuariosWeb
/// Devuelve la cadena de parámetros que se enviarán a la actualización, o false si hay campos incorrectos
/// Sólo comprueba los campos existentes en el formulario, salvo el correo electrónico que se comprueba siempre
/// [1]
function ComprobarCamposUsuarioWeb( lActualizarPassword )
{
	//
	// Obtener los datos del usuario
	var cMail = document.getElementById( 'email' ).value;
	var cMensaje = "";
	//
	// Si no hay campo de usuario, el usuario es el email 
	if( document.getElementById( 'usuario' ) )
		cUsuario = document.getElementById( 'usuario' ).value; 
	else cUsuario = cMail;
	var cParameters = 'usuario=' + urlEncode( cUsuario );
	//
	// Correo electrónico
	if ( !checkEmail( cMail ) ) 
	{
		cMensaje += 'Debe indicar una dirección de correo válida\n';
		document.getElementById( 'lblMail' ).style.color = "red";
		document.getElementById( 'email' ).focus();
	}
	else document.getElementById( 'lblMail' ).style.color = "black";
	cParameters += '&mail=' + urlEncode( cMail );
	//
	// Nombre
	if( document.getElementById( 'nombre' ) )
	{
		var cNombre = document.getElementById( 'nombre' ).value;
		if( cNombre.replace(/^\s*|\s*$/g , '') == '' || valorPorDefecto( cNombre ) ) 
		{
			cMensaje += 'Debe indicar el nombre\n';
			document.getElementById( 'lblNombre' ).style.color = "red";
			document.getElementById( 'nombre' ).focus();
		}
		else document.getElementById( 'lblNombre' ).style.color = "black";
		cParameters += '&nombre=' + urlEncode( cNombre );
	}
	//
	// Contraseña
	if( document.getElementById( 'password' ) )
	{		
		var cPassword = document.getElementById( 'password' ).value;
		var cPassword2 = document.getElementById( 'password2' ).value;
		if( cPassword.replace(/^\s*|\s*$/g , '') == '' || valorPorDefecto( cPassword ) )
		{
			//
			// Modo actualización de datos. Si la clave está vacía o es la por defecto, se entiende
			// que se quiere mantener la clave existente
			if( lActualizarPassword == true )
				cPassword = '';		
			else
			{
				cMensaje += 'El usuario debe tener una contraseña\n';
				document.getElementById( 'lblPassword' ).style.color = "red";
				document.getElementById( 'password' ).focus();
			}
		}
		else if ( cPassword  != cPassword2 )
		{
			cMensaje += 'La contraseña y su confirmación no coinciden\n';
			document.getElementById( 'lblPassword' ).style.color = "red";
			document.getElementById( 'password' ).focus();
		}
		else document.getElementById( 'lblPassword' ).style.color = "black";
		cParameters += '&password=' + urlEncode( cPassword );
	}
	//
	// Validación DNI/NIE
	if( document.getElementById( 'inputIdentificador' ) != undefined )
	{
		var cTipoIdentificador = "NIF"; //[9]
		if( document.getElementById( 'selectIdentificador' ) )
			cTipoIdentificador = document.getElementById( 'selectIdentificador' ).value; //[9]
		var cNif = document.getElementById( 'inputIdentificador' ).value;
		//
		if( valorPorDefecto( cNif ) ) //[11]
		{
			cParameters += '&nif='; //[11]
			document.getElementById( 'lblIdentificador' ).style.color = "black";
		}
		else
		{
			if( !checkNIF( cNif , cTipoIdentificador ) )
			{
				if( cTipoIdentificador == "NIF" )
					cMensaje += 'Introduzca su DNI. El NIF debe tener 8 dígitos y una letra, sin espacios ni ningún otro separador.\n'; //[11]
				else
					cMensaje += 'Introduzca su DNI. El NIE debe comenzar por X o Y, seguido de 7 dígitos y una letra, sin espacios ni ningún otro separador.\n'; //[11]
				document.getElementById( 'lblIdentificador' ).style.color = "red";
				document.getElementById( 'inputIdentificador' ).focus();
			}
			else
			{
				cParameters += '&nif=' + cNif;
				document.getElementById( 'lblIdentificador' ).style.color = "black";
			}
		}
	}
	//
	// Firma (Sólo si el foro está activo) [6]
	if( document.getElementById( 'textoFirma' ) != undefined )	
		cParameters += '&firma=' + urlEncode( tinyMCE.get( 'textoFirma' ).getContent() );
	//
	// Apellidos (Opcionales)
	if( document.getElementById( 'apellido1' ) )
	{
		cApellido1 = document.getElementById( 'apellido1' ).value; //[8]
		if( valorPorDefecto( cApellido1 ) ) //[8]
			cParameters += '&apellido1='; //[8]
		else
			cParameters += '&apellido1=' + document.getElementById( 'apellido1' ).value;
	}
	if( document.getElementById( 'apellido2' ) )
	{
		cApellido2 = document.getElementById( 'apellido2' ).value; //[8]
		if( valorPorDefecto( cApellido2 ) ) //[8]
			cParameters += '&apellido2='; //[8]
		else
			cParameters += '&apellido2=' + document.getElementById( 'apellido2' ).value;
	}
	//
	// Captcha
	if( document.getElementById( 'captcha' ) )
	{		
		var cCaptcha = document.getElementById( 'captcha' ).value;
		if ( cCaptcha.replace(/^\s*|\s*$/g , '') == '' || valorPorDefecto( cCaptcha ) )
		{
			cMensaje += 'Introduzca el texto de la imagen\n';
			document.getElementById( 'lblCaptcha' ).style.color = "red";
			document.getElementById( 'captcha' ).focus();
		}
		else document.getElementById( 'lblCaptcha' ).style.color = "black";
		cParameters += '&captcha=' + urlEncode( cCaptcha );
	}
	//
	// Adjuntamos los campos 'extra': lista de campo-valor separadas por '***': campo1***valor1***campo2***valor2***...
	var camposExtra = '';
	for ( i=0; i < document.form2.elements.length ; i++ )
	{
		//
		// Todos los nombres de los campos extra comienzan con _
		if( document.form2.elements[i].id.indexOf( '_' ) == 0 )
		{
			//
			// Comprobamos si el campo es obligatorio. Para ello, combrobamos que el último caracter
			// de la etiqueta del campo sea un *
			cIdElemento = document.form2.elements[i].id;
			lObligatorio = false;
			if( document.getElementById( "lblExtra" + cIdElemento ) )
			{
				cDescriCampo = document.getElementById( "lblExtra" + cIdElemento ).innerHTML;
				if( cDescriCampo.substr( cDescriCampo.length - 1  , 1 ) == "*" )
					lObligatorio = true;
			}  
			//
			// Añadimos nombre
			camposExtra += cIdElemento.substr( 1, cIdElemento.length ) + '***';
			//
			// Añadimos valor 
			if( document.form2.elements[i].type == 'textarea' )  // Si es un textarea
			{
				cValorCampo = tinyMCE.get( cIdElemento ).getContent() ;
				if( lObligatorio && ( cValorCampo.replace(/^\s*|\s*$/g , '') == '' || valorPorDefecto( cValorCampo ) ) )
				{
					cMensaje += 'Introduzca ' + cDescriCampo.substr( 0 , cDescriCampo.length - 1 ) + '\n';
					document.getElementById( "lblExtra" + cIdElemento ).style.color = "red";
				}	
				else if( document.getElementById( "lblExtra" + cIdElemento ) )
					document.getElementById( "lblExtra" + cIdElemento ).style.color = "black";
				//
				// Si el campo no es obligatorio y no se ha modificado el valor por defecto, grabarlo vacío
				if( !lObligatorio && valorPorDefecto( cValorCampo ) )
					camposExtra += ' ***';
				else camposExtra += urlEncode( cValorCampo ) + '***';
			}
			else if( document.form2.elements[i].type == 'checkbox' ) // Si es un check
			{
				var valorCheck = ( document.form2.elements[i].checked ) ? '1' : '0';
				camposExtra += valorCheck + '***';
			}
			else // Si es una caja de texto
			{
				cValorCampo = document.form2.elements[i].value;
				if( lObligatorio && ( cValorCampo.replace(/^\s*|\s*$/g , '') == '' || valorPorDefecto( cValorCampo ) ) )
				{
					cMensaje += 'Introduzca ' + cDescriCampo.substr( 0 , cDescriCampo.length - 1 ) + '\n';
					document.getElementById( "lblExtra" + cIdElemento ).style.color = "red";
				}	
				else if( document.getElementById( "lblExtra" + cIdElemento ) )
					document.getElementById( "lblExtra" + cIdElemento ).style.color = "black";
				//
				// Si el campo no es obligatorio y no se ha modificado el valor por defecto, grabarlo vacío
				if( !lObligatorio && valorPorDefecto( cValorCampo ) )
					camposExtra += ' ***';
				else camposExtra += urlEncode( cValorCampo ) + '***';
			}
		}
	}
	//
	// Si hay campos extra, eliminamos el último separador *** y los añadimos a la lista de parámetros
	if( camposExtra != '' )
		cParameters += '&camposExtra=' + camposExtra.substr( 0 , camposExtra.length - 3 );
	//
	// Mostrar errores de validación
	if ( cMensaje != "" )
	{
		if( document.getElementById( 'msgUsuarioWeb' ) != undefined )
		{
			document.getElementById( 'msgUsuarioWeb' ).innerHTML = cMensaje.replace(/\n/g, "<br />");
			document.getElementById( 'msgUsuarioWeb' ).style.display = "block";
		}
		else alert( cMensaje );
		return false;
	}
	else if( document.getElementById( 'msgUsuarioWeb' ) != undefined )
		document.getElementById( 'msgUsuarioWeb' ).style.display = "none";
	//
	return cParameters;
}
///
/// Recupera la clave del usuario
/// [3]
function RecuperarClave()
{
	var cParameters = ComprobarCamposUsuarioWeb();
	if( cParameters )
		AjaxRequest( '../Modulos/usuariosWeb/recuperarClave.php' , cParameters , CallBackRecuperarClave );
	else return false;
}
///
/// CallBack de Ajax de recuperación de clave
///
function CallBackRecuperarClave( xmlhttp )
{
	if( xmlhttp.readyState == 4 && xmlhttp.status == 200 )
	{
		if( xmlhttp.responseText.substr( 0 , 2 ) == 'OK' )
		{	
			document.getElementById( 'divFormAltaUsuarioWeb' ).innerHTML = '<div class="msgRespuestaUsuarioWeb" id="msgRespuestaRecuperar">' + xmlhttp.responseText.substr(3) + '</div>'; //[4]
		}
		else
		{							
			if( document.getElementById( 'msgUsuarioWeb' ) != undefined )
			{
				document.getElementById( 'msgUsuarioWeb' ).innerHTML = xmlhttp.responseText;
				document.getElementById( 'msgUsuarioWeb' ).style.display = "block";
			} 
		}
	}
}
/*
///
/// Función anónima que para todos los campos de texto con clase cajaTexto
/// se quite automáticamente el "Introduzca" al coger el foco y lo vuelva a poner al perderlo
/// Requerimientos iniciales: jQuery y campos con clase cajaTexto y valor inicial "Introduzca xxx"
/// [3][7]
///
var valoresPorDefecto = new Array();
$(function () {  
	$('.cajaTexto').focus( function (){
		if( valorPorDefecto(this.value) && typeof(valoresPorDefecto[this.id]) == "undefined")
			valoresPorDefecto[this.id] = this.value.substr(11) ;
		BorrarValorPorDefecto( this );
  });
	$('.cajaTexto').blur( function (){
		ValorContenido( this , valoresPorDefecto[this.id] );
  });
});
*/



