// Validador del Formulario form_comerc.asp

var pasofono=false;
var pasorut=false;
var faltacampo=0;

function ValidaTelefonos(tip)
{
	if (tip=="1")
		{
			if (Formulario.codp_fonop.value == "")
				{alert( "Debe Ingresar Código País en teléfono particular");
				faltacampo=1;
				Formulario.codp_fonop.focus();return false;}
				
			if (Formulario.codc_fonop.value == "")
				{alert( "Debe Ingresar Código Ciudad en teléfono particular");
				faltacampo=2;
				Formulario.codc_fonop.focus();return false;}
				
			if (Formulario.fonop.value == "" )
				{alert( "Debe Ingresar el Teléfono particular");
				faltacampo=3;
				Formulario.fonop.focus();return false;}
			var telpart=Formulario.fonop.value;

			if	(telpart.length<5 )
				{alert( "Debe Ingresar un Teléfono particular Válido ");
				faltacampo=3;
			Formulario.fonop.focus();return false;}
			
			pasofono=true;
			return true;		
		}
	else
		{
			if (tip=="2")
				{
					if (Formulario.codp_fonoc.value=="")
						{alert("Debe Ingresar Código País en teléfono comercial");
						faltacampo=1;
						Formulario.codp_fonoc.focus();return false;}
					
					if (Formulario.codc_fonoc.value=="")
						{alert("Debe Ingresar Código Ciudad en teléfono comercial");
						faltacampo=2;
						Formulario.codc_fonoc.focus();return false;}

					if (Formulario.fonoc.value=="")
						{alert("Debe Ingresar el Teléfono Comercial");
						faltacampo=3;
						Formulario.numfonoc.focus();return false;}
					var telcom=Formulario.fonoc.value;
					if	(telcom.length<5 )
						{alert( "Debe Ingresar un Teléfono Comercial Válido ");
						faltacampo=3;
						Formulario.fonoc.focus();return false;}
					pasofono=true;		
					return true;
				}
			else
				{
					if (Formulario.codp_fax.value=="")
						{alert("Debe Ingresar Código País en Fax");
						faltacampo=1;
						return Formulario.codp_fax.focus();return false;}
					
					if (Formulario.codc_fax.value=="")
						{alert("Debe Ingresar Código Ciudad en Fax");
						faltacampo=2;
						return Formulario.codc_fax.focus();return false;}

					if (Formulario.fax.value=="")
						{alert("Debe Ingresar el Fax");
						faltacampo=3;
						return Formulario.fax.focus();return false;}					
					var telfax=Formulario.fax.value;
					if	(telfax.length<5 )
						{alert( "Debe Ingresar un Fax Válido ");
						faltacampo=3;
						Formulario.fax.focus();return false;}
					
					return true;
				}
		}
	
}

