var versionJs = 19;
var _tools1_js_ = true;
var alto_anterior_navegar = 0;
var __global__con_binarios_imagenes = false; //con esto sabemos si la norma que se esta navegando tiene imagenes a mostrar
var __global__contador_binarios_imagenes = {};
function ajustarTam(val,val2,re_llamado){
	if (typeof(re_llamado) == 'undefined'){
		re_llamado = false;
	}
	var idtabla= val2;
	var mytabla = document.getElementById(val);

	/**
	 * Para evitar modificaciones de mas al alto, cuando no es necesario.. 
	 * se agregan estas lineas para validar eso.
	 */
	var alto_ahora = mytabla.offsetHeight;
	if(val == 'norma' && val2 == 'iframeContenido_norma'){
		if (alto_ahora == alto_anterior_navegar) {
			return true;
		}else{
			alto_anterior_navegar = alto_ahora;
		}
	}

	
	if (navigator.appName == "Microsoft Internet Explorer") {
		parent.document.getElementById(idtabla).style.height = (alto_ahora+30)+'px';
	}else{
		parent.document.getElementById(idtabla).style.height = (alto_ahora+15)+'px';
	}
	
	/**
	 * Cuando hay imágenes que mostrar, el alto de la pagina cambia cuando se cargan las imagenes
	 * es por eso que la funcion debe ser llamada nuevamente, para ajustar el tamaño corretamente.
	 * se llama varias veces a distintos tiempos para asegurse de dar tiempo a cargarse todas las imagenes
	 * si esque se llama 2 o mas veces despues que se han cargado las imagenes y el tamaño no ha cambiado,
	 * esta funcion detecta ese caso y no hace trabajo de más.
	 */
	if(__global__con_binarios_imagenes && re_llamado == false){
		setTimeout(function(){ajustarTam(val,val2,true);},500);
		setTimeout(function(){ajustarTam(val,val2,true);},1000);
		setTimeout(function(){ajustarTam(val,val2,true);},1500);
	}
}

function ajustarTam2(val,val2){
	var idtabla= val2;
	var mytabla = document.getElementById(val);

	parent.document.getElementById(idtabla).style.height = (mytabla.offsetHeight+95)+'px';
	
	if (navigator.appName == "Microsoft Internet Explorer") {
		parent.document.getElementById(idtabla).style.height = (mytabla.offsetHeight+30)+'px';
	}
}


function ajustarTamNavegar(val,val2){
	var idtabla= val2;
	var mytabla = document.getElementById(val);

	parent.document.getElementById(idtabla).style.height = (mytabla.offsetHeight+15)+'px';
	parent.document.getElementById(idtabla).style.width = (mytabla.offsetWidth)+'px';
	
	if (navigator.appName == "Microsoft Internet Explorer") {
		parent.document.getElementById(idtabla).style.height = (mytabla.offsetHeight+30)+'px';
		parent.document.getElementById(idtabla).style.width = (mytabla.offsetWidth)+'px';
	}
}
function replace(texto,s1,s2){
	var tmp = texto.split(s1).join(s2);
	return tmp;
}
function getAppVersion(){
	var nameN = navigator.userAgent;
	var appVersion 	= navigator.appVersion;
	var intAppVersion = 0;

	if (nameN.indexOf("MSIE") > -1 ){
		appVersion 	  = appVersion.split(";")[1];
		appVersion	  = replace(appVersion,"MSIE","");
		intAppVersion = parseInt(trim(appVersion).split(".")[0]);
	}
	return intAppVersion;
}
function esModoAporte(){
	var p = window.parent;
	var modo_aporte = p.getCookie('modo_aporte');
	if (modo_aporte && modo_aporte.indexOf('True') > -1){
		var _iter = 0;		
		while(typeof p.selectNormaParaAporte != 'function' && _iter < 10){
		    p = p.parent;
		    _iter++;
		}
		if (_iter < 10){
			return p;
		}else{
			p.deleteCookie('modo_aporte');	
		}
	}
	return false;
}
function NavegarNorma(idNorma, idParte, idVersion, buscar, revisarNormasGrandes, target, tipoVersion, checkFecha, msgDif){
	if ((idNorma == '') || (idNorma == '0') || (idNorma == 0)) {
		alert("Norma no navegable por falta de datos");
		return;
	}
	/**
	*Chequeo por si viene del modo busqueda para aportar
	*/
	var p = esModoAporte();
	if (p != false){
		return p.selectNormaParaAporte(idNorma);
	}
	
	if (revisarNormasGrandes == false) {
		revisarNormasGrandes = false;
	}
	else {
		revisarNormasGrandes = "check";
	}
	
	if (typeof(target) == 'undefined') {
		target = null;
	}
	if (typeof(tipoVersion) == 'undefined') {
		tipoVersion = 1;
	}
	if (typeof(checkFecha) == 'undefined'){
		checkFecha = false;
	}
	if (typeof(msgDif) == 'undefined'){
		msgDif = '';
	}
	
	try {
		if (typeof mensajesPuntuales == 'undefined') {
			mensajesPuntuales = window.parent.mensajesPuntuales;
		}
		if (revisarNormasGrandes && idNorma in mensajesPuntuales) {
			alert("Nota: " + mensajesPuntuales[idNorma]);
		}
	} 
	catch (e) {
	}
	
	var nameN = navigator.userAgent;
	var intAppVersion = getAppVersion();
	
	if (revisarNormasGrandes == "check" && nameN.indexOf("MSIE") > -1 && intAppVersion < 9) {
		revisarNormasGrandes = true;
	}
	else {
		revisarNormasGrandes = false;
	}
	
	/******
	 REVISION DE SI LA NORMA PERTENECE A LAS NORMAS GRANDES
	 ********/
	if (revisarNormasGrandes) {
		if (typeof idsNormasGrandes == 'undefined') {
			idsNormasGrandes = window.parent.idsNormasGrandes;
		}
		if (idNorma in idsNormasGrandes) {//idsNormasGrandes variable global definida en master.pt
			setMensajeNormasGrandes(idNorma, idParte, idVersion, buscar, undefined, target, tipoVersion);
			return;
		}
	}
	idVersion = darFormatoFechaTools(idVersion, 'aaa-mm-dd')
	if (checkFecha && idVersion){
		var hoy = new Date();
		hoy.setDate(hoy.getDate()+1);
		var fecha = getFecha(idVersion);
		if (fecha > hoy){
			if (idVersion == '2222-02-02'){
				if (msgDif){
					var msg = 'Usted está accediendo a la versión que entrará en vigencia cuando se cumpla el siguiente evento:\n';
					msgDif = extractEventoDiferido(msgDif);
					alert(msg+msgDif);
				}else{
					alert("Usted está accediendo a una versión que entrará en vigencia cuando se cumpla el evento indicado en la alerta 'Tiene texto diferido'");
				}
			}else{
				alert("Usted está accediendo a la versión que entrará en vigencia el "+darFormatoFechaTools(idVersion,'dd-mm-aaa'));
			}
		}
	}
	var form = document.createElement("form");
	form.setAttribute('id', 'Form_' + idNorma + idParte + idVersion);
	form.setAttribute('action', parent.urlServidor + '/../Navegar');
	form.setAttribute('method', 'get');
	if (target) {
		form.setAttribute('target', target);
	}
	else {
		form.setAttribute('target', '_parent');
	}
	
	var InputidNorma = document.createElement("input");
	InputidNorma.setAttribute('type', 'hidden');
	InputidNorma.setAttribute('value', idNorma);
	InputidNorma.setAttribute('name', 'idNorma');
	form.appendChild(InputidNorma);
	
	if (idParte != '' && idParte != 0) {
		var InputidParte = document.createElement("input");
		InputidParte.setAttribute('type', 'hidden');
		InputidParte.setAttribute('value', idParte);
		InputidParte.setAttribute('name', 'idParte');
		form.appendChild(InputidParte);
	}
	if (tipoVersion != 2) {
		if ((tipoVersion != 0 && tipoVersion != 3) || (idParte != '' && idParte != 0)) {
			var InputidVersion = document.createElement("input");
			InputidVersion.setAttribute('type', 'hidden');
			InputidVersion.setAttribute('value', idVersion);
			InputidVersion.setAttribute('name', 'idVersion');
			form.appendChild(InputidVersion);
		}
	}
	if (idParte == '' || idParte == 0) {
		if (tipoVersion == 0) {
			var InputtipoVersion = document.createElement("input");
			InputtipoVersion.setAttribute('type', 'hidden');
			InputtipoVersion.setAttribute('value', 0);
			InputtipoVersion.setAttribute('name', 'tipoVersion');
			form.appendChild(InputtipoVersion);
		}
	}
	
	
	if (buscar == undefined) {
		buscar = "";
	}
	if (buscar && buscar != "") {
		var Inputbuscar = document.createElement("input");
		Inputbuscar.setAttribute('type', 'hidden');
		Inputbuscar.setAttribute('value', buscar);
		Inputbuscar.setAttribute('name', 'buscar');
		form.appendChild(Inputbuscar);
	}
	
	document.body.appendChild(form);
	setTimeout(function(){
		document.getElementById('Form_' + idNorma + idParte + idVersion).submit();
	}, 500);
}
function extractEventoDiferido(txt){
	var init = txt.indexOf('<li>');
	var end = txt.indexOf('</li>');
	var txtFin = '';
	while(init > -1 && end > -1){	
		var substr = txt.substr(init,end+5);
		txt = txt.replace(substr, '');
		txtFin += '- '+substr.replace('<li>', '').replace('</li>', '').replace('<br/>', '')+'\n ';
		init = txt.indexOf('<li>');
		end = txt.indexOf('</li>');
	}
	return txtFin;
}
function getFecha (fechastr){
	var tmp = fechastr.split("-");
	var anio = tmp[0];
	var mes = tmp[1];
	var dia = tmp[2];
	var n_fechaStr = anio+"/"+mes+"/"+dia;
	var fecha = new Date(n_fechaStr);
	return fecha;
}

