
function AbrirURL(URL){
	window.open(URL);
}

function VerDocumento(ref, carpeta){

	if(UsuarioLogado == false && DocumentoAccesoPago(ref) == true){
		alert("Para acceder a este apartado tienes que iniciar sesión.\nIntroduce tu usuario y clave en la parte superior derecha.");
		return;
	}

	if(carpeta){
		Shadowbox.open({
			content:	"/visor/default.asp?referencia=" + ref + "&carpeta_leg=" + carpeta,
			player:		"iframe",
			title:		"Documento " + ref
		});
	}else{
		if(ref.substr(0, 8).toUpperCase() == "SP/FORM/"){
			window.open("/visor/default.asp?referencia=" + ref);
		}else{
			if(/MSIE (\d+\.\d+);/.test(navigator.userAgent) == false){
				Shadowbox.open({
					content:	"/visor/default.asp?referencia=" + ref,
					player:		"iframe",
					title:		"Documento " + ref
				});
			}else{
				window.open("/visor/default.asp?referencia=" + ref);
			}
		}
	}
}

function VerDocumentoBinario(ref){

	if(UsuarioLogado == false && DocumentoAccesoPago(ref) == true){
		alert("Para acceder a este apartado tienes que iniciar sesión.\nIntroduce tu usuario y clave en la parte superior derecha.");
		return;
	}

	window.open("/visor/default.asp?referencia=" + ref);
}

function DescargarDocumento(ref){

	if(UsuarioLogado == false && DocumentoAccesoPago() == true){
		alert("Para acceder a este apartado tienes que iniciar sesión.\nIntroduce tu usuario y clave en la parte superior derecha.");
		return;
	}

	window.open("/visor/default.asp?referencia=" + ref + "&descargar=1");
}

function VerDocumentoInline(obj){

	var TextoDestacar = "";
	var ref = $(obj).attr("id");
	
	if(ref.substr(0, 4).toLowerCase() == "http"){
		AbrirURL(ref);
	}else{
	
		if(($(".login_necesario").length > 0) && (ref.substr(0, 7).toUpperCase() == "SP/ART/")){
			alert("Por favor, indica tu clave para acceder a esta sección");
			return;
		}
	
		var re = new RegExp("/","ig");
		var id_previa = "prev_doc_" + ref.replace(re, "_");
			
		if($(obj).nextAll("#" + id_previa).length == 0){

			var id_ul_padre_previa = $(obj).parents("ul").attr("id");
			if(id_ul_padre_previa != "")
				id_ul_padre_previa = "#" + id_ul_padre_previa;
			
			if($(obj).parents("#resultados_bbdd_modal").length > 0){
				id_ul_padre_previa = "#resultados_bbdd_modal>div:eq(1)>" + id_ul_padre_previa;
			}
			
			if(ref.substr(0, 7).toUpperCase() != "SP/ART/"){
				$(id_ul_padre_previa + " .previa_documento").remove();
				if($(window).scrollTop() > $(obj).offset().top)
					$(window).scrollTop($(obj).offset().top);
			}

			//Para los árboles de legislación. Impide que se muestre más de un art. si no está logado.
			var arbol_padre = $(".previa_documento:has(div.login_necesario)").parents("div.tree");
			if(arbol_padre.length > 0){
				$("#" + arbol_padre[0].id + " .previa_documento:has(div.login_necesario)").remove();
			}
	
			if($(obj).next("span").length == 0)
				$(obj).after("<div id='" + id_previa + "' class='previa_documento'>&nbsp;<\/div>");
			else
				$(obj).nextAll(".doc_titulo").after("<div id='" + id_previa + "' class='previa_documento'>&nbsp;<\/div>");

			$.ajax({
				async:		true,
				type:		"GET",
				cache:		false,
				url:		"/visor/ajax_documento.asp?referencia=" + ref,
				beforeSend: function(){
					$(obj).nextAll("#" + id_previa).before("<div id='img_cargando_doc" + id_previa + "'><img src='/comunes/imagenes/spinner.gif'>&nbsp;cargando...<\/div>");
				},
				success: function(codigo){
					$(obj).nextAll("#" + id_previa).html(codigo);

					$(obj).addClass("documento_visitado");

					$(obj).nextAll("#" + id_previa).find("#chk_seleccionar_documento").click(function(){
						SeleccionarDocumento(ref);
					});

					if($("div#sb-container:visible").length > 0){
						$(obj).nextAll("#" + id_previa).find(".documentos_relacionados").addClass("desactivado");
						$(obj).nextAll("#" + id_previa).find(".formularios_relacionados").addClass("desactivado");
					}
						
					$(obj).nextAll("#" + id_previa).find(".enlace_anexo:not('.desactivado, .enlace_anexo_directo')").click(function(){
						if($(this).hasClass("activo") == false){
							$(obj).nextAll("#" + id_previa).find(".enlace_anexo.activo").removeClass("activo");
							$(this).addClass("activo");
							$(obj).nextAll("#" + id_previa).find(".contenido_anexo:visible").hide();
							if($(this).hasClass("clasificadores_documento"))
								ListarClasificadoresDelDocumento(ref, $(obj).nextAll("#" + id_previa));
								
							if($(this).hasClass("legislacion_documento"))
								ListarLegislacionRelacionada(ref, $(obj).nextAll("#" + id_previa));
								
							if($(this).hasClass("formularios_relacionados"))
								ListarFormsRelacionados(ref, $(obj).nextAll("#" + id_previa));

							if($(this).hasClass("notas_de_usuario"))
								MostrarNotasUsuario(ref);
						}else{
							$(obj).nextAll("#" + id_previa).find(".contenido_anexo:visible").hide();
							$(this).removeClass("activo");
						}
					});
					
					$(obj).nextAll("#" + id_previa + " #documento").append('<div class="b_icono_cerrar_doc"><a href="javascript:void(null);">cerrar</a></div>');
					$(obj).nextAll("#" + id_previa + " .b_icono_cerrar_doc>a").click(function(){
						$(obj).nextAll("#" + id_previa).stop();
						$(obj).nextAll("#" + id_previa).remove();
						if($(window).scrollTop() > $(obj).offset().top)
							$(window).scrollTop($(obj).offset().top);
					});
					
					$(obj).nextAll("#" + id_previa).find(".enlace_anexo_directo:not('.desactivado')").click(function(){
						if($(this).hasClass("documentos_relacionados"))
							ListarDocsRelacionados(ref);
					});
					
					DestacarTextoBuscado(TextoUsadoEnBusqueda($("#resumen_criterios_busqueda>#id_busqueda_actual").val()), "#" + id_previa, 1);

					$(id_ul_padre_previa).find("div.documento_bloque_expansible").click(function(){
						$(this).next(".documento_bloque_oculto").toggle();
					});
	
					$(obj).nextAll("#" + id_previa).find("input:checkbox").hide();
					$(obj).nextAll("#" + id_previa).find("input:checkbox").checkbox({cls:"jquery-safari-checkbox"});
					
					ajustarFuenteDocumento(tamanoFuente);
					
					TratarAvisosDeAcceso(id_previa, ref);
					
					$("#img_cargando_doc" + id_previa).remove();

//					$(obj).nextAll("#" + id_previa) + " .nota_en_documento[title]").mbTooltip({ // also $([domElement])..mbTooltip  >>  in this case only children element are involved
//						opacity :		.95,       //opacity
//						wait:			400,       //before show
//						cssClass:		"default", // default = default
//						timePerWord:	70,        //time to show in milliseconds per word
//						hasArrow:		false,     // if you whant a little arrow on the corner
//						imgPath:		"/comunes/includes/js/jquery/jQuery.mbTooltip.1.0/images/",
//						ancor:			"mouse",   //"parent"  //you can ancor the tooltip to the mouse position or at the bottom of the element
//						shadowColor:	"black"    //the color of the shadow
//					});

					$(obj).nextAll("#" + id_previa).show();

				},
				error: function(XMLHttpRequest, textStatus, errorThrown){
					$("#img_cargando_doc" + id_previa).remove();
					$(obj).nextAll("#" + id_previa).remove();
					if(XMLHttpRequest.status >= 800)
						alert(XMLHttpRequest.statusText);
					else
						alert("Error cargando.");
				}
			});
		}else{
			$(obj).nextAll("#" + id_previa).stop();
			$(obj).nextAll("#" + id_previa).slideUp("normal", function(){
				$(obj).nextAll("#" + id_previa).remove();
			});
		}

		$(".cont_imagen_resultados").hide();
		$("#imagen_boletin").remove();
	}
}

