function DetectaBloqueoPops()
{
  var popup
  try
  {
    //Se crea una nueva ventana para probar si esta o no activo
    // el bloqueador de ventanas emergentes.
    //Si esta activo, se lanza el error, de lo contrario sólo se cierra la ventana creada
    if(!(popup = window.open('about:blank','_blank','width=1,height=1')))
      throw "ErrPop"
    //msj = "La ventana se creó con éxito"
    popup.close()
  }
  catch(err)
  {
    //Se captura el error, si fue por motivo de bloqueo, se muestra el mensaje de advertencia
    //Si no fue por bloque, entonces se muestra la descripción del error ocurrido.
    if(err=="ErrPop")
	  {
	      msj = "tA T E N C I Ó Nnn¡El bloqueo de popups esta activo!"
		alert(msj);
	  }
    else
    {
      msj="Hubo un erro en la página.nn"
      msj+="Descripción del error: " + err.description + "nn"
	  alert(msj);
     }
  }  
 
}
 
window.onload=function(){
  //Al terminar la carga de la página se manda a llamar a la función
  //Esto provocará el bloqueo de la ventana
  //DetectaBloqueoPops()
 }


// Global user functions

function CasoCategoria(elem)
{	
	//valor = GetRadioValue(elem);	
	valor = elem.value;
	if (valor == "Gerais e/ou Especiais")
	{
		document.getElementById("x_caso_categoria_T1").disabled = false;
		document.getElementById("x_caso_categoria_T2").disabled = false;
	}
	else
	{
		document.getElementById("x_caso_categoria_T1").value = "";
		document.getElementById("x_caso_categoria_T1").disabled = true;
		document.getElementById("x_caso_categoria_T2").value = "";
		document.getElementById("x_caso_categoria_T2").disabled = true;
	}
}

function CasoCategoriaForm(obj)
{
	valor = GetRadioValue(obj);
	if (valor == "Gerais e/ou Especiais" && document.getElementById("x_caso_categoria_T1").value == "" && document.getElementById("x_caso_categoria_T2").value == "")
		return true;
	return false;
}

function validaRutLP(obj_rut,OParam)
{	
	obj_rut.value = obj_rut.value.toUpperCase();
	texto = obj_rut.value;
	if (OParam == 'E')
	{
		obj_rut.value = formatCpfCnpj(texto, true, true);
		if (isCnpj(texto))
		{
			return true;
		}
	}
	else
	{
		obj_rut.value = formatCpfCnpj(texto, true);
		if (isCpf(texto))
		{
			return true;
		}
	}
	obj_rut.select();
	obj_rut.value = "";
	obj_rut.focus();
	return false;
}

function validaRut(obj_rut,OParam)
{
	ew_AjaxAutoFill_Clear(obj_rut,true);
	obj_rut.value = obj_rut.value.toUpperCase();
	texto = obj_rut.value;
	if (OParam == 'E')
	{
		obj_rut.value = formatCpfCnpj(texto, true, true);
		if (isCnpj(texto))
		{
			return true;
		}		
		//alert("El valor ingresado no corresponde a un CNPJ valido.");
		alert("O valor digitado não corresponde a um CNPJ válido.");		
	}
	else
	{
		obj_rut.value = formatCpfCnpj(texto, true);
		if (isCpf(texto))
		{
			return true;
		}
		//alert("El valor ingresado no corresponde a un CPF valido.");
		alert("O valor digitado não corresponde a um CPF válido.");				
	}	
	obj_rut.select();
	obj_rut.value = "";
	obj_rut.focus();
	return false;
}