function dateFormat(fecha, format){
	var dia = fecha.getDate();
	var mes = fecha.getMonth();
	var anio = fecha.getFullYear();
	if (dia < 10){
		dia = '0'+dia.toString();	
	}
	if (mes < 10){
		mes = '0'+mes.toString();	
	}
	
	return format.replace('dd',dia).replace('mm',mes).replace('yyyy',anio);
	
}
function NavegarVinculaciones(idNorma,idParte,tipo,fechaVigencia,tipoParte){
	/*
	 * Trazar el Navegar Vinculaciones
	 */
	if(idParte == "0"){idParte="";}
	TrazarNavegarVinculaciones(tipo,idNorma,idParte);
	
	if (typeof(tipoParte)== 'undefined'){
		tipoParte = 0;
	}
	var PAGINA = "";
	switch (tipo) {
		case "MODIFICACION":
			PAGINA = "nav_vinc_modificacion";
			break;
		case "CONCORDANCIA":
			PAGINA = "nav_vinc_concordancia";
			break;
		case "REGLAMENTO":
			PAGINA = "nav_vinc_reglamento";
			break;
		case "TEXTO REFUNDIDO":
		case "TEXTO_REFUNDIDO":
			PAGINA = "nav_vinc_texto_refundido";
			break;
		case "RECTIFICACION":
			PAGINA = "nav_vinc_rectificacion";
			break;
		default:
			PAGINA = "nav_vinc_modificacion";
			break;
	}
	/*
	if (tipo != 'MODIFICACION' && tipo != 'TEXTO REFUNDIDO' && tipo != 'REGLAMENTO') {
		alert("Este tipo de Vinculacion aun no esta implementado.");
		return;
	}
	*/
	var form = document.createElement("form");
	form.setAttribute('id','FormVinc_'+idNorma+idParte+fechaVigencia);
	form.setAttribute('action',parent.urlServidor+"/../Consulta/"+PAGINA);
	form.setAttribute('method','get');
	form.setAttribute('target','_parent');
	
	var InputidNorma = document.createElement("input");
	InputidNorma.setAttribute('type','hidden');
	InputidNorma.setAttribute('value',idNorma);
	InputidNorma.setAttribute('name','idNorma');
	form.appendChild(InputidNorma);

	var InputtipoParte = document.createElement("input");
	InputtipoParte.setAttribute('type','hidden');
	InputtipoParte.setAttribute('value',tipoParte);
	InputtipoParte.setAttribute('name','tipoParte');
	form.appendChild(InputtipoParte);
	
	var InputidParte = document.createElement("input");
	InputidParte.setAttribute('type','hidden');
	InputidParte.setAttribute('value',idParte);
	InputidParte.setAttribute('name','idParte');
	form.appendChild(InputidParte);
	
	var InputfechaVigencia = document.createElement("input");
	InputfechaVigencia.setAttribute('type','hidden');
	InputfechaVigencia.setAttribute('value',fechaVigencia);
	InputfechaVigencia.setAttribute('name','fechaVigencia');
	form.appendChild(InputfechaVigencia);

	var InputTipo = document.createElement("input");
	InputTipo.setAttribute('type','hidden');
	InputTipo.setAttribute('value',tipo);
	var nombre = (tipo=="RECTIFICACION")?"tipo_vinculacion":"clase_vinculacion";
	InputTipo.setAttribute('name',nombre);
	form.appendChild(InputTipo);
		
	document.body.appendChild(form);
	setTimeout(function(){
			mostrarMensajeBuscando();
			document.getElementById('FormVinc_'+idNorma+idParte+fechaVigencia).submit();
		},500);
}
function postToResumen(idNorma,idParte,fechaVigencia){
	var form = document.createElement("form");
	form.setAttribute('id','FormRes_'+idNorma+idParte+fechaVigencia);
	form.setAttribute('action',parent.urlServidor+"/../Consulta/ResumenNorma");
	form.setAttribute('method','get');
	form.setAttribute('target','_parent');
	
	var InputidNorma = document.createElement("input");
	InputidNorma.setAttribute('type','hidden');
	InputidNorma.setAttribute('value',idNorma);
	InputidNorma.setAttribute('name','idNorma');
	form.appendChild(InputidNorma);
	
	var InputidParte = document.createElement("input");
	InputidParte.setAttribute('type','hidden');
	InputidParte.setAttribute('value',idParte);
	InputidParte.setAttribute('name','idParte');
	form.appendChild(InputidParte);
	
	var InputfechaVigencia = document.createElement("input");
	InputfechaVigencia.setAttribute('type','hidden');
	InputfechaVigencia.setAttribute('value',fechaVigencia);
	InputfechaVigencia.setAttribute('name','fechaVigencia');
	form.appendChild(InputfechaVigencia);

	document.body.appendChild(form);
	document.getElementById('FormRes_'+idNorma+idParte+fechaVigencia).submit();
	
}
function postToEventos(idNorma,tipoNorma,nroNorma,Organismo,fechaPublicacion){

	var form = document.createElement("form");
	form.setAttribute('id','FormEvent_'+tipoNorma+nroNorma);
	form.setAttribute('action',parent.urlServidor+"/../Consulta/eventos");
	form.setAttribute('method','get');
	form.setAttribute('target','_parent');
	
	var InputidNorma = document.createElement("input");
	InputidNorma.setAttribute('type','hidden');
	InputidNorma.setAttribute('value',idNorma);
	InputidNorma.setAttribute('name','idNorma');
	form.appendChild(InputidNorma);
	
	var InputtipoNorma = document.createElement("input");
	InputtipoNorma.setAttribute('type','hidden');
	InputtipoNorma.setAttribute('value',tipoNorma.replace("XX",""));
	InputtipoNorma.setAttribute('name','tipoNorma');
	form.appendChild(InputtipoNorma);
	
	var InputnroNorma = document.createElement("input");
	InputnroNorma.setAttribute('type','hidden');
	InputnroNorma.setAttribute('value',nroNorma);
	InputnroNorma.setAttribute('name','nroNorma');
	form.appendChild(InputnroNorma);

	var InputOrganismo = document.createElement("input");
	InputOrganismo.setAttribute('type','hidden');
	InputOrganismo.setAttribute('value',Organismo);
	InputOrganismo.setAttribute('name','Organismo');
	form.appendChild(InputOrganismo);
		
	var InputfechaPublicacion = document.createElement("input");
	InputfechaPublicacion.setAttribute('type','hidden');
	InputfechaPublicacion.setAttribute('value',fechaPublicacion);
	InputfechaPublicacion.setAttribute('name','fechaPublicacion');
	form.appendChild(InputfechaPublicacion);
		
	document.body.appendChild(form);
	document.getElementById('FormEvent_'+tipoNorma+nroNorma).submit();
}