function ValidarForm(form)
{
 		 var errors='';
		 	 clave="";
			 tipo="";
		 
		if ( Formulario.RUT.value == "" )
			{ alert ( "Debe Ingresar RUT" ) ; Formulario.RUT.focus();return; }
						   
  		if ( Formulario.DV.value == "" )
		   { alert ( "Debe Ingresar DV" );Formulario.DV.focus();return; }
	
		rut=Formulario.RUT.value;
		dv=Formulario.DV.value;			
		if (checkFields( rut, dv, clave, tipo )!= true)
		   {
			if (pasorut==true)
				{pasorut=false;
				Formulario.RUT.value ="";
				Formulario.DV.value = "";
				Formulario.RUT.focus();return;}
			else
				{alert ( "Rut Invalido" );Formulario.RUT.focus();return;}
		    }
			
  		if ( Formulario.nombres.value == "" )
		   { alert ( "Debe Ingresar Nombres" );Formulario.nombres.focus();return; }
		
		if ( Formulario.appat.value == "" )
		   { alert ( "Debe Ingresar Apellido Paterno" );Formulario.appat.focus();return;}		
		
		if ( Formulario.apmat.value == "" )
			{ alert ( "Debe Ingresar Apellido Materno" ) ; Formulario.apmat.focus();return; }
		
  		if ( Formulario.sexo.value == "NN" )
		   { alert ( "Debe Seleccionar Sexo" );Formulario.sexo.focus();return; }

  		/*if ( Formulario.actividad.value == "NN" )
		   { alert ( "Debe Seleccionar Actividad" );Formulario.actividad.focus();return; }*/

  		if ( Formulario.fechan.value == "" )
		   { alert ( "Debe Ingresar Fecha de Nacimiento" );Formulario.fechan.focus();return; }

  		if ( Formulario.domicilio.value == "" )
		   { alert ( "Debe Ingresar Domicilio" );Formulario.domicilio.focus();return; }
		
  		/*valida teléfono particular*/
  		
  		if ((Formulario.codp_fonop.value!="")||(Formulario.codc_fonop.value!="")||(Formulario.fonop.value!=""))
  			{
  				pasada=ValidaTelefonos("1")
  				if (pasada!=true)
  					{
  					if (faltacampo==1)
  						{return Formulario.codp_fonop.focus()}
  					if (faltacampo==2)
  						{return Formulario.codc_fonop.focus()}
  					if (faltacampo==3)
  						{return Formulario.fonop.focus()}  					
  					}
  			}
		   
		
  		if ( Formulario.ciudad.value == "" )
		   { alert ( "Debe Ingresar Ciudad" );Formulario.ciudad.focus();return; }
		
  		/*valida teléfono comercial*/
  		if ((Formulario.codp_fonoc.value!="")||(Formulario.codc_fonoc.value!="")||(Formulario.fonoc.value!=""))
		   {
			pasada=ValidaTelefonos("2")
				if (pasada!=true)
  					{
  					if (faltacampo==1)
  						{return Formulario.codp_fonoc.focus()}
  					if (faltacampo==2)
  						{return Formulario.codc_fonoc.focus()}
  					if (faltacampo==3)
  						{return Formulario.fonoc.focus()}
  					}
  			}

		if ( Formulario.pais.value == "" )
		   { alert ( "Debe Ingresar el País de Residencia" );Formulario.pais.focus();return; }
		   
		if ( Formulario.dir_epost.value == "" )
		   { alert ( "Debe Ingresar Dirección de Envío Postal" );Formulario.dir_epost.focus();return; }

		
		if ( Formulario.ciudad2.value == "" )
		   { alert ( "Debe Ingresar Ciudad" );Formulario.ciudad2.focus();return; }

		if ( Formulario.pais2.value == "" )
		   { alert ( "Debe Ingresar País" );Formulario.pais2.focus();return; }

		if ( Formulario.mail.value == "" )
		   { alert ( "Debe Ingresar e-mail" );Formulario.mail.focus();return; }

		if(Formulario.mail.value !="")
		Result = email (Formulario.mail.value);
		if ( Result != true ) 
			{Formulario.mail.focus();return;}

		/*valida Fax*/
  		if ((Formulario.codp_fax.value!="")||(Formulario.codc_fax.value!="")||(Formulario.fax.value!=""))
			  {
				pasada=ValidaTelefonos("3")
  				if (pasada!=true)
  					{
  					if (faltacampo==1)
  						{return Formulario.codp_fax.focus()}
  					if (faltacampo==2)
  						{return Formulario.codc_fax.focus()}
  					if (faltacampo==3)
  						{return Formulario.fax.focus()}  					  					
  					}
			}
		   
		if (pasofono==false)
			{alert("Debe ingresar a lo menos uno de los dos teléfonos solicitados");
			return Formulario.codp_fonop.focus();}
		
Formulario.paso.value="1"

Formulario.submit();

}

function IsNumberChar(InString)
{
  var i ;
  var cond;
  RefString="1234567890.";

  for(i=0;i<InString.length;i++) 
  {
  if ( RefString.indexOf ( InString.substring(i,i+1) , 0 ) == -1 )
  {
   	 cond=1;
	 i=InString.length+1;
  }
  else
  {	 
  	 cond=0
  } 	 

  }
  if ( cond == 1 )
  	 {return ( false ) ;}
  else
  {	 
  return ( true ) ;
  }  
}  


function Dia(InString)
{
   	 var dia;
   	 dia=InString;
 
	if (dia !="" && !(dia > 0 && dia < 32))
	{
		alert ("Invalido Día!");
		return false;
	}
	else
	{
	 return true;
    }
}

function ano(InString)
{
	 var ano;
   	 ano=InString;
	
	if (ano !="" && !(ano > 1900 && ano < 2100))
	{
		alert ("Invalido Año!");
		return false;
	}
	else
	{
	 return true;
    }
}


function checkFields( rut, dv, clave, tipo )

{
  var tmpstr = "";
  for ( i=0; i < rut.length ; i++ )
    if ( rut.charAt(i) != ' ' && rut.charAt(i) != '.' && rut.charAt(i) != '-' )
      tmpstr = tmpstr + rut.charAt(i);
  rut = tmpstr;
  texto = rut + dv

  if ( rut == "")
  {
    return false;
  }
  if ( !checkRutField(rut,dv,tipo) )
    return false;
  if ( !checkDV( texto, tipo ) )
    return false;
  if (eval(rut)>eval("49999999"))
	{
	alert("Rut No corresponde a persona Natural");
	pasorut=true;
	return false;
	}
  return true;
}