function SeleccionarDocumento(ref){

	var accion, msg;
	var re = new RegExp("/","ig");
	var refTratada;
	
	refTratada = ref.replace(re, "_");
	
	if($("#chk_seleccionar_documento").attr("checked")){
		accion = "0";
		msg = "Error deseleccionando el documento.";
	}else{
		accion = "1";
		msg = "Error seleccionando el documento.";
	}

	$.ajax({
		type: "GET", 
		url: "/visor/ajax_seleccion_documentos.asp",
		data: "referencia=" + ref + "&accion=" + accion,
		cache: false,
		async: true,
		success: function(html){
			if(accion == "0")
				$("#chkSelDoc_" + refTratada).attr("checked", "");
			else
				if(accion == "1")
					$("#chkSelDoc_" + refTratada).attr("checked", "checked");
			return true;
		},
		error: function(){
			alert(msg);
			return false;
		}
	});
}

function GuardarDoc(Ref){
	
	if(Ref.substr(0, 8).toUpperCase() == "SP/SENT/"){
		if(confirm("¿Guardar sólo los extractos?"))
			window.open("/visor/default.asp?guardar=1&referencia=" + Ref + "&solo_extractos=1");
		else
			window.open("/visor/default.asp?guardar=1&referencia=" + Ref);
	}else
		window.open("/visor/default.asp?guardar=1&referencia=" + Ref);
}

function ImprimirDoc(Ref){
	
	if(Ref.substr(0, 8).toUpperCase() == "SP/SENT/"){
		if(confirm("¿Imprimir sólo los extractos?"))
			window.open("/visor/default.asp?imprimir=1&referencia=" + Ref + "&solo_extractos=1");
		else
			window.open("/visor/default.asp?imprimir=1&referencia=" + Ref);
	}else
		window.open("/visor/default.asp?imprimir=1&referencia=" + Ref);
}

function DetallesDocumento(Referencia){
	
	var r = false;
	
	$.ajax({
		type: "GET", 
		url: "/visor/ajax_detalles_documento.asp?ref=" + Referencia,
		cache: false,
		async: false,
		dataType:	"json",
		success: function(jsonCabecera){
			r = jsonCabecera;
		}
	});
	
	return r;
}

function DocumentoAccesoPago(Referencia){

	var r = DetallesDocumento(Referencia);
	
	return(r.NIVEL_ACCESO == "PAGO");

}
