var versionJs = 19;
var _tools_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
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 NavegarNorma(idNorma,idParte,idVersion, buscar, revisarNormasGrandes,target,tipoVersion){
	if ((idNorma == '') || (idNorma == '0') || (idNorma == 0)) {
		alert("Norma no navegable por falta de datos");
		return;
	}
	if (revisarNormasGrandes == false) {
		revisarNormasGrandes = false;
	}else{
		revisarNormasGrandes = "check";
	}
	
	if(typeof(target)=='undefined'){
		target = null;
	}
    if(typeof(tipoVersion)=='undefined'){
		tipoVersion = 1;
	}
	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')
	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!=0 && tipoVersion!=2 && 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 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 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');
	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;
		}
	}
	var divMensajeBusqueda = $('divMensajeBusqueda');
	if (divMensajeBusqueda){
		divMensajeBusqueda.style.display = "none";
	}
	if (window.location.href.indexOf("registro") > -1){
		return true;
	}
	var forms = document.getElementsByTagName("form");
	for (var i=0;i<forms.length;i++){
		forms[i].setAttribute("method","get");
	}
	return true;
};
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");

function esModulo(modulo){
	
	for(var i=0;i<modulosGenerales.length;i++){
		if(modulosGenerales[i]==modulo){
			return true;
		}	
	}
	return false;
}

function SeleccionaMenuActual(){
	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;
		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("pac_name").value;
	var clave = document.getElementById("__ac_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 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");
	//alert(msje.innerHTML);
	cookiemsj =getCookie("msjes")
	//alert(cookiemsj);
	if((cookiemsj!="")&&(cookiemsj!=null)&&(cookiemsj!="\"None\"")&&(cookiemsj!="None")){
		divmsje.style.display = "block";
		
		var variable = cookiemsj;
		/*variable = variable.replace("Sera", "Será");
		variable = variable.replace("habiles", "hábiles");
		variable = variable.replace("dias", "días");*/

		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];
		}
		//alert(user);
		//document.getElementById("hLostUser").value = user;
		var url = "loginback?hLostUser="+correo;
		Cargar(url);
		//document.getElementById("frmRecClave").submit();
	}
	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="No hay 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 += '				Esta norma es muy grande, y su navegador es '+nameAppVersion+', que es lento.<br />';
	}
	if (!comparar) {
		html += '	Recomendamos descargar el pdf.<br />'
		html += '	<li style="margin-left:40px"><a href="javascript:descargarNormaListado(\'' + idNorma + '\', \''+ idVersion + '\', \'' + idParte + '\', \'' + 0 +  '\', \'' + pdf +  '\', \'' + NORMA+idNorma+idParte +  '\' );"><img border="0" src="imagenes_Consulta/iconos/ic_pdf.gif" /> <b>descargar pdf</b></a><br /></li>';
		html += '	<li style="margin-left:40px"><a href="javascript:NavegarNorma(\'' + idNorma + '\', \'' + idParte + '\', \'' + idVersion + '\', \'' + buscar + '\',false,\''+target+'\','+tipoVersion+');"><b>ver norma</b></a><br /><br /></li>';
	}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.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=320,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();
	}
}