function ocultarInfo(valId){
	var res = document.getElementById(valId);
	if(res.style.display=='block'){
		res.style.display = 'none';
	}else{
		res.style.display = 'block';
	}
}
function ir_a_volver(a,b){
	window.history.back();	
};
function revisaEnter(e,funcionOnEnter){
	if (navigator.appName == "Netscape") {
		var tecla = e.which
	}
	else {
		var tecla = e.keyCode
	}
	if (tecla == 13) {//13 -> Enter
		if (typeof funcionOnEnter == 'undefined'){
			enviarLoginNew('Consulta');
		}else{
			eval(funcionOnEnter);
		}
	}
	return true;
}
function onUnload(){
	var divMensajeBusqueda = $('divMensajeBusqueda');
	if (divMensajeBusqueda){
		divMensajeBusqueda.style.display = "none";
	}
}
function revisaLogueado(){
	if (window.location.href.indexOf('loginCD') > -1){
		return;
	}
	if (window.location.href.indexOf('registrook') > -1){
		return;
	}
	if (window.location.href.indexOf('pre_registrookmail') > -1){
		return;
	}
	
	var mailUser = getCookie('mailUser')?getCookie('mailUser'):"";
	var spanBienvenido = $('spanBienvenido');
	if (mailUser){
		//spanBienvenido.innerHTML = mailUser.replace('"','').replace('"','');
	}
	var divMensajeBusqueda = $('divMensajeBusqueda');
	if (divMensajeBusqueda){
		divMensajeBusqueda.style.display = "none";
	}
	if (window.location.href.indexOf("registro") > -1){
		return true;
	}
	if (window.location.href.indexOf("confirmacion") > -1){
		return true;
	}
	
	var forms = document.getElementsByTagName("form");
	for (var i=0;i<forms.length;i++){
		forms[i].setAttribute("method","get");
	}
	limpiaCookiesIfAnon();
	return;	
	/**
	 * Lo siguiente no es necesario ahora. 15-04-2011
	 */
	var reloades = getReloades();
	if (reloades > 5){
		deleteCookie('mailUser','/');
		return;
	}
	var vhref = window.location.href;
	if (reloades > 0) {
		vhref = vhref.replace("?reloaded=" + reloades, "")
		vhref = vhref.replace("&reloaded=" + reloades, "")
	}
	reloades += 1;
	if (spanBienvenido) {
		var correo 	 = spanBienvenido.innerHTML;
		var mailUser = mailUser.substr(1,mailUser.length-2);
		if (!mailUser || correo.indexOf(mailUser) == -1){//Esta anónimo y viendo una pagina de conectado o una pagina visitada como otro usuario
			var divMensajeBusqueda = $('divMensajeBusqueda');
			if (divMensajeBusqueda){
				divMensajeBusqueda.innerHTML 	 = "Recargando espere un momento ... ";
				divMensajeBusqueda.style.display = "";
			}
			window.location.href = (vhref.indexOf("?")> -1)?vhref+"&reloaded="+reloades+"":vhref+"?reloaded="+reloades;
		}
	}else{
		if (mailUser){//Esta Visitando una página de anónimo y está logueado
			var divMensajeBusqueda = $('divMensajeBusqueda');
			if (divMensajeBusqueda){
				divMensajeBusqueda.innerHTML 	 = "Recargando espere un momento ... ";
				divMensajeBusqueda.style.display = "";
			}
			window.location.href = (vhref.indexOf("?")> -1)?vhref+"&reloaded="+reloades+"":vhref+"?reloaded="+reloades;
		}
	}
	return true;
};
function limpiaCookiesIfAnon(){
	/**
	 * Si no está logueado, se borran las cookies de Zope, para que varnish pueda cachear.
	 */
	var mailUser = getCookie('mailUser')?getCookie('mailUser'):"";
	if (!mailUser){
		/*Cookies de Google Analitycs*/
		/*deleteCookie('__utma','/','.leychile.cl');
		deleteCookie('__utmb','/','.leychile.cl');
		deleteCookie('__utmc','/','.leychile.cl');
		deleteCookie('__utmz','/','.leychile.cl');*/

		deleteCookie('mailUser','/');
		deleteCookie('_ZopeId','/');
		deleteCookie('rolUser','/');
		deleteCookie('errorlogin','/');
		deleteCookie('stringBusquedaSession','/');
		//deleteCookie('CookieModuloActual','/');
		deleteCookie('permisoVinculacion','/');
		
		if (window.location.href.indexOf("avanzada") == -1){
			deleteCookie('fechaVersionIntermedios','/');
		}
		if (window.location.href.indexOf("exportar") == -1){
			deleteCookie('carritoExportar','/');
		}
		setTimeout("limpiaCookiesIfAnon()",1500);
	}
}
function getReloades(){
	var tmp = window.location.href.split("?");
	if (!tmp[1]) {
		return 0;
	}
	tmp = tmp[1].split("&");
	for (var i = 0; i < tmp.length; i++) {
		var tmp1 = tmp[i].split("=");
		if (tmp1[0] == 'reloaded') {
			try {
				return parseInt(tmp1[1]);
			}catch(e){
				return 0;
			}
		}
	}
	return 0;
}
function cierraInfo(){
	document.getElementById('contenidoajax').style.display = "none";
}
function optUsers(opt){
	var frm = document.getElementById('frmHUser');
	var hopt = document.getElementById('optUser');
	hopt.value = opt;
	if (opt == 3){
		deleteCookie('rolUser','/');
	}
	frm.submit();
	
}
function validarRegistro(){ 
	var frm = document.getElementById("frmRegistro");
	var pass = document.getElementById("rPass");
	var rpass = document.getElementById("rRpass");
	if (pass.value == rpass.value) {
		frm.submit();
	}
	else{
		pass.focus()
		alert("contrseña no coinciden " + pass.value + " <> " + rpass.value );
	}
}

