﻿/*
FUNCIONES PARA REALIZAR PETICIONES AJAX
*/
var XMLHttpFactories = [
	function() { return new XMLHttpRequest() },
	function() { return new ActiveXObject("Msxml2.XMLHTTP") },
	function() { return new ActiveXObject("Msxml3.XMLHTTP") },
	function() { return new ActiveXObject("Microsoft.XMLHTTP") }
];


function sendRequest(url, callback, postData, params) {
	var cache = new Date().getTime();
	var req = createXMLHTTPObject();
	if (!req) return;
	var method = (postData) ? "POST" : "GET";
	req.open(method, url, true);
  	req.setRequestHeader("User-Agent", "XMLHTTP/1.0");
	if (postData) {
		postData += '&date=' + cache;
		
		req.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8");
	}
	req.onreadystatechange = function () {
		if (req.readyState != 4) return;
		if (req.status != 200 && req.status != 304) {
			alert('HTTP error ' + req.status);
			return;
		}
		if (params && params.length > 0)
			callback(req, params);
		else
			callback(req);
	}
	if (req.readyState == 4) return;
	req.send(postData);
}


function createXMLHTTPObject() {
	var xmlhttp = false;
	for (var i=0; i < XMLHttpFactories.length; i++) {
		try {
			xmlhttp = XMLHttpFactories[i]();
		}
		catch (e) {
			continue;
		}
		break;
	}
	return xmlhttp;

}

/*FUNCIONES PROPIAS QUE SE LANZAN AL REALIZAR PETICION AJAX*/
function handleRequestAcceso(req) {

	
	var response = eval("(" + req.responseText + ")");
	switch (response.usuario.id) {
		case '-1':
			$("#Listado").html(response.usuario.msg);
			alert(response.usuario.msg);
			break;
		case '0':
			$("#Listado").html(response.usuario.nombre+' '+response.usuario.email);
			
			break;
		default:
			// Acceso a la aplicación
			$('#ListadoProjects').html('&nbsp;');
			$("#Listado").html(response.usuario.nombre+' '+response.usuario.msg);
			$("#Login").html(response.usuario.nombre+' '+response.usuario.email+'&nbsp;&nbsp;<a href="#" id="logout">Cancelar sesión</a>');
			$("#logout").click(function (){logout(document,'http://www.anunciosmvm.com');});
			$("#PROY_ID").val(response.usuario.proyecto);
			// Acceso a la aplicación por defecto siempre empezamos por listado de anuncios
			CargaIndicador('ANUNCIOS',document.forms[0]);
			break;
	}
	return true;
}

