function LogarUsuario(Usuario, Password){

	var Usuario = Usuario || $("#formLog>#lg_usuario").val();
	var Password = Password || $("#formLog>#lg_password").val();

	$.ajax({
		async:		false,
		cache:		false,
		type:		"GET",		
		url:		"/zona_usuario/login/ajax_logar.asp",
		data:		"usuario=" + Usuario + "&password=" + Password,
		beforeSend: function(){
			$("#auxLogin").html("<img src='/comunes/imagenes/spinner.gif' />&nbsp;Conectando...");
			$("#frmLogin").toggle();
			$("#auxLogin").toggle();
		},
		success:	function(html){
			AjustesPorLogarUsuario(html);
			
			$("#auxLogin").toggle();
			$("#otros_enlaces>a:contains('Gratis')").prev("span").remove();
			$("#otros_enlaces>a:contains('Gratis')").remove();
		},
		error:		function(XMLHttpRequest, textStatus, errorThrown){					
			$("#auxLogin").toggle();
			$("#frmLogin").toggle();
			if(XMLHttpRequest.status >= 800 && XMLHttpRequest.readyState == 4)
				if(XMLHttpRequest.status == 903){
					ListarSesionesActivas();
				}else{						
					alert(XMLHttpRequest.statusText);
				}
			else
				alert("Error logando usuario.");

		}
	});
}

function AjustesPorLogarUsuario(html){

	var appURL = unescape(location.pathname.substr(0,15));
	if(appURL == "/servicios_n/"){
		
		UsuarioLogado = true;
		
		var Contenedor = "";
		if($("div#sb-container:visible").length > 0){
			Contenedor = "div#sb-container ";
		}
		
		if($("#cabecera_usuario").length > 0){
			$("#cabecera_usuario").html(html);
		}else{
			if($("#formLog").length > 0){
				$("#formLog").remove();
				$("#cont_enlaces_cab").prepend(html);
			}					
		}
		
		var obj_li_activo = document.getElementById($(Contenedor + ".previa_documento:first").parents("li").children(".doc_descripcion").attr("id"));
		
		if(obj_li_activo == null){
			obj_li_activo = document.getElementById($(Contenedor + ".previa_documento:first").prev().attr("id"));//legislación
		}
		
		if(obj_li_activo != null){
			if(obj_li_activo.id.substr(0, 7).toUpperCase() == "SP/LEG/"){
				var aElemPrevias = new Array;
				$(".previa_documento").each(function(){
					obj_li_activo = document.getElementById($(this).prev().attr("id"));
					if(obj_li_activo == null){ //Resultado de buscar legislación
						obj_li_activo = document.getElementById($(this).find(".previa_documento").prev().attr("id"));
					}else{
						obj_li_activo = document.getElementById($(this).prev().attr("id"));
					}
					if($.inArray(obj_li_activo, aElemPrevias) == -1) //evita repetidos
						aElemPrevias.push(obj_li_activo);
				});
				aElemPrevias.forEach(function(Elem){
					$(Elem).next(".previa_documento").remove();
				});
				aElemPrevias.forEach(function(Elem){
					VerDocumentoInline(Elem);
				});
			}else{
							
				var aElemDocDesc = new Array;
				$(".previa_documento").each(function(i, obj){
					var aElem = $(obj).prevAll(".doc_descripcion").get();
					$.each(aElem, function(i, oElem){
						aElemDocDesc.push(oElem);
					});							
					$(obj).remove();
				});
				
				$(aElemDocDesc).each(function(i, obj){							
					VerDocumentoInline(obj);
				});					

			}
		}

		if($("div#frmFormTel").length > 0){
			BuscadorAjustarServicio(13, $("#b_servicios a[rel='13']").html());
		}
		
		if($("div#frmDocumentacion").length > 0){
			BuscadorAjustarServicio(14, $("#b_servicios a[rel='14']").html());
		}
		
		if($("div#contenido_utilidades").length > 0){
			BuscadorAjustarServicio($("div#cont_titulo_utilidades").attr("rel"), $("#b_servicios a[rel='" + $("div#cont_titulo_utilidades").attr("rel") + "']").html());
		}
		
		if($("div#frmConsulta").length > 0){
			MostrarFormularioConsultaNueva();
		}
		
		if($("div#contenido_carpetas").length > 0){
			CargarFavoritos();
		}
		
		if($("ul#listado_consultas_cliente").length > 0){
			if(qs_id_consulta_cliente != "")
				ListadoConsultasCliente(qs_id_consulta_cliente, qs_tipo_consulta_cliente);
			else
				ListadoConsultasCliente(undefined, 'Consulta');
		}
		
		if($("#contenido_promo_demo_10_dias").length > 0){
			location.reload();
		}
		
		CargarZonaMaterias();
		
//				//si se ha logado desde un boletín, quita el aviso de ánimo para logarse.
//				$("#imgAvisoInicioSesion").remove();
//				if($("div#zona_derecha_boletin").length > 0){
//				    $("#lnk_gestor_boletines").remove();
//				    CargarZonaDerechaBoletines();
//					$("#aviso_login_boletin").remove();
//				}
			
		/* PENDIENTE: No hay que averiguar si está en consultas por el parámetro, si no por si 
					  hay un contenedor de consultas. como en documentos.
		if((qsIdConsultaCliente != "") && (IdTipoServicio == 1000))
			ListadoConsultasCliente(qsIdConsultaCliente);
		*/

	}else{
		location.reload();
	}
}

function ListarSesionesActivas(){
	VentanaModalAjax('vGestorSesiones', '/sistema/sesiones/ajax_listar_sesiones.asp', 'Listado de sesiones abiertas');
//	var T = setTimeout("CerrarVentanaModal('vGestorSesiones')", 10000);
//	$("#fondo_modal_vGestorSesiones, #btnCancelarGS").click(function(){
//		clearTimeout(T);
//	});
}

function TerminarSesion(IdSesion){

	$.ajax({
		type: "GET", 
		url: "/sistema/sesiones/ajax_terminar_sesion.asp",
		data: "id_sesion=" + IdSesion,
		cache: false,
		async: false,
		success: function(html){
			AjustesPorLogarUsuario(html);
			CerrarVentanaModal('vGestorSesiones');
		},
		error:		function(XMLHttpRequest, textStatus, errorThrown){					
			$("#auxLogin").toggle();
			$("#frmLogin").toggle();
			if(XMLHttpRequest.status >= 800 && XMLHttpRequest.readyState == 4){
				if(XMLHttpRequest.status == 901){
					CerrarVentanaModal('vGestorSesiones');
				}
				alert(XMLHttpRequest.statusText);
			}else
				alert("Error Terminando la sesión.");

		}
	});

}
