
/**
 * Globals.js
 *
 * @package Gestion Clientes
 * @subpackage include
 * @author Maria Cortez
 * @version 0.1.0
 * @copyright * (c) 2005 Grupo Deltron, Todos los derechos Reservados.
 * 
 * @filesource
 */

	
	/**
	 * Función que abre una ventana popup
	 */		
	function popup(url,x,y,name,sb,rs,st,lt,tb) 
	{
		var win = null;
		var centerwidth=(screen.width/2)-(x/2);
		var centerheight=(screen.height/2)-(y/2);
		var scrollbarstext = 'scrollbars = no,';
		var resizabletext = 'resizable = no,';
		var statustext = 'status = no,';
		var locationtext = 'location = no,';
		var toolbartext = 'toolbar = no,';
		var features = '';
		if (sb == 1){
			scrollbarstext = 'scrollbars = yes,'
		}
		if (rs == 1){
			resizabletext = 'resizable = yes,'
		}
		if (st == 1){
			statustext = 'status = yes,'
		}
		if (lt == 1){
			locationtext = 'location = yes,'
		}
		if (tb == 1){
			toolbartext = 'toolbar = yes,'
		}
		features = scrollbarstext+resizabletext+statustext;
		features = features + locationtext+toolbartext;
		features = features + 'width = '+x+',height = '+y;
		features = features + ',top = ' + centerheight;
		features = features + ',left = ' + centerwidth;
		win = window.open(url, name, features);
	}
	
	/**
	 * Función que coloca el focus en un campo
	 */	
	function focusOn(field) {
		field.focus();
	}
	
	/**
	 * Función que valida si lo ingresado es un email
	 */	
	function isEmailAddress(field)
	{
		//var s = theElement.value;
		//var filter=/^[A-Za-z][A-Za-z0-9_.]*@[A-Za-z0-9_]+\.[A-Za-z0-9_.]+[A-za-z]$/;
		var filter=/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
		if (field.length == 0 ) return true;
		if (filter.test(field))
			return true;
		else
			return false;
	}
	/**
	 * Función que solo permite el ingreso de letras
	 * se utiliza con las funciones: onKeyDown="validarletras(formulario.txt_campo)" 
	 * y onKeyUp="validarletras(formulario.txt_campo)"
	 */		
	function validarletras(form)
	{
		val = form.value.length
		tex=form.value
		val=val-1
		tex1 = tex.charAt(val);
		tex2 = encodeURIComponent(tex1)
		if(((!isNaN(tex1))||(tex1!=tex2)||(tex1=='*')||(tex1=='-')||(tex1=='_')||(tex1=='.')||(tex1=='(')||(tex1==')'))&&(tex1!=' ')&&(tex1!='ñ')&&(tex1!='Ñ'))
		{
			form.value = tex.substring(0,val)
		}
	}

	/**
	 * Función que solo permite el ingreso de Numeros
	 * Se utiliza con las funciones: onKeyDown="validarnumeros(formulario.txt_campo)" 
	 * y onKeyUp="validarnumeros(formulario.txt_campo)"
	 */		
	function validarnumeros(form)
	{
	     val=form.value.length
		 tex=form.value
		 val=val-1
		 tex1 = tex.charAt(val);
		 if((isNaN(tex1))||(tex1==' '))
		 {
			form.value = tex.substring(0,val)
		 }
	}
	
	/** 
	 * Funcion que restringe el ingreso de caracteres espeiales solo alfanumericos 
	 */		
	function validartexto(form)
	{
    	val=form.value.length
		tex=form.value
		val=val-1
		tex1 = tex.charAt(val);
		tex2 = encodeURIComponent(tex1)
		if(((tex1!=tex2)||(tex1=='*')||(tex1=='!')||(tex1=='_')||(tex1=='(')||(tex1==')'))&&(tex1!=' ')&&(tex1!='ñ')&&(tex1!='Ñ')&&(tex1!='&')&&(tex1!='@'))
		{
			form.value = tex.substring(0,val)
		}
	}
	
	/** 
	 * Funcion que centra la posicion de una ventana
	 */	
	function centraVentana(ancho,alto) 
	{
		if (window.screen) {
			var aw = screen.availWidth;var ah = screen.availHeight;window.resizeTo(ancho,alto);window.moveTo((aw-ancho)/2,(ah-alto)/2);
		}
	}
	
	/** 
	 * Verifica si algun checkBox esta activado
	 */		
	function algunCheck(form)
	{
		for(i=0 ; i<form.elements.length; i++){
			if(form.elements[i].type == "checkbox"){
				if(form.elements[i].checked){
					return true;
					exit();
				}
			}
		}
		return false;
	}
	
	/** 
	 * Valida la cadena Hora
	 */		
	function validarHora(strHora)
	{
		if (longitudcorrecta(strHora, 5)) {
			strHora += ":00";
		}
		return !(!(/[0-2][0-9]:[0-5][0-9]:[0-5][0-9]/.test(strHora)) || (strHora.substring(0,2)<0 || strHora.substring(0,2)>23));
	}
	
	/** 
	 * Asigna Formato a la Fecha
	 */		
	function formateafecha(valor)
	{
	  var l = StringTokenizer(valor, "/");
	  return rellena(l[0], "0", 2) + "/" + rellena(l[1], "0", 2) + "/" + l[2];
	}
	
	/** 
	 * Verifica si el formato de telefono es correcto
	 */		
	function estelefono(valor)
	{
	  var pattern = "/\\b(^(\\d+)(\\-\\d+)$)\\b/gi";
		return valor.match(eval(pattern));
	}
	
	/** 
	 * Verifica si el numero es entero
	 */		
	function esEntero(numero)
	{
	  tokens = StringTokenizer(numero, '.');
	  return ( (tokens.length<=1)&&(esnumero(numero)) );
	}
	
	/** 
	 * Valida valor decimal
	 */		
	function validaDecimal(numero, dec)
	{
	  tokens = StringTokenizer(numero, '.');
	  return (( tokens.length>1 )? (tokens[tokens.length-1].length > 0 && tokens[tokens.length-1].length <= dec) : true)&&(esdecimal(numero));
	}
	
	/** 
	 * Verifica si el numero es decimal
	 */		
	function esdecimal(valor)
	{
	  var pattern = "/\\b(^(\\d+)(\\.\\d+)$)\\b/gi";
		return valor.match(eval(pattern));
	}
	
	/* fn & ext Rt T F */
	function validanombrearchivo(nombre, ext)
	{
	  var pattern = "/\\b(^(((\\S)|(\\s))+)(\\."+ext+")$)\\b/gi";
		return nombre.match(eval(pattern));
	}
	
	/** 
	 * Divide la cadena de acuerdo a un delimitador
	 * Retona Array
	 */	
	function StringTokenizer(cad, delim)
	{
	  var cads = new Array();
	  var n = cad.length;
	  var j = 0;
	  var ic = 0;
	  for (i=0;i<n;i++){
	    if ( cad.charAt(i)==delim ){ cads[j] = cad.substring(ic, i); ic = i+1; j++; }
	  }
	  cads[j] = cad.substring(ic, n);
	  return cads;
	}
	
	/** 
	 * Convierte el mes ingresado en letras
	 * Rt m ltr: mes # / 1-12, may 1 o 0 M o m, cap 1 o 0 M 1ra lt
	 */
	function mesenletras(mes, may, cap)
	{
	  if ( !esnumero(mes) ) return "-";
	  var imes = parseInt(mes, 10);
	  var tmes = "";
	  if ( imes == 1 ) tmes = "enero";
	  else if ( imes == 2 ) tmes = "febrero";
	  else if ( imes == 3 ) tmes = "marzo";
	  else if ( imes == 4 ) tmes = "abril";
	  else if ( imes == 5 ) tmes = "mayo";
	  else if ( imes == 6 ) tmes = "junio";
	  else if ( imes == 7 ) tmes = "julio";
	  else if ( imes == 8 ) tmes = "agosto";
	  else if ( imes == 9 ) tmes = "setiembre";
	  else if ( imes == 10 ) tmes = "octubre";
	  else if ( imes == 11 ) tmes = "noviembre";
	  else if ( imes == 12 ) tmes = "diciembre";
	  if ( may == 1) tmes = tmes.toUpperCase(); 
	  if ( cap == 1) tmes = tmes.substring(0,1).toUpperCase() + tmes.substring(1, tmes.length);
	  return tmes;
	}
	
	/** 
	 * Compara dos fechas entre si
	 * -1: err, 1: f1>f2, 2: f1<f2, 0: f1=f2 
	 */
	function comparafecha(fecha1, fecha2)
	{
	  if ( !checkdate(fecha1) || !checkdate(fecha2) ) return -1;
	  dia = fecha1.substring(0,2)
	  mes = fecha1.substring(3,5)
	  anho = fecha1.substring(6,10)
	  fecha1x = anho + mes + dia
	  dia = fecha2.substring(0,2)
	  mes = fecha2.substring(3,5)
	  anho = fecha2.substring(6,10)
	  fecha2x = anho + mes + dia
	  return (fecha1x>fecha2x?1:(fecha1x<fecha2x?2:0));
	}

	/** 
	 * Funcion Vacia, no realiza ninguna operacion
	 */
	function nada(){}
	
	/** 
	 * Divide una cadena
	 */	
	function corta(campo, longitud, cars) 
	{
	  if (campo.value.length>longitud) campo.value=campo.value.substring(0,longitud);
	  cuenta(campo, cars);
	}
	
	/** 
	 * Cuenta la longitud de una cadena
	 */	
	function cuenta(campo, cars) 
	{ 
		cars.value=campo.value.length; 
	}
	
	/** 
	 * Completa la longitud de una cadena con un caracter indicado
	 */	
	function rellena(dato, caracter, tamanho)
	{
	  dato_trim = trim(dato);
	  len = dato_trim.length;
	  dato_fill = "";
	  for (var i=0;i<tamanho-len;i++){ dato_fill+=caracter; }
	  dato_fill+=dato_trim;
	  return dato_fill;
	}
	
	/** 
	 * Verifica la Fecha
	 */	
	function checkdate(fecha)
	{
	  var err=0
	  if ( fecha.length != 10) err=1
	  dia = fecha.substring(0,2)
	  slash1 = fecha.substring(2,3)
	  mes = fecha.substring(3,5)
	  slash2 = fecha.substring(5,6)
	  anho = fecha.substring(6,10)
	  if ( dia<1 || dia>31) err = 1
	  if ( slash1 != '/' ) err = 1
	  if ( mes<1 || mes>12) err = 1
	  if ( slash1 == '/' && slash2 != '/' ) err = 1
	  if ( anho < 0 || anho > 2200 ) err = 1
	  if ( mes == 4 || mes == 6 || mes == 9 || mes == 11 ){
	    if (dia==31) err=1
	  }
	  if (mes == 2){
	    var g = parseInt(anho/4)
	    if (isNaN(g)){
	      err = 1
	    }
	    if (dia >29) err =1
	    if (dia ==29 && ((anho/4)!=parseInt(anho/4))) err=1
	  }
	  return (!(err==1));
	}
	
	/** 
	 * Verifica si un campo es nulo
	 */	
	function esnulo(campo)
	{ 
		return (campo == null||campo=="");
	}
	
	/** 
	 * Verifica si un campo es nulo o solo tiene un guion
	 */	
	function esnulooguion(campo)
	{
	  return esnulo(campo) || ( trim( campo ) == "-" );
	}
	
	/** 
	 * Verifica si es numero
	 */	
	function esnumero(campo)
	{ 
		return (!(isNaN( campo )));
	}
	
	/** 
	 * Verifica que un campo tenga la longitud correcta
	 */	
	function longitudcorrecta( campo, len )
	{
	  if ( campo != null ) return ( campo.length == len );
	  else return false;
	}
	
	/** 
	 * Convierte campo en mayuscula
	 */
	function mayuscula(campo)
	{
		return campo.toUpperCase();
	}
	
	/** 
	 * Convierte campo en minuscula
	 */	
	function minuscula(campo)
	{
		return campo.toLowerCase();
	}
	
	/** 
	 * Verifica longitud de cadena de RUC
	 */	
	function eslongrucok(ruc)
	{
		return ( ruc.length == 11 );
	}
	
	/** 
	 * Verifica longitud de cadena de contraseña
	 */	
	function eslongcontrasenhaok(contrasenha)
	{
	  return (contrasenha.length >= longcontrasenhaok());
	}
	
	/** 
	 * Establece longitud de contraseña
	 */	
	function longcontrasenhaok()
	{
		 return 6;
	}
	
	/** 
	 * Verifica si un valor es negativo
	 */	
	function esnegativo(valor)
	{ 
		return (valor < 0);
	}
	
	/** 
	 * Valida cadena de RUC
	 */	
	function esrucok(ruc)
	{
	  return (!( esnulo(ruc) || !esnumero(ruc) || !eslongrucok(ruc) || !valruc(ruc) ));
	}
	
	/** 
	 * Verifica valor de RUC
	 */	
	function valruc(valor)
	{
		
	  valor = trim(valor)
	  if ( esnumero( valor ) ) {
	    if ( valor.length == 8 ){
	      suma = 0
	      for (i=0; i<valor.length-1;i++){
	        digito = valor.charAt(i) - '0';
	        if ( i==0 ) suma += (digito*2)
	        else suma += (digito*(valor.length-i))
	      }
	      resto = suma % 11;
	      if ( resto == 1) resto = 11;
	      if ( resto + ( valor.charAt( valor.length-1 ) - '0' ) == 11 ){
	        return true
	      }
	    } else if ( valor.length == 11 ){
	      suma = 0
	      x = 6
	      for (i=0; i<valor.length-1;i++){
	        if ( i == 4 ) x = 8
	        digito = valor.charAt(i) - '0';
	        x--
	        if ( i==0 ) suma += (digito*x)
	        else suma += (digito*x)
	      }
	      resto = suma % 11;
	      resto = 11 - resto
	      
	      if ( resto >= 10) resto = resto - 10;
	      if ( resto == valor.charAt( valor.length-1 ) - '0' ){
	        return true
	      }      
	    }
	  }
	  return false
	}
	
	/** 
	 * Valida si longitud es mayor que la indicada
	 */	
	function longitudmayor( campo, len )
	{
	  return ( campo != null )? (campo.length > len) : false;
	}
	
	/** 
	 * Validar si un campo se encuentra entre 2 parametros dados
	 */	
	function estaentre(campo, inicio, fin)
	{
	  if ( campo != null ) return ( campo.length >= inicio && campo.length <= fin );
	  else return false;
	}
	
	//Se define variables
	var da = (document.all) ? 1 : 0;
	var pr = (window.print) ? 1 : 0;
	var mac = (navigator.userAgent.indexOf("Mac") != -1); 
	
	/** 
	 * Imprime Paginas
	 */	
	function printPage(frame, arg) 
	{
	  if (frame == window){printThis();}
	  else {link = arg; printFrame(frame); }
	  return false;
	}
	
	/** 
	 * Imprime Pagina Actual
	 */
	function printThis() 
	{
	  if (pr) { // NS4, IE5
	    window.print();
	  } else if (da && !mac) { // IE4 (Windows)
	    vbPrintPage();
	  } else { // other browsers
	    alert("Disculpe, su browser no soporta esta aplicacion.");
	  }
	}
	
	/** 
	 * Elimina espacios en blanco en una cadena
	 */	
	function trim(cadena)
	{
	  cadena2 = "";
	  len = cadena.length;
	  for ( var i=0; i <= len ; i++ ) if ( cadena.charAt(i) != " " ){cadena2+=cadena.charAt(i);	}
	  return cadena2;
	}
	
	/** 
	 * Imprime el frame indicado
	 */	
	function printFrame(frame) 
	{
	  if (pr && da) { // IE5
	    frame.focus();
	    window.print();
	    link.focus();
	  } else if (pr) { // NS4
	    frame.print();
	  } else if (da && !mac) { // IE4 (Windows)
	    frame.focus();
	    setTimeout("vbPrintPage(); link.focus();", 100);
	  } else { // other browsers
	    alert("Disculpe, su browser no soporta esta aplicacion.");
	  }
	}
	
	/** 
	 * funcion que solo permite el ingreso de numeros,separa los codigo de provincias de acuerdo al formato 01-####### , 0##-######## para lima y 
	   provincia respectivamente,se emplea con las funciones
	   onKeyDown="codificatelefono(document.form1.txt_telefono)" onKeyUp="codificatelefono(document.form1.txt_telefono)"
    */	
	function codificatelefono(telefono)
	{
		val=telefono.value.length
		tex=telefono.value
		val=val-1
		tex1 = tex.charAt(val);
		tex2 = tex.charAt(val-1);
		if(val>10)
		    {
		    	alert("El # de Telefono sobrepasa el Numero de Digitos ")
		    	text.value = tex.substring(0,val)
		    }
		switch(val)
		    {
		        case 0 :
		    			     if(tex1!=0)
		    				    telefono.value = '0' + tex1;
		    			     break;
		        case 1 :
		    			    if((tex1==0)||(tex1=='-'))
		    				       telefono.value = tex.substring(0,val)
		    	case 2 :
		      				if((tex2==1)&&(tex1!='-'))
							{
		    				     telefono.value = tex.substring(0,val) + "-" + tex1
							}
		    				if((isNaN(tex1))||(tex1==' '))
							{
								if(tex1!='-')
				   				{
				   					telefono.value = tex.substring(0,val)
				   		  	    }	
				   		  	    if((tex1=='-')&&(tex2!=1))
				   				{
				   					telefono.value = tex.substring(0,val)
				   		  	    }	
							 }
						      break;
		        case 3 : 
		                 if(tex2=='-')
				   				{
				   					if((isNaN(tex1))||(tex1==' '))
									{
										telefono.value = tex.substring(0,val)
									}
								}
						  else
						  {
							if(tex1!='-')
				   				{
				   					telefono.value = tex.substring(0,val)
				   					telefono.value = telefono.value + '-' + tex1  		
						
				 				}	
						  }			
		    		
		    	          break;
		    		
		           default :
		    				if((isNaN(tex1))||(tex1==' '))
							{
								telefono.value = tex.substring(0,val)
							}
		    				break ;
		    	        
		    } 
		  
		}		