/*
DEVUELVE LOS LISTADOS EN FUNCION DEL INDICADOR
ASIGNA EVENTOS A ELEMENTOS, DEPENDIENDO DEL INdICADOR
*/
function handleRequestList(req,idpadre) {
	
	var response = req.responseText;
	var Groupby = new String();
	
	$("#Listado").animate({height:100,opacity: 'show'}, "slow",$("#Listado").html(response));
	
	switch ($("#INDICADOR").val()) {
		
		case 'ANUNCIOS':
			// Selectores y eventos para el listado
			
			$(".SelectAction").click(function (){SelectChk(this.id);});
			$(".ToActionDestacar").click(function (){DestacarAnuncio_CHK(this.id);});
			$(".ToActionState").click(function (){CambiarEstado_CHK(this.id);});
			
			// Eventos individuales para los registros
			$(".Destacar").click(function (){DestacarAnuncio(this.id);});
			$(".Actualizar").click(function (){CambiarEstado(this.id);});
			$(".Edit").click(function (){EditarAnuncio(this.id);});
			$(".EmailAnuncio").click(function (){UsuarioAnuncio(this.id);});
			$(".MensajesAnuncio").click(function (){MensajesAnuncio(this.parentNode.id)});
			$(".potato").click(function (){
				if (this.src=='http://www.anunciosmvm.com/Images/potato.png'){
					// No permito que haya mas de una ventanta abierta
					$(".potato").each(function(i){CambiaClase(this.id,'REG_AUX','POTATO_LINEA','on_aux'); $("#"+this.id).attr("src","/Images/potato.png");});
					CambiaClase(this.id,'REG_AUX','POTATO_LINEA','off_aux','on_aux');
					$("#"+this.id).attr("src","/Images/potatoAnimado.gif");
				}
				else{
					CambiaClase(this.id,'REG_AUX','POTATO_LINEA','on_aux');
					$("#"+this.id).attr("src","/Images/potato.png");
				}
			});
			$(".Sel_Chk").click(function (){
				if (this.checked){CambiaClase(this.id,'REG_','CHK_LINEA_','off','on');}
				else{CambiaClase(this.id,'REG_','CHK_LINEA_','on','off');}
				
	 			$('#Num_Sel').html(SumRegistros()+' seleccionados');
			});
			
			$("#toolbarGraph").css("font-weight","normal");
			$('#toolbarGraph').click(function (){DisplayToolbar(this);});
			$('#toolbarData').click(function (){DisplayToolbar(this);});
			$(".ToSendMail").click(function (){DisplaySendMail();});
			$(".PAGINA").click(function (){LanzarConsulta(document.forms[0],null,null,this.id.substring(7));});
			
			
			
			/* funciones al cargar el listado de anuncios */
			
			if (!document.getElementById('Buscador')){Buscador(idpadre);}
			$("#BarraEstado").html("&nbsp;");
			
			
			if ($("#GROUPBY").val()==null){
				if ($("#PROY_ID").val()=='HosP') Groupby='IDCATEGORIA';
				else Groupby='ANOS';
			} 
			else Groupby=$("#GROUPBY").val();
			
			RecargaEstadisticas(Groupby);
			
			$("#CloseStatistics").click(function(){
				if ($("#CloseStatistics").text()=='Cerrar'){
					$("#CloseStatistics").text('Abrir');
					$("#Result_estad_table").slideUp("slow");
					
				}
				else{
					 $("#CloseStatistics").text('Cerrar');
					 $("#Result_estad_table").slideDown("slow");
				}
				}
			);
			
			break;
		case 'USUARIOS':
			// Selectores y eventos para el listado
			$(".SelectAction").click(function (){SelectChk(this.id);});
			$(".ToActionState").click(function (){CambiarEstado_Usuario_CHK(this.id);});
			$(".ToSendMail").click(function (){DisplaySendMail();});
			$(".ToActionNLState").click(function (){NewsLetter_CHK(document.forms[0],this.id);});
			$(".Usuario_clave").click(function (){MuestraClave(this.id)});
			$(".AnunciosUSuario").click(function (){AnunciosUsuario(this.parentNode.id)});
			$(".MensajesUSuario").click(function (){MensajesUsuario(this.parentNode.id)});
			$(".Edit").click(function (){EditarUsuario(this.id);});
			
			// Eventos individuales para los registros
			$(".Actualizar").click(function (){CambiarEstado_Usuario(this.id);});
			$(".potato").click(function (){
				if (this.src=='http://www.anunciosmvm.com/Images/info-usuario.png'){
					// No permito que haya mas de una ventanta abierta
					$(".potato").each(function(i){CambiaClase(this.id,'REG_AUX','POTATO_LINEA','on_aux'); $("#"+this.id).attr("src","/Images/info-usuario.png");});
					CambiaClase(this.id,'REG_AUX','POTATO_LINEA','off_aux','on_aux');
					$("#"+this.id).attr("src","/Images/potatoAnimado.gif");
				}
				else{
					CambiaClase(this.id,'REG_AUX','POTATO_LINEA','on_aux');
					$("#"+this.id).attr("src","/Images/info-usuario.png");
				}
			});
			
			$(".Newsletter").click(function (){EstadoNewsletter(this.id,this.alt);});
			
			if (!document.getElementById('Buscador')){Buscador(idpadre);}
			
			$(".PAGINA").click(function (){LanzarConsulta(document.forms[0],null,null,this.id.substring(7));});
			$("#BarraEstado").html("&nbsp;");
			
			if ($("#GROUPBY").val()==null) Groupby='ANOS';
			else Groupby=$("#GROUPBY").val();
						
			RecargaEstadisticas(Groupby);
			
			$("#CloseStatistics").click(function(){
				if ($("#CloseStatistics").text()=='Cerrar'){
					$("#CloseStatistics").text('Abrir');
					$("#Result_estad").slideUp("slow");
					
				}
				else{
					 $("#CloseStatistics").text('Cerrar');
					 $("#Result_estad").slideDown("slow");
				}
				}
			);
			
			$('#toolbarGraph').click(function (){DisplayToolbar(this);});
			$("#toolbarGraph").css("font-weight","normal");
			$('#toolbarData').click(function (){DisplayToolbar(this);});
			
			break;
		case 'MENSAJES':
			
			// Eventos individuales para los registros
			$(".EmailAnuncio").click(function (){UsuarioAnuncio(this.id);});
			
			$(".potato").click(function (){
				if (this.src=='http://www.anunciosmvm.com/Images/i-email.gif'){
					// No permito que haya mas de una ventanta abierta
					$(".potato").each(function(i){CambiaClase(this.id,'REG_AUX','POTATO_LINEA','on_aux'); $("#"+this.id).attr("src","/Images/i-email.gif");});
					CambiaClase(this.id,'REG_AUX','POTATO_LINEA','off_aux','on_aux');
					$("#"+this.id).attr("src","/Images/email.png");
				}
				else{
					CambiaClase(this.id,'REG_AUX','POTATO_LINEA','on_aux');
					$("#"+this.id).attr("src","/Images/i-email.gif");
				}
			});
			
			//$(".EmailAnuncio").click(function (){UsuarioAnuncio(this.id);});
			
			$(".PAGINA").click(function (){LanzarConsulta(document.forms[0],null,null,this.id.substring(7));});
			
			if (!document.getElementById('Buscador')){Buscador(idpadre);}
			
			$("#BarraEstado").html("&nbsp;");
			if ($("#GROUPBY").val()==null) Groupby='ANOS';
			else Groupby=$("#GROUPBY").val();
			
			RecargaEstadisticas(Groupby);
			$("#CloseStatistics").click(function(){
				if ($("#CloseStatistics").text()=='Cerrar'){
					$("#CloseStatistics").text('Abrir');
					$("#Result_estad").slideUp("slow");
					
				}
				else{
					 $("#CloseStatistics").text('Cerrar');
					 $("#Result_estad").slideDown("slow");
				}
				}
			);
			$("#toolbarGraph").css("font-weight","normal");
			$('#toolbarGraph').click(function (){DisplayToolbar(this);});
			$('#toolbarData').click(function (){DisplayToolbar(this);});
			break;
		default:
			alert('inicio parametros no se ha inicializado');
			break;
	}
	return false;
}