function validaRut_Chile(obj_rut,OParam)
{
  ew_AjaxAutoFill_Clear(obj_rut,true);
  obj_rut.value = obj_rut.value.toUpperCase();
  texto = obj_rut.value;
  
  var tmpstr = "";
  
  if ( obj_rut.value==0 ) 
	{
		alert( "Ingrese su R.U.T.");
		obj_rut.select();
		obj_rut.value = "";
		obj_rut.focus();
		return false;
	}	  

  for ( i=0; i < texto.length ; i++ )
    if ( texto.charAt(i) != ' ' && texto.charAt(i) != '.' && texto.charAt(i) != '-' )
      tmpstr = tmpstr + texto.charAt(i);
  texto = tmpstr;
	  
  largo = texto.length;

  if ( largo < 7 )
  {
	alert("El valor ingresado no corresponde a un R.U.T valido.");
    obj_rut.select();
	obj_rut.value = "";
    obj_rut.focus();
    return false;
  }


  for (i=0; i < largo ; i++ )
  { 
    if ( texto.charAt(i) !="0" && texto.charAt(i) != "1" && texto.charAt(i) !="2" && texto.charAt(i) != "3" && texto.charAt(i) != "4" && texto.charAt(i) !="5" && texto.charAt(i) != "6" && texto.charAt(i) != "7" && texto.charAt(i) !="8" && texto.charAt(i) != "9" && texto.charAt(i) !="k" && texto.charAt(i) != "K" ) 
    {
		alert("El valor ingresado no corresponde a un R.U.T valido.");
      	obj_rut.select();
		obj_rut.value = "";
		obj_rut.focus();
		return false;
    }
  }
	
  if ( checkDV(obj_rut) )	{
	  largo =  obj_rut.value.length;
	  //alert(obj_rut.value.substring(largo - 2, largo - 1));
	  if (obj_rut.value.substring(largo - 2, largo - 1)!='-')
	  {
		  	  obj_rut.value = obj_rut.value.substring(0, largo - 1)+'-'+obj_rut.value.charAt(largo-1);
	  }
//	  obj_rut.value = obj_rut.value.substring(0, largo - 1)+'-'+obj_rut.value.charAt(largo-1);		
	  return true;
  }

	alert("El valor ingresado no corresponde a un R.U.T valido.");
	obj_rut.select();
	obj_rut.value = "";
	obj_rut.focus();
	return false;
}

function checkDV( obj_rut )

{
  texto = obj_rut.value;  
  var tmpstr = "";
  for ( i=0; i < texto.length ; i++ )
    if ( texto.charAt(i) != ' ' && texto.charAt(i) != '.' && texto.charAt(i) != '-' )
      tmpstr = tmpstr + texto.charAt(i);
  texto = tmpstr;
	  
  largo = texto.length;
  if ( largo < 2 )
  {
	alert("Debe ingresar el rut completo.");
	obj_rut.select();
	obj_rut.value = "";
	obj_rut.focus();
    return false;
  }

  if ( largo > 2 )
    rut = texto.substring(0, largo - 1);
  else
    rut = texto.charAt(0);
  dv = texto.charAt(largo-1);
  if (!checkCDV(dv))
  {
	obj_rut.select();
	obj_rut.value = "";
	obj_rut.focus();
  }

  if ( rut == null )
      return 0

  var dvr = '0'

  suma = 0
  mul  = 2

  for (i= rut.length -1 ; i >= 0; i--)
  {
    suma = suma + rut.charAt(i) * mul
    if (mul == 7)
      mul = 2
    else    
      mul++
  }


  res = suma % 11
  if (res==1)
    dvr = 'k'
  else if (res==0)
    dvr = '0'
  else
  {
    dvi = 11-res
    dvr = dvi + ""
  }

  if ( dvr != dv.toLowerCase() )
  {
    obj_rut.value = "";
    obj_rut.focus();
    return false
  }
  return true
}

function checkCDV( dvr ){
  dv = dvr + ""
  if ( dv != '0' && dv != '1' && dv != '2' && dv != '3' && dv != '4' && dv != '5' && dv != '6' && dv != '7' && dv != '8' && dv != '9' && dv != 'k'  && dv != 'K')
  { return false; } return true;
}


function emailCheck(elem) {
	emailStr = elem.value
	var emailPat=/^(.+)@(.+)$/;
	var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]";
	var validChars="\[^\\s" + specialChars + "\]";
	var quotedUser="(\"[^\"]*\")";
	var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;
	var atom=validChars + '+';
	var word="(" + atom + "|" + quotedUser + ")";
	var userPat=new RegExp("^" + word + "(\\." + word + ")*$");
	var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");
	var matchArray=emailStr.match(emailPat);
	if (matchArray==null) {
		//alert("Dirección de correo inválida (comprobar @ y .'s)");
		alert("Endereço de e-mail inválido");
		elem.focus();
		return false;
	}
	var user=matchArray[1];
	var domain=matchArray[2];

	if (user.match(userPat)==null) {
		//alert("El usuario no parece ser válido.");
		alert("Endereço de e-mail inválido.");
		elem.focus();
		return false;
	}
	
	var IPArray=domain.match(ipDomainPat);
	if (IPArray!=null) {
		  for (var i=1;i<=4;i++) {
			if (IPArray[i]>255) {
				//alert("IP de destino incorrecta.");
				alert("Endereço de e-mail inválido.");
				elem.focus();
				return false;
			}
		}
		return true;
	}
	
	var domainArray=domain.match(domainPat);
	if (domainArray==null) {
		alert("Endereço de e-mail inválido.");
		//alert("El dominio no parece ser válido.");
		elem.focus();
		return false;
	}
	
	var atomPat=new RegExp(atom,"g");
	var domArr=domain.match(atomPat);
	var len=domArr.length;
	if (domArr[domArr.length-1].length<2 || 
		domArr[domArr.length-1].length>3) {
	   // the address must end in a two letter or three letter word.
	   //alert("La dirección e-mail debe terminar con un dominio de 3 letras, o un nombre de país de dos letras.");
		alert("Endereço de e-mail inválido.");
	   elem.focus();
	   return false;
	}

	if (len<2) {
	   //var errStr="¡A esta dirección le falta un nombre de host!";
		var errStr="Endereço de e-mail inválido.";
	   alert(errStr);
	   elem.focus();
	   return false;
	}
	return true;
}