function checkCDV( dvr,tipo )

{
  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')
  {
    if (tipo==1)
    {
    }
    if (tipo==2)
    {
    }
    if (tipo==3)
    {
    }
    if (tipo==4)
    {
    }
    return false;
  }
  return true;
}

function checkDV( crut,tipo )

{
  largo = crut.length;
  if ( largo < 2 )
  {
    if (tipo==1)
    {
    }
    if (tipo==2)
    {
    }
    if (tipo==3)
    {
    }
    if (tipo==4)
    {
    }
    return false;
  }

  if ( largo > 2 )
    rut = crut.substring(0, largo - 1);
  else
    rut = crut.charAt(0);
  dv = crut.charAt(largo-1);
  checkCDV( dv,tipo );

  if ( rut == null || dv == 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() )
  {
    if (tipo==1)
    {
    }
    if (tipo==2)
    {
    }
    if (tipo==3)
    {
    }
    if (tipo==4)
    {
    }
    return false
  }

      return true

}

function checkPinField()

{

  if ( window.document.Formulario.CLAVE.value.length == 0 )
  {
    window.document.Formulario.CLAVE.focus();
    window.document.Formulario.CLAVE.select();
    return false;
  }
  if ( window.document.Formulario.CLAVE.value.length != 4 )
  {
    window.document.Formulario.CLAVE.focus();
    window.document.Formulario.CLAVE.select();
    return false;
  }

  

  for (i=0; i < window.document.Formulario.CLAVE.value.length ; i++ )
  { 
    if ( window.document.Formulario.CLAVE.value.charAt(i) !="0" && window.document.Formulario.CLAVE.value.charAt(i) != "1" && window.document.Formulario.CLAVE.value.charAt(i) !="2" && window.document.Formulario.CLAVE.value.charAt(i) != "3" && window.document.Formulario.CLAVE.value.charAt(i) != "4" && window.document.Formulario.CLAVE.value.charAt(i) !="5" && window.document.Formulario.CLAVE.value.charAt(i) != "6" && window.document.Formulario.CLAVE.value.charAt(i) != "7" && window.document.Formulario.CLAVE.value.charAt(i) !="8" && window.document.Formulario.CLAVE.value.charAt(i) != "9" ) 
    {
      window.document.Formulario.CLAVE.focus();
      window.document.Formulario.CLAVE.select();
      return false;
    }
  }
  return true;
}

function checkRutField(texto,dv,tipo)
{
  if (dv=='k'){
	dv='K';
	if (tipo==1)
		window.document.Formulario.DV.value = 'K';
	if (tipo==2)
		window.document.Formulario.DVPERSONA.value = 'K';
	if (tipo==3)
		window.document.Formulario.DVPERSONA2.value = 'K';
	if (tipo==4)
		window.document.Formulario.DVVENDE.value = 'K';
	}
	
  texto = texto + dv;	
  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 )
  {
    if (tipo==1)
    {
    }
    if (tipo==2)
    {
    }
    if (tipo==3)
    {
    }
    if (tipo==4)
    {
    }
    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" ) 
    {
		if (tipo==1)
		{
		}
		if (tipo==2)
		{
		}
		if (tipo==3)
		{
		}
		if (tipo==4)
		{
		}
		return false;
    }
  }

  var invertido = "";

  for ( i=(largo-1),j=0; i>=0; i--,j++ )
    invertido = invertido + texto.charAt(i);

  var dtexto = "";

  dtexto = dtexto + invertido.charAt(0);
  dtexto = dtexto + '-';
  cnt = 0;

  for ( i=1,j=2; i<largo; i++,j++ )
  {
    if ( cnt == 3 )
    {
      dtexto = dtexto + '.';
      j++;
	  dtexto = dtexto + invertido.charAt(i);
      cnt = 1;
    }
    else
    { 
      dtexto = dtexto + invertido.charAt(i);
      cnt++;
    }
  }

  invertido = "";

 for ( i=(dtexto.length-1),j=0; i>=2; i--,j++ )
	if (dtexto.charAt(i) == "k")
		invertido = invertido + "K";		
	else
		invertido = invertido + dtexto.charAt(i);
    if (tipo==1)
    {
		window.document.Formulario.RUT.value = invertido;  
    }
    if (tipo==2)
    {
		window.document.Formulario.RUTPERSONA.value = invertido;  
	  }
    if (tipo==3)
  {
		window.document.Formulario.RUTPERSONA2.value = invertido;  
	}
    if (tipo==4)
    {
		window.document.Formulario.RUTVENDE.value = invertido;  
	}


  if ( checkDV(texto,tipo) )
  {	
		return true;
  }
   else
   {
		return false;
	}
 }