/*
CARGA EL BUSCADOR AJAX
*/
function handleRequestFilt(req,idpadre){
	
	var response = req.responseText;
	var ElementBuscador = document.getElementById("Filtros");	

	$("#Filtros").html(response);

	

	$("#IDPAIS").after('<select name="IDPROVINCIA" id="IDPROVINCIA"><option value="-1" selected="selected">[Selecciona Provincia]</option></select>');
	$('#Filtros').animate({height:200}, "fast");
	$("#IDPAIS").change(function (){SeleccionaProvincia(this.value)});
	$("#ID1").change(function (){SeleccionaSubCategoria(this.value,'ID1','ID2')});
	$("#ID2").change(function (){SeleccionaSubCategoria(this.value,'ID2','ID3')});
	$("#ID3").change(function (){SeleccionaSubCategoria(this.value,'ID3','ID4')});
	$("#IDINDICADOR").change(function (){CargaIndicador(this.value,document.forms[0])});
	$(".calendar").click(function(){getPopUpDate(this.id)});
	$(".reset").click(function(){RestoreDate(this.id)});
	/*
	$("#SQLQuery").click(function (){
		if (this.title=='Ver sql'){this.title='Ocultar sql';$("#List_SQL").show();}
		else{this.title='Ver sql';$("#List_SQL").hide();}
	});*/
	
	$("#BUSQUEDA_TEXTO").click(function (){this.value='';});
	$("#SearchBottom").click(function (){
		$("#IDPADRE").val('');
		LanzarConsulta(document.forms[0]);
	});
	
	
	
	if(typeof idpadre != 'undefined'){
		  if ($("#INDICADOR").val()=='ANUNCIOS') $('#BUSQUEDA_TEXTO').val($("#EMAIL_"+idpadre).text());
		  if ($("#INDICADOR").val()=='USUARIOS') $('#BUSQUEDA_TEXTO').val($("#EMAIL_"+idpadre).text());
		  if ($("#INDICADOR").val()=='MENSAJES') $('#BUSQUEDA_TEXTO').val($("#EMAIL_"+idpadre).text());
	}
	
	return true;
}