function soloNumeros(Objeto, Evento, strAnexoCaracteres) // Se aplica en el onKeyPress (javascript: return soloNumeros(this, event);)
{
 with(Evento){
	 
	if(navigator.appName.indexOf("Microsoft") != -1) {
		codCaracter=keyCode;
	}else {
		codCaracter=Evento.charCode;
	}

	if (strAnexoCaracteres==undefined){
		strAnexoCaracteres='';
	}

	var strCaracteresAceptados = "1234567890 " + strAnexoCaracteres;
	if (strCaracteresAceptados.indexOf(String.fromCharCode(codCaracter))==-1){
		if(codCaracter==0){
				return true;
		}else{
			return false;
		}
	}else{
		return true;
	}
 }  
}
	
function isNum(argvalue) {
	argvalue = argvalue.toString();
	if (argvalue.length == 0)
		return false;
	for (var n = 0; n < argvalue.length; n++)
		if (argvalue.substring(n, n+1) < "0" || argvalue.substring(n, n+1) > "9")
			return false;
	return true;
}

function acceptNum(evt){
var nav4 = window.Event ? true : false;
var key = nav4 ? evt.which : evt.keyCode;	
return (key <= 13 || (key >= 48 && key <= 57));
}

function GetRadioValue( radioObject ) { 
	var value = null;

	// Validate parameter value
//***	if (radioObject+"" == "undefined" || radioObject == null)
	if (radioObject == null)
		return null;

	for (var i=0; i < radioObject.length; i++) { 
		if (radioObject[i].checked) { 
			value = radioObject[i].value;
			break;
		} 
	} // end for loop 
	
	return value;
}

function textCounter(field, countfield, maxlimit)
{
	if (field.value.length > maxlimit) // if too long...trim it!
		field.value = field.value.substring(0, maxlimit);
		// otherwise, update 'characters left' counter
	else 
		countfield.value = maxlimit - field.value.length;
}

// Auto fill text boxes by AJAX
function ew_AjaxAutoFill_Clear(obj, async) {
	if (!(document.getElementsByTagName || document.all))
		return;
	try {		
			var destnames = eval('obj.form.ln_' + obj.name + '.value');
			var dest_array = destnames.split(',');
			for (var j=0; j<dest_array.length; j=j+1)
			{
				var destobj = ew_GetFormElement(obj.form, dest_array[j]);
				if ((destobj))
					destobj.value = '';
			}
		}
	catch (e) {}
}

function Ventana(url, ancho, alto)
{	
	var myWidth = ancho;
	var myHeight = alto;
	var myLeft = (screen.width-myWidth)/2;
	var myTop = (screen.height-myHeight)/2;	
	var param='toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,width='+ancho+',height='+alto+',left=' + myLeft + ',top=' + myTop
	day = new Date();
	id = day.getTime();
	eval("page" + id + " = window.open('" + url + "', 'page" + id + "','"+param+"');");
}

String.prototype.Trim = function(){
  return this.replace(/\s+$|^\s+/g,""); 
}

String.prototype.LTrim = function(){
   return this.replace(/^\s+/,""); 
}

String.prototype.RTrim = function(){
	return this.replace(/\s+$/,""); 
}

function Trim_Nom_Propio(elemento){
	str = elemento.value;
	str = str.Trim();
	str = str.toLowerCase();
	while (str.indexOf("  ") > 0)
	{
		str = str.substring(0,str.indexOf("  ")) + str.substring(str.indexOf("  ") + 1,str.length);
	}
	
	var partes = str.split(" ");
	var part_num=0;
	var Dato = '';
	while (part_num < partes.length)
	{
		palabra = partes[part_num];
		letra = palabra.substring(0,1);
		letra = letra.toUpperCase();
		Dato = Dato + letra + palabra.substring(1,palabra.length) + ' ';
		part_num+=1;
	}
	elemento.value = Dato.Trim();
}

function izq(str){
  str = str.LTrim();

}