function cookiesEnabled() {
  // Test whether cookies are enabled by attempting to set a cookie and then change its value
  // set test cookie
  var c = "areYourCookiesEnabled=0";
  document.cookie = c;
  var dc = document.cookie;
  // cookie not set?  fail
  if (dc.indexOf(c) == -1) return 0;
  // change test cookie
  c = "areYourCookiesEnabled=1";
  document.cookie = c;
  dc = document.cookie;
  // cookie not changed?  fail
  if (dc.indexOf(c) == -1) return 0;
  // delete cookie
  document.cookie = "areYourCookiesEnabled=; expires=Thu, 01-Jan-70 00:00:01 GMT";
  return 1;
}

function showCookieMessage(msg_id) {
  // Show the element with the given id if cookies are not enabled
  msg = document.getElementById(msg_id)
  if (msg) {
     if (cookiesEnabled()) {
        msg.style.display = 'none';
     } else {
        msg.style.display = 'block';
     }
  }
}

function SetCookieModuloActual(modulo){
	if(!esModulo(modulo)) {alert('El nombre del módulo Ingresado, no existe'); return false;}
	var nombreCookie = "CookieModuloActual"
	deleteCookie( nombreCookie, '/', '' );
	setCookie(nombreCookie, modulo, '', '/', '', '' );
}

function closeCookieMessage(msg_id){
	msg = document.getElementById(msg_id);
	msg.style.display = 'none';
}

function esEsteModulo(modulo){
	if(!esModulo(modulo)) {alert('El nombre del módulo Ingresado, no existe'); return false;}
	var nombreCookie = "CookieModuloActual"
	var moduloActual  = getCookie(nombreCookie);
	if(moduloActual == modulo){
		return true;
	}else{
		return false;
	}
}

var modulosGenerales = new Array();
modulosGenerales.push("simple");
modulosGenerales.push("avanzada");
modulosGenerales.push("indice_materias");
modulosGenerales.push("vinculaciones");
modulosGenerales.push("normas_seleccionadas");
modulosGenerales.push("tratados");
modulosGenerales.push("legislacion_abierta");
modulosGenerales.push("leyes_por_institucion");
modulosGenerales.push("aportar_leychile");

function esModulo(modulo){
	
	for(var i=0;i<modulosGenerales.length;i++){
		if(modulosGenerales[i]==modulo){
			return true;
		}	
	}
	return false;
}

function SeleccionaMenuActual(){
	return true;
	var nombreCookie = "CookieModuloActual"
	var moduloActual  = getCookie(nombreCookie);
	var td_menu = ""
	var linea = "";
	switch (moduloActual){
		case 'simple':
			td_menu = "menu_simple";
			break;
		case 'avanzada':
			td_menu = "menu_avanzada";
			linea = "linea1";
			break;
		case 'indice_materias':
			td_menu = "menu_indice_materias";
			linea = "linea2";
			break;
		case 'vinculaciones':
			td_menu = "menu_vinculaciones";
			linea = "linea3";
			break;
		case 'normas_seleccionadas':
			td_menu = "menu_normas_seleccionadas";
			linea = "linea4";
			break;
		case 'tratados':
			td_menu = "menu_tratados";
			linea = "linea5";
			break;
		case 'legislacion_abierta':
			td_menu = "menu_legislacion_abierta";
			linea = "";
			break;
		case 'leyes_por_institucion':
			td_menu = "leyes_por_institucion";
			linea = "";
			break;
		default:
			td_menu = "";
	}		
	limpiarColorModulos();
	if(td_menu != ""){
		document.getElementById(td_menu).className="color2";
		if (linea != "") {
            if((document.getElementById('menu_vinculaciones')==null)&&(linea=='linea4')){
                document.getElementById('linea3').className = "lineainvisible";
            }else{
			      document.getElementById(linea).className = "lineainvisible";
            }
		}
	}
}
function limpiarColorModulos(){
	var flag = true;
    for (var i = 0; i < modulosGenerales.length; i++) {
        if (document.getElementById("menu_" + modulosGenerales[i]) == null) {
            flag = false;
        }
        else {
            document.getElementById("menu_" + modulosGenerales[i]).className = "color1";
        }
    }
	for(var j=1;j<6;j++){
		var temp = "linea"+j;
        if(flag){
           document.getElementById(temp).className="lineamenu"; 
        }
		
	}
}

function getCodigoModulo(){
	var modulo = '14';
	if(esEsteModulo('simple')) modulo = '1';
	if(esEsteModulo('avanzada')) modulo = '2';
	if(esEsteModulo('indice_materias')) modulo = '4';
	if(esEsteModulo('vinculaciones')) modulo = '6';
	if(esEsteModulo('normas_seleccionadas')) modulo = '5';
	if(esEsteModulo('tratados')) modulo = '13';
	
	return modulo;
}

function fLogin(){
	var correo =  document.getElementById("usuario").value;
	var clave = document.getElementById("password").value;
	
	if ((correo != '') && (correo) && (validarEmail(correo)) ) {
		if (clave==""){
			alert("Escriba Contraseña");
			RegistrarRegistroUsuario('46','AUT-03');
			return false;
		}
		return true;
	}
	else if(correo==""){
		alert("Su usuario es la direccion de correo");
		RegistrarRegistroUsuario('46','AUT-01');
		return false;
		
	}
	else{alert("Su usuario es la direccion de correo");
		RegistrarRegistroUsuario('46','AUT-01');
		return false;}
	
}
function enviarLogin(url){
	if(fLogin()){
		getUserDB(url);
	}
	return false;
}
function enviarLoginNew(){
	this.succes = function(req){
		var pagina = req.responseText.split("?")
		var params = "";		
		if (pagina.length > 1){
			params = pagina[1];
			for (var i=2;i<pagina.length;i++){
				params += "?"+pagina[i];
			}
		}
		pagina = pagina[0];
		$('formLoginNew').setAttribute('action',pagina);
		$('formLoginNew').setAttribute('method','get');
		params = params.split("&");
		for(var i=0;i<params.length;i++){
			var nombre = params[i].split("=")[0];
			var valor = params[i].split("=")[1];
			var input = $('id_'+nombre);
			if (!input){
				var input = document.createElement('input');
				input.setAttribute("type","hidden");
				input.setAttribute("name",nombre);
				input.setAttribute("id","id_"+nombre);
				$('formLoginNew').appendChild(input);
			}
			input.setAttribute("value",valor);
		}
		$('formLoginNew').submit();
	};
	this.failure = function (req){
		alert(req.responseText);
	};
	var params = {
		method: 'get',
		onSuccess: this.succes,
		onFailure: this.failure,
		parameters: {
			usuario: $F('usuario')
			,password: $F('password')
		}
	};
	this.request = new Ajax.Request(parent.urlServidor + '/../Consulta/script/validaUsuarioLogin', params);
}
function validarEmail(email){
    regx = /^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$/;
    return regx.test(email);
}

function ltrim(s) {
   return s.replace(/^\s+/, "");
}

function rtrim(s) {
   return s.replace(/\s+$/, "");
}

function trim(s) {
   return rtrim(ltrim(s));
}