function handleRequestEstadisticas(req,display){

	
	var response = eval("(" + req.responseText + ")");
	var Resultados = new String('');
	
	var count=0;
	
	var Identificador=new Array();
	var Nombres=new Array();
	var Identificador_padre=new Array();
	var Nombres_padre=new Array();
	var Totales=new Array();
	
	var Identificador_aux=new Array();
	var Nombres_aux=new Array();
	var Identificador_padre_aux=new Array();
	var Nombres_padre_aux=new Array();
	var Totales_aux=new Array();
	
	Identificador[0]='0';
	Nombres[0]='0';
	Totales[0]='0';
	Identificador_padre[0]='0';
	Nombres_padre[0]='0';
	
	var Existe=0;
	
	var count_array=0;
	
	
	var Action_filtro="http://www.anunciosmvm.com/filtro_estadisticas.xsql";
	var post_filt='INDICADOR='+response.Resultados[0].resultado.indicador;
	
	var TipoGraf=response.Resultados[0].resultado.groupby_id;

	if (response.Resultados[0].resultado.total>0){
		var TotalElementos=response.Resultados.length;
		var Groupby = response.Resultados[0].resultado.groupby_id;
		for (var i=0; i < response.Resultados.length; i++) {
			
			Identificador_aux=response.Resultados[i].resultado.id.split('|');
			Nombres_aux=response.Resultados[i].resultado.nombre.split('|');
			Totales_aux=response.Resultados[i].resultado.total;
			Identificador_padre_aux=response.Resultados[i].resultado.id_padre;
			Nombres_padre_aux=response.Resultados[i].resultado.nombre_padre;
			
			
			for (var k=0;k<Identificador_aux.length; k++){
			        Existe=ExisteEnArray(Identificador_aux[k],Identificador);
				if (Existe==-1) {
					count_array=Identificador.length;
					Identificador[count_array]=Identificador_aux[k];
					Nombres[count_array]=Nombres_aux[k];
					Totales[count_array]=Totales_aux;
					Identificador_padre[count_array]=Identificador_padre_aux;
					Nombres_padre[count_array]=Nombres_padre_aux;
				}
				
				else{Totales[Existe]=parseInt(Totales[Existe])+parseInt(Totales_aux);}
			}
		}
		
		
		Resultados=Resultados+'<ul id="ul_'+Groupby+'">'
		
		for (var j=0;j<Identificador.length; j++){
			if (Identificador[j]!='0'){
				if (Nombres[j]) Resultados =Resultados+'<li title="'+Identificador_padre[j]+'" class="li_estadis"  id="ESTADIS_'+Identificador[j]+'">'+Nombres[j]+'&nbsp;(<span class="TotalEstadis">'+Totales[j]+'</span>)</li>';
				else Resultados =Resultados+'<li title="'+Identificador_padre[j]+'" class="li_estadis_error"  id="ESTADIS_'+Identificador[j]+'">'+Identificador[j]+'&nbsp;(<span class="TotalEstadis">'+Totales[j]+'</span>)</li>';
			}
		}
		
		Resultados=Resultados+'</ul>'
		
		if (count==1) Resultados =Resultados+'</div>';
		$("#Result_estad").html(Resultados);
	
		$(".li_estadis").click(function (){LanzarConsulta(document.forms[0],this.id.substring(8),this.parentNode.id.substring(3));});
		$(".li_estadis_error").click(function (){LanzarConsulta(document.forms[0],this.id.substring(8),this.parentNode.id.substring(3));});

		sendRequest(Action_filtro,handleRequestFiltoEstadisticas,post_filt,Groupby);
	}
	else{
		Resultados=Resultados+'<ul>Sin Resultados</ul>';
		$("#IndicardorEstadis").html("&nbsp;");
		$("#Result_estad").html(Resultados);
	}

      google.setOnLoadCallback(drawVisualization(TotalElementos,Nombres,Totales,Groupby));

}

 function drawVisualization(TotalElementos, Nombres, Totales, Groupby){
 

 	if (Groupby == 'ANOS' || Groupby == 'MESES' || Groupby == 'DIAS') {
	 // Create and populate the data table.
        var data = new google.visualization.DataTable();
        data.addColumn('string', 'x');
        data.addColumn('number', 'Anuncios');
		
		for (var j = 1; j <= TotalElementos; j++) {
			data.addRow([Nombres[j], parseInt(Totales[j])]);
		}
       
       
        // Create and draw the visualization.
        new google.visualization.LineChart(document.getElementById('visualization')).
            draw(data, {curveType: "function",
                        width: 800, height: 200,
                        vAxis: {maxValue: 10}}
      );
      

 	}
 	else {
 		// Create and populate the data table.
		var data = new google.visualization.DataTable();
		data.addColumn('string', 'Anuncios');
		data.addColumn('number', 'Estado');
		data.addRows(TotalElementos);
			
		for (var j = 1; j <= TotalElementos; j++) {
			data.setValue(j - 1, 0, Nombres[j]);
			data.setValue(j - 1, 1, parseInt(Totales[j]));
		}
		// Create and draw the visualization.
		new google.visualization.PieChart(document.getElementById('visualization')).draw(data, {
			title: "Estado de los anuncios"
		});
	}
}