function dcha(str){
  str = str.RTrim();
}

function LCase(element)
{
valor = element.value;
element.value = valor.toLowerCase();
}

function CargarFoto(img){
  string="toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=1";
  window.open(img,"",string);
}

String.prototype.fechaDDMMAAAA = function() {
	return this.replace(/^(\d{2})\/(\d{2})\/(\d{4})$/, "$2/$1/$3");
}
String.prototype.fechaMMDDAAAA = function() {
	return this.replace(/^(\d{2})\/(\d{2})\/(\d{4})$/, "$2/$1/$3");
}

function getTimestamp(fecha_dd_mm_yyyy)
{
var dia_aux = parseInt(fecha_dd_mm_yyyy.substring(0, 2),10);
var mes_aux = parseInt(fecha_dd_mm_yyyy.substring(3, 5),10);
var ano_aux = parseInt(fecha_dd_mm_yyyy.substring(6, 10),10);
var fecha = new Date();
fecha.setDate(dia_aux);
fecha.setMonth(mes_aux-1);
fecha.setFullYear(ano_aux);
fecha.setHours(0);
fecha.setMinutes(0);
fecha.setSeconds(0);
fecha.setMilliseconds(0);
var timestamp = parseInt(fecha.getTime(),10);

var pepe = new Date(timestamp);
//alert(timestamp+', '+fecha.getTime()+', '+pepe.getDate()+'-'+(pepe.getMonth()+1)+'-'+pepe.getFullYear());

return timestamp;
}

function FormateaValor(campo,tammax,teclapres) {
	with(teclapres)
	{
		if(navigator.appName.indexOf("Microsoft") != -1){
			tecla=keyCode;
		}else {
			tecla=teclapres.charCode;
		}
		
		vr = document.getElementById(campo).value;
		vr = vr.replace( "/", "" );
		vr = vr.replace( "/", "" );     
		vr = vr.replace( ",", "" );   
		vr = vr.replace( ".", "" ); 
		vr = vr.replace( ".", "" ); 
		vr = vr.replace( ".", "" ); 
		vr = vr.replace( ".", "" );  
		tam = vr.length;
		 
		if (tam < tammax && tecla != 8){ tam = vr.length + 1 ; }

		if (tecla == 8 ){    tam = tam - 1 ; }
			
		if ( tecla == 8 || tecla >= 48 && tecla <= 57 || tecla >= 96 && tecla <= 105 ){
			 if ( tam <= 2 ){ 
				 document.getElementById(campo).value = vr ; }
			 if ( (tam > 2) && (tam <= 5) ){
				 document.getElementById(campo).value = vr.substr( 0, tam - 2 ) + ',' + vr.substr( tam - 2, tam ) ; }
			 if ( (tam >= 6) && (tam <= 8) ){
				 document.getElementById(campo).value = vr.substr( 0, tam - 5 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam ) ; }
			 if ( (tam >= 9) && (tam <= 11) ){
				 document.getElementById(campo).value = vr.substr( 0, tam - 8 ) + '.' + vr.substr( tam - 8, 3 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam ) ; }
			 if ( (tam >= 12) && (tam <= 14) ){
				 document.getElementById(campo).value = vr.substr( 0, tam - 11 ) + '.' + vr.substr( tam - 11, 3 ) + '.' + vr.substr( tam - 8, 3 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam ) ; }
			 if ( (tam >= 15) && (tam <= 17) ){
				 document.getElementById(campo).value = vr.substr( 0, tam - 14 ) + '.' + vr.substr( tam - 14, 3 ) + '.' + vr.substr( tam - 11, 3 ) + '.' + vr.substr( tam - 8, 3 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam ) ;}
		}		
	}
}


function IsCEP(strCEP, elem)
{	
	var objER = /^[0-9]{5}-[0-9]{3}$/;
	strCEP = strCEP.Trim();
	if(strCEP.length > 0)
	{
		strCEP = '000000000' + strCEP;
		partes = strCEP.split('-');
		palabra = '';
		part_num = 0;
		while (part_num < partes.length)
		{
			palabra = palabra + partes[part_num];
			part_num+=1;
		}

		iLen = palabra.length;
		palabra = palabra.substring(iLen-8, iLen);
		//alert (palabra);
		iLen = palabra.length;
		sufijo  = palabra.substring(iLen-3, iLen);		
		//alert (sufijo);
		prefijo = palabra.substring(0, 5);
		strCEP = prefijo + '-' + sufijo;
		//alert (strCEP);
		if(objER.test(strCEP))
		{
			elem.value = strCEP;
			return true;
		}
		else
		{
			return false;
		}
	}
	else
	{
		return true;
	}
}