function validarMsje(){
	var divmsje = document.getElementById("msjeLogin");
	var msje = document.getElementById("mensaje");
	cookiemsj =getCookie("msjes")
	if((cookiemsj!="")&&(cookiemsj!=null)&&(cookiemsj!="\"None\"")&&(cookiemsj!="None")){
		divmsje.style.display = "block";
		var variable = cookiemsj;
		msje.innerHTML= variable;
	}
	deleteCookie( "msjes", '/', '' );
}
function cerrarMsjeLogin(){
	document.getElementById("msjeLogin").style.display = "none";
	deleteCookie( "msjes", '/', '' );
}

/**
*
* URL encode / decode
* http://www.webtoolkit.info/
*
**/

var Url = {

    // public method for url encoding
    encode : function (string) {
        return escape(this._utf8_encode(string));
    },

    // public method for url decoding
    decode : function (string) {
        return this._utf8_decode(unescape(string));
    },

    // private method for UTF-8 encoding
    _utf8_encode : function (string) {
        string = string.replace(/\r\n/g,"\n");
        var utftext = "";

        for (var n = 0; n < string.length; n++) {

            var c = string.charCodeAt(n);

            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }

        return utftext;
    },

    // private method for UTF-8 decoding
    _utf8_decode : function (utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;

        while ( i < utftext.length ) {

            c = utftext.charCodeAt(i);

            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }
            else if((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i+1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else {
                c2 = utftext.charCodeAt(i+1);
                c3 = utftext.charCodeAt(i+2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }

        }

        return string;
    }

}
function findPos(obj){
    var curleft = curtop = 0;
    try {
		if (obj.offsetParent) {
			curleft = obj.offsetLeft;
			curtop = obj.offsetTop;
			while (obj = obj.offsetParent) {
				curleft += obj.offsetLeft;
				curtop += obj.offsetTop;
			}
		}
	} 
	catch (e) {
	}
    return [curleft, curtop];
}

	
	
function fbackLogin(){
	var correo =  document.getElementById("mailLost").value;
	if ((correo != '') && (correo) && (validarEmail(correo))) {
		var arrUser = correo.split("@");
		var arrEmp = arrUser[1].split(".")
		var user = arrUser[0];
		for (var i = 0; i < arrEmp.length; i++) {
			user += "_" + arrEmp[i];
		}
		var url = "loginback?hLostUser="+correo;
		Cargar(url);
	}
	else if(correo!=''){
		alert("Su usuario es la direccion de correo");
		document.getElementById("mailLost").focus();
	}
	else{}
}

function submitLogin(oEvento,url){
	 var iAscii;
	 if (oEvento.keyCode) {
	 	iAscii = oEvento.keyCode;
	 }
	 else {
	 	if (oEvento.which) {
	 		iAscii = oEvento.which;
	 	}
	 	else {
	 		return false;
	 	}
	 }
     if (iAscii == 13) {
		enviarLogin(url);
		return false;
	 }
     return true; 
}
function goToInside(nombre){
	var ubicacion = document.location.toString();
	ubicacion = ubicacion.split("#");
	document.location = ubicacion[0]+ "#" + nombre;
}

function enviarConsulta(parametros, exacta){
	var conc = "||-2#normal#on"
	if (exacta == 1) {
		parametros += conc;
	}
	//alert(parametros);
	document.getElementById("paramBusqueda").value = parametros;
	document.getElementById("frmConsutalH").submit();
}

function enviarConsultaIframe(parametros, exacta){
	//alert (parametros);
	var conc = "||-2#normal#on"
	if (parseInt(exacta) == 1) {
		parametros += conc;
	}
	document.getElementById("paramBusqueda").value = parametros;
	document.getElementById("frmConsutalH").target = "_parent";
	document.getElementById("frmConsutalH").submit();
}

function enviarConsultaIframe2(cadena, tipo){
	//alert (parametros);
	if(tipo == 'bmateria'){tipo = "Materia"}
	else{tipo= "en Norma"}
	var parametros = "[{'descripcion':'Cadena','valor_busqueda':'" + cadena + "'},{'descripcion':'Tipo Busqueda','valor_busqueda':'" + tipo + "'}]"
	//alert (parametros);
	document.getElementById("paramBusqueda").value = parametros;
	document.getElementById("frmConsutalH").target = "_parent";
	document.getElementById("frmConsutalH").submit();
}


/** Para traspaso de links de normas para la Atencion Telefonica
 * esta funcion abre un popup en management y le envia los valores de la busqueda en delivery
 * el nuevo popup se encarga de cargar los datos y cerrar las ventanas
 */

function TraspasarDatosManagmentAtencionUsuarios(normas){
	normas = getCookie("TraspasoNormasAU");
	if (normas == null || normas == "") {
		alert("No hay normas para traspasar desde el Maletín");
		return true;
	}
	if (confirm("ATENCION!! Se traspasarán los links de todas las normas que se encuentran en el maletín hacia la lista de links de respuesta.\n\nEsta funcionalidad es válida SÓLO para el referencista que proviene de Atencion Usuarios.\n\n¿Está seguro de continuar?")) {
		normas = replace(normas,"#","@");
		vaciaMaletines_al_traspasar();
		goToTraspasarDatosManagmentAtencionUsuarios(normas);
	}
}

function goToTraspasarDatosManagmentAtencionUsuarios(normas){
	if (window.opener) {
		try {
			var url = urlManagement+"/BaseCM/datosDeliveryAU?normas="+normas;
			window.open(url, '_blank', "height=10,width=10, scrollbars=yes, menubar=no, location=no, resizable=no");
		} 
		catch (e) {
			alert("No se puede traspasar datos, debe iniciar la búsqueda desde el Content Managment");
		}
	}
	else {
		alert("No se puede traspasar datos, debe iniciar la búsqueda desde el Content Managment");
	}
	return false;
}


function vaciaMaletines_al_traspasar(){
    var carrito = getCookie('carritoNorma');
    if (carrito != null && carrito != "") {
        deleteCookie('carritoNorma', '/', '');
    }
    var carrito = getCookie('carritoExportar');
    //if (carrito != null && carrito != "") {
        deleteCookie('carritoExportar', '/', '');
    //}
    var carrito = getCookie('TraspasoNormasAU');
    if (carrito != null && carrito != "") {
        deleteCookie('TraspasoNormasAU', '/', '');
    }	
}


/**
 * esta funcion abre un popup en management y le envia los valores de la busqueda en delivery
 * el nuevo popup se encarga de cargar los datos y cerrar las ventanas
 * @param {Object} idNorma
 * @param {Object} Tipo
 * @param {Object} Numero
 * @param {Object} Organismo
 * @param {Object} fechaPublicacion
 * @param {Object} fechaPromulgacion
 * @param {Object} fechaInicioVigencia
 * @param {Object} tipoParte
 * @param {Object} idParte
 * @param {Object} transitorio
 */
function goToTraspasarDatosManagment(idNorma, Tipo, Numero, Organismo, fechaPublicacion, fechaPromulgacion, fechaInicioVigencia, tipoParte,idParte,transitorio,strParte){
	if (window.opener) {
		try {
			var url = urlManagement+"/BaseCM/datosDelivery?idNorma="+idNorma+"&Tipo="+Tipo+"&Numero="+Numero+"&Organismo="+Organismo+"&fechaPublicacion="+fechaPublicacion+"&fechaPromulgacion="+fechaPromulgacion+"&fechaInicioVigencia="+fechaInicioVigencia+"&tipoParte="+tipoParte+"&idParte="+idParte+"&transitorio="+transitorio+"&strParte="+strParte;
			window.open(url, '_blank', "height=10,width=10, scrollbars=yes, menubar=no, location=no, resizable=no");
		} 
		catch (e) {
			alert("No se puede traspasar datos, debe iniciar la búsqueda desde el Content Managment");
		}
	}
	else {
		alert("No se puede traspasar datos, debe iniciar la búsqueda desde el Content Managment");
	}
	return false;
}


//Funciones para dar formato a la fecha:
function darFormatoFechaTools(strFecha, strFormato){
	var dd_mm_yyyy = /^[0-9]{2}-[0-9]{2}-[0-9]{4}$/;
	var yyyy_mm_dd = /^[0-9]{4}-[0-9]{2}-[0-9]{2}$/;
	var mm_yyyy = /^[0-9]{2}-[0-9]{4}$/;
	var yyyy = /^[0-9]{4}$/;
	var formato = "";
	//En Formato dd-mm-yyyy
	if (dd_mm_yyyy.test(strFecha)) {
		formato="dd-mm-aaa";
	}else if(mm_yyyy.test(strFecha)){
		formato="mm-aaa";
	}else if(yyyy.test(strFecha)){
		formato="aaa";
	}else if(yyyy_mm_dd.test(strFecha)){
		formato="aaa-mm-dd";
	}else{

		if (trim(strFecha) != "") {
			alert("Formato de Fecha Desconicido: " + strFecha);
		}
		return strFecha;
	}

	if(formato==strFormato){
		return strFecha;
	}
	var arrFecha = strFecha.split("-");

	switch(formato){
		case "dd-mm-aaa":
			if(strFormato=="aaa-mm-dd"){
				return arrFecha[2]+"-"+arrFecha[1]+"-"+arrFecha[0];
			}else if(strFormato=="dd-mmm-aaaa"){
				return arrFecha[0]+"-"+Mes(arrFecha[1])+"-"+arrFecha[2];
			}else{
				alert("Formato no implementado: "+strFormato);
			}
			break;
		case "aaa-mm-dd":
			if(strFormato=="dd-mm-aaa"){
				return arrFecha[2]+"-"+arrFecha[1]+"-"+arrFecha[0];
			}else{
				alert("Formato no implementado: "+strFormato);
			}
			break;
	}

}

function recalcularCarro(name){
    var objtexto=document.getElementById('selecciones');
    if(!objtexto){
		objtexto=parent.document.getElementById('selecciones');
	}
	var carrito=getCookie(name);
    var texto="Mi selección";
    if(carrito!=null&&carrito!=""){
        var nuevocarro=carrito.split('#');
        var n=nuevocarro.length;
        //alert(n);
        if(n!=0 && n>1){texto=n+ " Documentos";}
        if(n!=0 && n==1){texto=n+ " Documento";}
    }
    objtexto.innerHTML=texto;
}

/**
 * funciones para ayuda
 */

function verAyuda(){
	//se debe definir los parametros que se le entregan a la pagina que abre la ayuda	
	var url = urlServidor+"/ayudaLocal";
	var parametro = arguments[0];
	if(parametro){
		//alert(parametro);
		var url = url+'?nombre_pt='+ parametro;

	}
	eval(window.open(url, 'window', 'toolbar=0,scrollbars=yes,location=0,statusbar=0,menubar=0,resizable=0,width=976,height=450,left = 150,top = 200'));

}

function cerrarAyuda(){
	window.close();
}

function cerrarMensajeNormasGrandes(){
	var divMensaje = document.getElementById('divNormasGrandes');
	if(!divMensaje){
		divMensaje = window.parent.document.getElementById('divNormasGrandes');
	}
	if(!divMensaje){
		divMensaje = window.parent.parent.document.getElementById('divNormasGrandes');
	}
	divMensaje.style.display = "none";
	divMensaje.innerHTML = "";
}
function setMensajeNormasGrandes(idNorma,idParte,idVersion,buscar,idVersionContexto, target, tipoVersion){
	if(typeof(target) == 'undefined'){
		target = '';
	}
	if(typeof(tipoVersion) == 'undefined'){
		tipoVersion = 1;
	}
	if(typeof(idVersionContexto) == 'undefined'){
		comparar = false;
	}else{
		comparar = true;
	}
	if(!idParte){
	   idParte=0
	  }
	pdf='pdf';
	NORMA='NORMA_';
	var nameApp = navigator.userAgent;
	appVersion 	= getAppVersion();

	if (nameApp.indexOf("Firefox") > -1) {
		nameApp = "Mozilla Firefox";
	}
	else 
		if (nameApp.indexOf("MSIE") > -1) {
			nameApp = "Microsoft Internet Explorer";
		}
		else 
			if (nameApp.indexOf("Opera") > -1) {
				nameApp = "Microsoft Internet Explorer";
			}else{
				nameApp = navigator.appName;
			}
	
	var nameAppVersion = nameApp+" "+appVersion;
	var divMensaje = document.getElementById('divNormasGrandes');
	if(!divMensaje){
		divMensaje = window.parent.document.getElementById('divNormasGrandes');
	}
	if(!divMensaje){
		divMensaje = window.parent.parent.document.getElementById('divNormasGrandes');
	}

	var html = '<table>';
	
	html 	+= ' <tr><td><div style="float:right"><button onclick="javascript:cerrarMensajeNormasGrandes();" class="boton_cerrar invisible"><span>Cerrar</span></button></div></td></tr>';

	html 	+= '		<tr>';
	html 	+= '			<td>';
	if (comparar) {
		//html += '				Su navegador es <b>'+nameApp+'</b>,<br />';
	}else{
		html += 'La Norma que solicita es demasiado grande para ser procesada rápidamente por su navegador <b>'+nameAppVersion+'</b>.<br />';
	}
	if (!comparar) {
		html += 'Recomendamos <a style="TEXT-DECORATION: underline" href="javascript:descargarNormaListado(\'' + idNorma + '\', \''+ idVersion + '\', \'' + idParte + '\', \'' + 0 +  '\', \'' + pdf +  '\', \'' + NORMA+idNorma+idParte +  '\' );">descargar la versión PDF</a> de ella, o bien ';
		html += '<a style="TEXT-DECORATION: underline" href="javascript:NavegarNorma(\'' + idNorma + '\', \'' + idParte + '\', \'' + idVersion + '\', \'' + buscar + '\',false,\''+target+'\','+tipoVersion+');">continuar el proceso de construcción</a>';
		html += ', considerando el tiempo de espera.<br>';
		html += 'Para un mejor tiempo de respuesta, <a style="TEXT-DECORATION: underline" href="../Consulta/ayuda_motor_javascript" target="_blank" >siga este enlace.</a>';
	}else{
		html += '	Le <b>recomendamos comparar</b> la norma a <b>nivel de Artículo</b><br /><br />';
	}
	
	html 	+= '			</td>';
	html 	+= '		</tr>';
	html 	+= '		<tr>';
	html 	+= '			<td style="text-align:right">';

	if (comparar) {
		html += '				<a href="javascript:CompararNorma(\'' + idNorma + '\', \'' + idParte + '\', \'' + idVersion + '\', \'' + idVersionContexto + '\',false);"><b>Comparar la norma de todos modos</b></a>';
	}else{
		html += '';
	}
	
	html 	+= '			</td>';
	html 	+= '		</tr>';
	html 	+= '	</table>';
	if(typeof(tempMouseX) == 'undefined' || tempMouseX <= 0){
		var top  = "50%";
		var left = "30%";
	}else{
		var top  = tempMouseY+"px";
		var left = (((tempMouseX - 300) > 0)?(tempMouseX - 300):tempMouseX)+"px";
	}
	divMensaje.style.top  = top;
	divMensaje.style.left = left;
	divMensaje.style.fontSize = '10pt';
	divMensaje.style.width = '600px';
	divMensaje.innerHTML = html;
	divMensaje.style.display = "";
	
	return false;
}
function oc(a){
	var o = {};
	for (var i = 0; i < a.length; i++) {
		o[a[i]] = '';
	}
	return o;
}


function goToExportarConsulta(idNorma, idParte ,idVersion){
	if(idParte != 0 && idParte != ''){
		var selectNorma = idNorma+"."+idVersion+"."+idParte+".0";
	}else{
		var selectNorma = idNorma+"."+idVersion+".0.0";
	}
	
	var form = document.createElement("form");

	form.setAttribute("action",parent.urlServidor+"/../Consulta/exportarLista");
	form.setAttribute("method","get");
	form.setAttribute("id","formExpDirectaNorma");

	var InputSelectNorma = document.createElement("input");
	InputSelectNorma.setAttribute("type","hidden");
	InputSelectNorma.setAttribute("value",selectNorma);
	InputSelectNorma.setAttribute("name",'selectNorma');
	InputSelectNorma.setAttribute("id",'selectNorma');
	
	document.body.appendChild(form);
	form.appendChild(InputSelectNorma);
	
	var obj = document.createElement("input");
	obj.setAttribute("type",'checkbox');
    obj.setAttribute('idnorma',idNorma);
	obj.setAttribute('fechavigencia',idVersion);
	if (idParte != 0 && idParte != '') {
		obj.setAttribute('idpartenorma', idParte);
	}else{
		obj.setAttribute('idpartenorma', '0');
	}
	obj.setAttribute('idversionparte','0');
	obj.setAttribute('checked',true);
	
	EnviarAExportar(obj,'carritoNorma');
    recalcularCarro('carritoNorma');
	form.submit();
}

function mostrarMensajeBuscando(){
	setTimeout(function(){
	
		var div = document.getElementById('divMensajeBusqueda');
		if(!div){
			div = window.parent.document.getElementById('divMensajeBusqueda');
		}
		if(!div){
			div = window.parent.parent.document.getElementById('divMensajeBusqueda');
		}
		
		div.style.display="";
		
	},tiempoMensajeBuscando);
}
function verArchivo(id_archivo, formato) {
    var urlLocal = replace(urlServidor,"Consulta","")+"/Navegar/archivobinario?id=" +id_archivo+ "&formato=" +formato; 
    window.open(urlLocal,'','scrollbars=no,menubar=no,height=240,width=520,resizable=no,toolbar=no,location=no,status=no');
}
function descargarNormaListado(idNorma, idVersion, idParte, idVersionParte, formato, nombreArchivo){
	if (idParte && idParte != 0){
		descargarNormaListadoNormal(idNorma, idVersion, idParte, idVersionParte, formato, nombreArchivo);
		return;
	}
	
	this.succes = function(req){
		try {
			var JSON = req.responseText;
			var res = eval('(' + JSON + ')');
			if (res.paraDescargaNormal) {
				descargarNormaListadoNormal(idNorma, idVersion, idParte, idVersionParte, formato, nombreArchivo);
				return;
			}else{
				var _id_archivo_ = res.id_archivo;
				var _formato_    = res.formato;
					/* Se utiliza esta funcion para registrar la traza porque ocupa los mismos parametros*/
				RegistrarNevegarNorma(58,idNorma,idVersion,getCodigoModulo(),idParte,idVersionParte,'');
				verArchivo(_id_archivo_, _formato_);
				return;
			}
		} 
		catch (e) {
			descargarNormaListadoNormal(idNorma, idVersion, idParte, idVersionParte, formato, nombreArchivo);
		}
	};
	this.failure = function (req){
			descargarNormaListadoNormal(idNorma, idVersion, idParte, idVersionParte, formato, nombreArchivo);
	};
	var params = {
		method: 'get',
		onSuccess: this.succes,
		onFailure: this.failure,
		parameters: {
			idNorma: idNorma
		}
	};
	this.request = new Ajax.Request(parent.urlServidor + '/../Navegar/scripts/validaDescargaPDF', params);
}
function descargarNormaListadoNormal(idNorma, idVersion, idParte, idVersionParte, formato, nombreArchivo){
	var d = document;
	var radioExportar = d.createElement("input");
	var exportar_formato = d.createElement("input");
	var nombrearchivo = d.createElement("input");
	var exportar_con_notas_bcn = d.createElement("input");
	var exportar_con_notas_originales = d.createElement("input");
	var exportar_con_notas_al_pie = d.createElement("input");
	var hddResultadoExportar = d.createElement("input");
	var f = d.createElement("form");
	
	radioExportar.setAttribute("name", "radioExportar");
	exportar_formato.setAttribute("name", "exportar_formato");
	nombrearchivo.setAttribute("name", "nombrearchivo");
	exportar_con_notas_bcn.setAttribute("name", "exportar_con_notas_bcn");
	exportar_con_notas_originales.setAttribute("name", "exportar_con_notas_originales");
	exportar_con_notas_al_pie.setAttribute("name", "exportar_con_notas_al_pie");
	hddResultadoExportar.setAttribute("name", "hddResultadoExportar");
	
	radioExportar.value = "Normas";
	exportar_formato.value = formato;
	
	nombrearchivo.value = nombreArchivo;
	
	exportar_con_notas_bcn.value = "True";
	exportar_con_notas_originales.value = "True";
	exportar_con_notas_al_pie.value = "True";
	
	hddResultadoExportar.value = idNorma + "." + idVersion + "."+idParte+"."+idVersionParte+"#";
	if (typeof(urlServidor) == 'undefined') {
		urlServidor = parent.urlServidor;
	}
	f.setAttribute("action", urlServidor + "/../Consulta/Exportar")
	f.setAttribute("method", "get");
	f.setAttribute("target", "_blank");
	f.style.display = "none";
	d.body.appendChild(f);
	
	f.appendChild(radioExportar);
	f.appendChild(exportar_formato);
	f.appendChild(nombrearchivo);
	f.appendChild(exportar_con_notas_bcn);
	f.appendChild(exportar_con_notas_originales);
	f.appendChild(exportar_con_notas_al_pie);
	f.appendChild(hddResultadoExportar);
	
	/* Se utiliza esta funcion para registrar la traza porque ocupa los mismos parametros*/
	RegistrarNevegarNorma(58,idNorma,idVersion,getCodigoModulo(),idParte,idVersionParte,'');
	
	f.submit();
	
}
function exportarMetadatosSeleccionados(formato,busqueda){
	var d = document;
	var radioExportar = d.createElement("input");
	var exportar_formato = d.createElement("input");
	var nombrearchivo = d.createElement("input");
	var hddResultadoExportar = d.createElement("input");
	var f = d.createElement("form");
	

	radioExportar.setAttribute("name", "radioExportar");
	exportar_formato.setAttribute("name", "exportar_formato");
	nombrearchivo.setAttribute("name", "nombrearchivo");
	hddResultadoExportar.setAttribute("name", "hddResultadoExportar");
	
	radioExportar.value = "Aciertos";
	exportar_formato.value = formato;
	
	nombrearchivo.value = "Aciertos_" + busqueda;
	
	var carritoNorma = getCookie("carritoNorma");
	if (!carritoNorma){
		return;//Nada que exportar
	}
	hddResultadoExportar.value = carritoNorma+"#";
	if (typeof(urlServidor) == 'undefined') {
		urlServidor = parent.urlServidor;
	}
	f.setAttribute("action", urlServidor + "/../Consulta/Exportar")
	f.setAttribute("method", "post");
	f.setAttribute("target", "_blank");
	f.style.display = "none";
	d.body.appendChild(f);

	f.appendChild(radioExportar);
	f.appendChild(exportar_formato);
	f.appendChild(nombrearchivo);
	f.appendChild(hddResultadoExportar);
	
	f.submit();
}

function eligeRegion(id){
	var sel = $('region');
	for (var i = 0; i < sel.length; i++) {
		if (sel[i].value == id) {
			sel[i].selected = true;
			break;
		}
	}
}

function exportarACsvLR(){
	var form = $('formExportarACsvLR');
	if (form){
		form.submit();
	}
}
function showMsgEncuesta(){
	try{	
		revisaLogueado();
	}catch(e){
	}
	var id_session_encuesta_real = getCookie("id_session_encuesta_real");
	if (id_session_encuesta_real){
		return true;
	}
	Shadowbox.open($('link_to_open_shadow'));
}
function continuarConEncuesta(op){
	$('divMsgEncuesta').style.display = "none";
	setCookie("id_session_encuesta_real",getCookie("id_session_encuesta"), 100, '/','','' );
	if(op=='si'){
		window.location.href = parent.urlServidor+"/../Consulta/encuesta";
	}
}

function prepararPaginaEncuesta(){
	$('sb-nav-close').onclick = onclickCerrarEncuesta;
	var id_session_encuesta_real = getCookie("id_session_encuesta_real");
	if (!id_session_encuesta_real){
		var d = new Date();
		var session = Math.random()*d.getTime()+Math.random();
		setCookie("id_session_encuesta_real",session, 100, '/','','' );
	}	
}
function onclickCerrarEncuesta(){
	var id_session_encuesta_real = getCookie("id_session_encuesta_real");
	Shadowbox.close();
	return false;
}


var observer = {};

observer.nextEffect = false;
observer.onPostEffect = function(e){
    if (this.nextEffect)
    {
        var eff = this.nextEffect;
        setTimeout(function(){eff.start();}, 10);
    }

    this.nextEffect = false;
}

function myPanelsSlides(currentPanel)
{
    // The list of all the panels that need sliding
    var panels = ['slide1'];
    var opened = -1;

    // Let's check if we have an effect for each of these sliding panels
    if (typeof effects == 'undefined')
        effects = {};

    for (var i=0; i < panels.length; i++)
    {
        if (typeof effects[panels[i]] == 'undefined'){
            effects[panels[i]] = new Spry.Effect.Slide(panels[i], {from: '0%', to: '100%', toggle: true});
            effects[panels[i]].addObserver(observer);
        }
         
        if (effects[panels[i]].direction == Spry.forwards)
            opened = i;

        //prevent too fast clicks on the buttons
        if (effects[panels[i]].direction == Spry.backwards && effects[panels[i]].isRunning)
        {
            observer.nextEffect = effects[currentPanel];
            return;
        }
    }

    if (opened != -1)
    {

       if (effects[currentPanel].direction == Spry.forwards &&   panels[opened] == currentPanel ){
          observer.nextEffect = new Spry.Effect.Slide(currentPanel, {from: '0%', to: '0%', toggle: true});
          effects[panels[opened]].start();
        }
        else
        {
             observer.nextEffect = effects[currentPanel];
              effects[panels[opened]].start();
        }


    } 
    else if (effects[currentPanel].direction != Spry.forwards)
    {

        effects[currentPanel].start();
    }
};


//This code was created by the fine folks at Switch On The Code - http://blog.paranoidferret.com
//This code can be used for any purpose

function animate(elementID, newLeft, newTop, newWidth, newHeight, time, callback)
{
  var el = document.getElementById(elementID);
  if(el == null)
    return;
 
  var cLeft = parseInt(el.style.left);
  var cTop = parseInt(el.style.top);
  var cWidth = parseInt(el.style.width);
  var cHeight = parseInt(el.style.height);
 
  var totalFrames = 1;
  if(time> 0)
    totalFrames = time/40;

  var fLeft = newLeft - cLeft;
  if(fLeft != 0)
    fLeft /= totalFrames;
 
  var fTop = newTop - cTop;
  if(fTop != 0)
    fTop /= totalFrames;
 
  var fWidth = newWidth - cWidth;
  if(fWidth != 0)
    fWidth /= totalFrames;
 
  var fHeight = newHeight - cHeight;
  if(fHeight != 0)
    fHeight /= totalFrames;
   
  doFrame(elementID, cLeft, newLeft, fLeft,
      cTop, newTop, fTop, cWidth, newWidth, fWidth,
      cHeight, newHeight, fHeight, callback);
}

function doFrame(eID, cLeft, nLeft, fLeft,
      cTop, nTop, fTop, cWidth, nWidth, fWidth,
      cHeight, nHeight, fHeight, callback)
{
   var el = document.getElementById(eID);
   if(el == null)
     return;

  cLeft = moveSingleVal(cLeft, nLeft, fLeft);
  cTop = moveSingleVal(cTop, nTop, fTop);
  cWidth = moveSingleVal(cWidth, nWidth, fWidth);
  cHeight = moveSingleVal(cHeight, nHeight, fHeight);

  el.style.left = Math.round(cLeft) + 'px';
  el.style.top = Math.round(cTop) + 'px';
  el.style.width = Math.round(cWidth) + 'px';
  el.style.height = Math.round(cHeight) + 'px';
 
  if(cLeft == nLeft && cTop == nTop && cHeight == nHeight
    && cWidth == nWidth)
  {
    if(callback != null)
      callback();
    return;
  }
   
  setTimeout( 'doFrame("'+eID+'",'+cLeft+','+nLeft+','+fLeft+','
    +cTop+','+nTop+','+fTop+','+cWidth+','+nWidth+','+fWidth+','
    +cHeight+','+nHeight+','+fHeight+','+callback+')', 40);
}

function moveSingleVal(currentVal, finalVal, frameAmt)
{
  if(frameAmt == 0 || currentVal == finalVal)
    return finalVal;
 
  currentVal += frameAmt;
  if((frameAmt> 0 && currentVal>= finalVal)
    || (frameAmt <0 && currentVal <= finalVal))
  {
    return finalVal;
  }
  return currentVal;
}

function slideLogin(elementId, headerElement)
{
   var element = document.getElementById(elementId);
   
   
   if (element.style.display == 'none'){
      element.style.display = '';
      SetPositionObjectByOtherObject(element, headerElement,-9,24);
   }
   var posy = findPosY(headerElement); 
   var posx = findPosX(headerElement); 
   if(element.down == null || element.up)
   {
	//elementId, newLeft, newTop, newWidth, newHeight, time
      animate(elementId, posx - 9, posy + 24, 200, 173, 250, null);
      element.up = false;
      element.down = true;
   }
   else
   {
	//elementId, newLeft, newTop, newWidth, newHeight, time
      animate(elementId, posx - 9, posy + 24, 200, 0, 250, null);
      element.down = false;
      element.up = true;
   }
}