function handleRequestFiltoEstadisticas(req,groupby){
	
	var response = eval("(" + req.responseText + ")");
	var Resultados = new String('');
	
	Resultados="<select name='GROUPBY' id='GROUPBY' onchange='RecargaEstadisticas(this.value)'>";
	for (var i=0; i < response.Filtros.length-1; i++) {
		if(response.Filtros[i].GroupBy.id==groupby) {
			Resultados =Resultados+' <option value="'+response.Filtros[i].GroupBy.id+'" selected="selected">'+response.Filtros[i].GroupBy.nombre+'</option>';
		}
		else{
			Resultados =Resultados+' <option value="'+response.Filtros[i].GroupBy.id+'">'+response.Filtros[i].GroupBy.nombre+'</option>';
		}
	}
	
	Resultados =Resultados+'</select>';
	$("#GroupBy").html(Resultados);
	$("#IndicardorEstadis").html("&nbsp;");
	return true;
}

// Selecciona Provincia a partir de Pais
function handleRequestSelProv(req){

	var response = eval("(" + req.responseText + ")");
	var Resultados = new String('');
	
	Resultados="<select name='IDPROVINCIA' id='IDPROVINCIA' onchange='SeleccionaPoblacion(this.value)'>";
	for (var i=0; i < response.Provincias.length; i++) {
		
		if (response.Provincias[i].Provincia.id!='-1'){
			if (arguments[1]){
				if (response.Provincias[i].Provincia.id==arguments[1]){
					Resultados =Resultados+' <option value="'+response.Provincias[i].Provincia.id+'" selected="selected">'+response.Provincias[i].Provincia.nombre+'</option>';
				}
			}
			
			Resultados =Resultados+' <option value="'+response.Provincias[i].Provincia.id+'">'+response.Provincias[i].Provincia.nombre+'</option>';
		}
	}
	
	Resultados =Resultados+'</select>';
	$("#IDPROVINCIA").remove();
	$("#IDPAIS").after(Resultados);
	
	return true;
}

// Selecciona Provincia a partir de Pais
function handleRequestSelPobl(req){

	var response = eval("(" + req.responseText + ")");
	var Resultados = new String('');
	
	Resultados="<select name='IDPOBLACION' id='IDPOBLACION'>";
	for (var i=0; i < response.Poblaciones.length; i++) {
		
		if (response.Poblaciones[i].Poblacion.id!='-1'){
			if (arguments[1]){
				if (response.Poblaciones[i].Poblacion.id==arguments[1]){
					Resultados =Resultados+' <option value="'+response.Poblaciones[i].Poblacion.id+'" selected="selected">'+response.Poblaciones[i].Poblacion.nombre+'</option>';
				}
			}
			
			Resultados =Resultados+' <option value="'+response.Poblaciones[i].Poblacion.id+'">'+response.Poblaciones[i].Poblacion.nombre+'</option>';
		}
	}
	
	Resultados =Resultados+'</select>';
	
	$("#IDPOBLACION").remove();
	$("#IDPROVINCIA").after(Resultados);
	
	return true;
}