function email (emailStr) {

/* Verificar si el email tiene el formato user@dominio. */
var emailPat=/^(.+)@(.+)$/ 

/* Verificar la existencia de caracteres. ( ) < > @ , ; : \ " . [ ] */
var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]" 

/* Verifica los caracteres que son válidos en una dirección de email */
var validChars="\[^\\s" + specialChars + "\]" 

var quotedUser="(\"[^\"]*\")" 

/* Verifica si la dirección de email está representada con una dirección IP Válida */ 


var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/


/* Verificar caracteres inválidos */ 

var atom=validChars + '+'
var word="(" + atom + "|" + quotedUser + ")"
var userPat=new RegExp("^" + word + "(\\." + word + ")*$")
/* domain, as opposed to ipDomainPat, shown above. */
var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$")


var matchArray=emailStr.match(emailPat)
if (matchArray==null) {
alert("La Dirección Email es incorrecta")
return false
}
var user=matchArray[1]
var domain=matchArray[2]

// Si el user "user" es valido 
if (user.match(userPat)==null) {
// Si no
alert("El nombre de usuario no es válido.")
return false
}

/* Si la dirección IP es válida */
var IPArray=domain.match(ipDomainPat)
if (IPArray!=null) {
for (var i=1;i<=4;i++) {
if (IPArray[i]>255) {
alert("IP de destino inválida")
return false
}
}
return true
}

var domainArray=domain.match(domainPat)
if (domainArray==null) {
alert("El dominio parece no ser válido.")
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) { 
alert("La dirección debe tener 3 letras si es .com o 2 si en de algún pais.")
//alert("La Dirección Email es incorrecta")
return false
}

if (len<2) {
var errStr="La Dirección Email es incorrecta"
alert(errStr)
return false
}

// La dirección de email ingresada es Válida
return true;
}

function validafono(fono) {
//validacion de telefono con pais - ciudad - telefono

	var ciudad = fono.substring(0,(fono.indexOf('-',0)));
	//var ciudad = fono.right(fono,(fono.indexOf('-',0)));
	if (ciudad.length==2)
	{ var telefono = fono.substring(3,(fono.length)); }
	else
	{ var telefono = fono.substring(2,(fono.length)); }
	
	if (ciudad.length>3)
	{ return false;}

	if (telefono.length<6)
	{ return false;}
	
	if (numeros(ciudad)==false)
			{ return false;}
		else
		{
			if (numeros(telefono)==false)
			{ return false;}
	}
}

function numeros (InString)
{
  var i ;
  var cond;
  RefString="1234567890";

  for(i=0;i<InString.length;i++) 
  {
  if ( RefString.indexOf ( InString.substring(i,i+1) , 0 ) == -1 )
  {
   	 cond=1;
	 i=InString.length+1;
  }
  else
  {	 
  	 cond=0
  } 	 

  }
  if ( cond == 1 )
  	 {return ( false ) ;}
  return ( true ) ;  
}

  function ValidarFecha(a, b, bb, c)  {
    var Error = "La fecha introducida es inválida.\n"
      + "Revísela, por favor.";
    var Dia, Mes, Anyo, a, b, c, bb, Dia_Mes_Mal = false;
    var MesElegido =  bb

    Dia = a;
    Mes = b;
    Anyo = c;

    if( Dia == "" && Mes == "" && Anyo == "" ) return true;
    else {
      Dia = parseInt(Dia);
      Mes = parseInt(Mes);
      Anyo = parseInt(Anyo);

      if( !isNaN(Dia) && !isNaN(Mes) && !isNaN(Anyo)
          &&
          Dia >= 1 && Anyo >= 1900
        )  {

        if( 
           (   Mes == 1 || Mes == 3 || Mes == 5 || Mes == 7
            || Mes == 8 || Mes == 10 || Mes == 12
           )
          && Dia > 31
          )   Dia_Mes_Mal = true;

        if(
           (Mes == 4 || Mes == 6 || Mes == 9 || Mes == 11)
          && Dia > 30
          )   Dia_Mes_Mal = true;

        if( Mes == 2 && 
            ( Dia > 29 ||
              ( Dia == 29 &&
                ( 
                  (Anyo % 400 != 0)
                  && (
                     (Anyo % 4 != 0) || (Anyo % 100 == 0)
                     )
                )
              )
            )
           )  Dia_Mes_Mal = true;

        if(Dia_Mes_Mal)  {
          alert(Error);
          return false;
          }
        else return true;
        }   
      else  {
        alert(Error);
        return false;
        }
      }
    }