// Selecciona subcategoria a partir de categoria
function handleRequestSelCat(req,catactual){
	
	var response = eval("(" + req.responseText + ")");
	var Resultados = new String('');
	
	Resultados="<select name='"+response.Filtros[0].nivel+"' id='"+response.Filtros[0].nivel+"' onchange='SeleccionaSubCategoria(this.value)'>";
	for (var i=1; i < response.Filtros.length; i++) {
		Resultados =Resultados+' <option value="'+response.Filtros[i].Fitro.id+'">'+response.Filtros[i].Fitro.nombre+'</option>';
	}
		
	Resultados =Resultados+'</select>';
	$("#"+catactual).after(Resultados);
	
	return true;
}

function handleRequestClave(req,elemento){
	var response = req.responseText;
	$("#"+elemento).html(response);
}

// Destaca o quita destacado de un anuncio
function handleRequestDestacado(req) {
	
	var response = eval("(" + req.responseText + ")");
	var Element=$("#DEST_"+response.anuncio.idanuncio);
	
	switch (response.anuncio.destacado) {
		case 'S':
			Element.attr("src","/Images/star_si_2.gif");
			Element.attr("alt","Destacado");
			break;
		case 'N':
			Element.attr("src","/Images/star_no_2.gif");
			Element.attr("alt","Sin destacar");
			break;
		default:
			alert(response.anuncio.destacado);
			break;
	}
	return false;
}

// Cambio estado de registros
function handleRequestEstado(req,Actual) {
	var response = eval("(" + req.responseText + ")");
	var Element=$("#EST_"+response.anuncio.idanuncio);
	var New_Estado=response.anuncio.estado;
	
	// DE C a P // DE P a F // DE F a B // DE B a C
	switch (New_Estado) {
		
		case 'P':
			Element.attr("src","/Images/apto.gif");
			Element.attr("alt","Parado");
			break;
		case 'F':
			Element.attr("src","/Images/Ambar.gif");
			Element.attr("alt","Finalizado");
			break;
		case 'B':
			Element.attr("src","/Images/Rojo.gif");
			Element.attr("alt","Borrado");
			break;
		case 'C':
			Element.attr("src","/Images/Verde.gif");
			Element.attr("alt","Activo");
			break;
		default:
			alert(response.anuncio.estado);
			break;
	}
	return false;
}


// Cambio estado de usuarios
function handleRequestEstadoUsuario(req,Actual) {
	
	var response = eval("(" + req.responseText + ")");
	var Element=$("#EST_"+response.usuario.idusuario);
	var Element_NL=$("#NL_"+response.usuario.idusuario);
	
	var New_Estado=response.usuario.estado;
	
	if (response.usuario.res=="1"){
		switch (New_Estado) {
			case 'B':
				Element.attr("src","/Images/Rojo.gif");
				Element.attr("alt","Borrado");
			
				Element_NL.attr("src","/Images/newsletter-no.jpg");
				Element_NL.attr("alt","Desactivado");
				$("#REG_AUX_AUX3_"+response.usuario.idusuario).html(response.usuario.fecha);
			
				break;
			case 'C':
				Element.attr("src","/Images/Verde.gif");
				Element.attr("alt","Activo");
				
				Element_NL.attr("src","/Images/newsletter.jpg");
				Element_NL.attr("alt","Activado");
			
				$("#REG_AUX_AUX3_"+response.usuario.idusuario).html(response.usuario.fecha);
			
				break;
			default:
				alert(response.usuario.estado);
				break;
		}
	}
	else{	
		alert(response.usuario.msg);
	}
	return false;
}


function handleRequestMsg(req,ultimo) {
	var response = eval("(" + req.responseText + ")");

	if (ultimo=='S' && document.getElementById('FormSendMail')) $("#SendMailResults").html('&nbsp;');
	
	if (document.getElementById('FormMessageBody'))$("#FormMessageBody").html(response.mail.estado+' '+response.mail.msg.split('.')[0]);
	if (document.getElementById('FormSendMail')){$("#FormSendMail").append(response.mail.usuario+' '+response.mail.estado+'<br/>');};
	
	
	if (ultimo=='S' && document.getElementById('FormSendMail')){
		$("#FormSendMail").append('<br/><br/>Proceso finalizado<br/>');
		$("#SendMailResults").html('&nbsp;');
	} 
	return false;
}

function handleRequestFormUserDisplay(req,element) {
	
	// Abrimos opcion escogida en el menu
	$(req.responseText).insertAfter("#"+element).slideDown("slow");
	
	//Inicializamos textarea de comentario
	
	$(".AddComentTxtArea").val($("#REG_AUX_AUX4_"+element.substring(12)).text());
	
	// Eventos de opciones menu usuario
	$("#SUBMIT_COMMENT").click(function (){SubmitComment();return false;});
	$("#SUBMIT_SPAM").click(function (){SubmitSpammer();return false;});
	$("#SUBMIT_SPAM").click(function (){SubmitSpammer();return false;});
	$("#TITULO_MSG").click(function (){$("#TITULO_MSG").val('');});
	$("#SUBMIT_MSG").click(function (){SubmitMessage();return false;});
	$("#SUBMIT_PASSWORD").click(function (){SubmitPassword();return false;});
	
	$("#CLOSE_COMMENT").click(function (){CloseWindow('FormCommentBody','class');return false;});
	$("#CLOSE_SPAM").click(function (){CloseWindow('FormSpammerBody','class');return false;});
	$("#CLOSE_MSG").click(function (){CloseWindow('FormMessageBody','class');return false;});
	$("#CLOSE_PASSWORD").click(function (){CloseWindow('FormPasswordBody','class');return false;});
	
	// Inicializamos el campo hidden user id.
	if (document.getElementById("Spam_UserID"))$("#Spam_UserID").val(element.substring(13));
	if (document.getElementById("Comment_UserID"))$("#Comment_UserID").val(element.substring(12));
	if (document.getElementById("Message_UserID"))$("#Message_UserID").val(element.substring(13));
	if (document.getElementById("Pass_UserID"))$("#Pass_UserID").val(element.substring(13));
	
	return false;
}

function handleRequestFormUserSpam(req,IDUSUARIO){
	var response = eval("(" + req.responseText + ")");
	var Element=$("#FormSpammerBody");
	Element.html(response.spammer.result+'&nbsp;&nbsp;&nbsp;&nbsp;<a href="#" id="CLOSE_MSG" onclick="CloseWindow(\'FormSpammerBody\',\'class\')>Close</a>');
	if (response.spammer.valor==1) {CambiarEstado_Usuario("EST_"+response.spammer.idusuario);}
	return false;
}

function handleRequestFormUserComment(req,IDUSUARIO){
	var response = eval("(" + req.responseText + ")");
	var Element=$("#FormCommentBody");
	Element.html(response.usuario.result+'&nbsp;&nbsp;&nbsp;&nbsp;<a href="#" id="CLOSE_MSG" onclick="CloseWindow(\'FormCommentBody\',\'class\')>Close</a>');
	$("#REG_AUX_AUX4_"+IDUSUARIO).html(response.usuario.comentario);
	return false;
}

function handleRequestFormUserPassword(req,IDUSUARIO){
	var response = eval("(" + req.responseText + ")");
	var Element=$("#FormPasswordBody");
	Element.html(response.usuario.result+'&nbsp;&nbsp;&nbsp;&nbsp;<a href="#" id="CLOSE_PASSWORD" onclick="CloseWindow(\'FormPasswordBody\',\'class\')>Close</a>');
	return false;
}

function handleRequestFormUserNewsletter(req,IDUSUARIO){
	var response = eval("(" + req.responseText + ")");
	var NuevoEstado = response.usuario.newsletter;
	var Element_NL = $("#NL_"+IDUSUARIO);
	
	switch (NuevoEstado) {
		case 'N':
			Element_NL.attr("src","/Images/newsletter-no.jpg");
			Element_NL.attr("alt","Desactivado");
		
			break;
		case 'S':
			Element_NL.attr("src","/Images/newsletter.jpg");
			Element_NL.attr("alt","Activado");
		
		
			break;
		default:
			alert(response.usuario.result);
			break;
	}
	return false;
	
}

