var nbsp = 160;		// non-breaking space char
var node_text = 3;	// DOM text node-type
var emptyString = /^\s*$/ ;
var global_valfield;	// retain valfield for timer thread




  function validateOnSubmit_cont() { 
    var elem;
    var errs=0;
    if (!validatePresent  (document.contacto_form.mensaje, 'inf_mensaje', true)) errs += 1; 
    if (!validateTelnr    (document.contacto_form.fono,   'inf_fono',  false)) errs += 1; 
    if (!validateEmail  (document.contacto_form.mail, 'inf_mail', true)) errs += 1; 
    if (!validatePresent(document.contacto_form.nombre,  'inf_nombre',true)) errs += 1; 
    /*if (errs>1)  alert('Hay campos que necesitan correcion antes de ser enviados');
    if (errs==1) alert('Hay un campo que necesita correcion antes de ser enviado');*/

    return (errs==0);
  }




  function validateOnSubmit_i() { 
    var elem;
    var errs=0;
    if (!validateRadio  (document.inscripcion_form.estudios, 'inf_estudios_i', true)) errs += 1; 
    if (!validatePresent  (document.inscripcion_form.nivel, 'inf_nivel_i', true)) errs += 1; 
    if (!validateAge(document.inscripcion_form.edad, 'inf_edad_i', true) ) errs += 1; 
    if (!validateFecha(document.inscripcion_form.fnac, 'inf_fnac_i', true) ) errs += 1; 
    if (!validateTelnr(document.inscripcion_form.fono, 'inf_fono_i', true) ) errs += 1; 
    if (!validateEmail  (document.inscripcion_form.email, 'inf_email_i', true)) errs += 1; 
    if (!validatePresent  (document.inscripcion_form.direccion, 'inf_direccion_i', true)) errs += 1; 
    if (!validateRut(document.inscripcion_form.rut,  'inf_rut_i',true)) errs += 1; 
    if (!validatePresent  (document.inscripcion_form.nombre, 'inf_nombre_i', true)) errs += 1; 
    if (!validatePresent  (document.inscripcion_form.instrumento, 'inf_instrumento_i', true)) errs += 1; 

    return (errs==0);
  }


  function validateOnSubmit_e() { 
    var elem;
    var errs=0;
    if (!validateMenciones('inf_menciones_e')) errs += 1; 
    if (!validateRadio  (document.encuesta_form.estudios, 'inf_estudios_e', true)) errs += 1; 
    if (!validatePresent  (document.encuesta_form.nivel, 'inf_nivel_e', true)) errs += 1; 
    if (!validateAge(document.encuesta_form.edad, 'inf_edad_e', true) ) errs += 1; 
    if (!validateFecha(document.encuesta_form.fnac, 'inf_fnac_e', true) ) errs += 1; 
    if (!validateTelnr(document.encuesta_form.fono, 'inf_fono_e', true) ) errs += 1; 
    if (!validateEmail  (document.encuesta_form.email, 'inf_email_e', true)) errs += 1; 
    if (!validatePresent  (document.encuesta_form.direccion, 'inf_direccion_e', true)) errs += 1; 
    if (!validateRut(document.encuesta_form.rut,  'inf_rut_e',true)) errs += 1; 
    if (!validatePresent  (document.encuesta_form.nombre, 'inf_nombre_e', true)) errs += 1; 
    //if (!validatePresent  (document.encuesta_form.instrumento, 'inf_instrumento_e', true)) errs += 1;

    return (errs==0);
  }






// --------------------------------------------
//                  trim
// Trim leading/trailing whitespace off string
// --------------------------------------------

function trim(str)
{
  return str.replace(/^\s+|\s+$/g, '');
}


// --------------------------------------------
//                  setfocus
// Delayed focus setting to get around IE bug
// --------------------------------------------

function setFocusDelayed()
{
  global_valfield.focus();
}

function setfocus(valfield)
{
  // save valfield in global variable so value retained when routine exits
  global_valfield = valfield;
  setTimeout( 'setFocusDelayed()', 100 );
}


// --------------------------------------------
//                  msg
// Display warn/error message in HTML element.
// commonCheck routine must have previously been called
// --------------------------------------------

function msg(fld,     // id of element to display message in
             msgtype, // class to give element ("warn" or "error")
             message) // string to display
{
  // setting an empty string can give problems if later set to a 
  // non-empty string, so ensure a space present. (For Mozilla and Opera one could 
  // simply use a space, but IE demands something more, like a non-breaking space.)
  var dispmessage;
  if (emptyString.test(message)) 
    dispmessage = String.fromCharCode(nbsp);    
  else  
    dispmessage = message;

  var elem = document.getElementById(fld);
  elem.firstChild.nodeValue = dispmessage;

  elem.className = msgtype;   // set the CSS class to adjust appearance of message
}

// --------------------------------------------
//            commonCheck
// Common code for all validation routines to:
// (a) check for older / less-equipped browsers
// (b) check if empty fields are required
// Returns true (validation passed), 
//         false (validation failed) or 
//         proceed (don't know yet)
// --------------------------------------------

var proceed = 2;  

function commonCheck    (valfield,   // element to be validated
                         infofield,  // id of element to receive info/error msg
                         required)   // true if required
{
  if (!document.getElementById) 
    return true;  // not available on this browser - leave validation to the server
  var elem = document.getElementById(infofield);
  if (!elem.firstChild) return true;  // not available on this browser 
  if (elem.firstChild.nodeType != node_text) return true;  // infofield is wrong type of node  

  if (emptyString.test(valfield.value)) {
    if (required) {
      msg (infofield, "error", " Debe completar este campo");  
      setfocus(valfield);
      return false;
    }
    else {
      msg (infofield, "warn", "");   // OK
      return true;  
    }
  }
  return proceed;
}

// --------------------------------------------
//            validatePresent
// Validate if something has been entered
// Returns true if so 
// --------------------------------------------

function validatePresent(valfield,   // element to be validated
                         infofield ) // id of element to receive info/error msg
{
  var stat = commonCheck (valfield, infofield, true);
  if (stat != proceed) return stat;

  msg (infofield, "warn", "");  
  return true;
}

// --------------------------------------------
//            validateRadio
// Validate if something has been entered
// Returns true if so 
// --------------------------------------------

function validateRadio( valfield,   // element to be validated
                         infofield ) // id of element to receive info/error msg
{
	var algo_pinchado; 
	algo_pinchado = 'no'; 
	rgroup = valfield;
	for (var i=0; i<rgroup.length; i++) { 
		if (rgroup[i].checked) { 
			algo_pinchado = 'si'; 
			break; 
		}	
	} 
	if (algo_pinchado == 'no'){
	    msg (infofield, "error", "Debe completar este campo");
	    return false;	
	}
  msg (infofield, "warn", "");  
  return true;
}

// --------------------------------------------
//            validateMenciones
// Validate if something has been entered
// Returns true if so 
// --------------------------------------------

function validateMenciones( infofield ) // id of element to receive info/error msg
{
	var algo_pinchado; 
	algo_pinchado = 'no'; 
	
	//alert("sfsdf" + document.encuesta_form.menciones1.checked);
	if (document.encuesta_form.menciones1.checked) { 
		algo_pinchado = 'si'; 
	}	
	if (document.encuesta_form.menciones2.checked) { 
		algo_pinchado = 'si'; 
	}	
	if (document.encuesta_form.menciones3.checked) { 
		algo_pinchado = 'si'; 
	}	

	if (algo_pinchado == 'no'){
	    msg (infofield, "error", "Debe completar este campo");
	    return false;	
	}
	
  msg (infofield, "warn", "");  
  return true;
}

// --------------------------------------------
//               validateEmail
// Validate if e-mail address
// Returns true if so (and also if could not be executed because of old browser)
// --------------------------------------------

function validateEmail  (valfield,   // element to be validated
                         infofield,  // id of element to receive info/error msg
                         required)   // true if required
{
  var stat = commonCheck (valfield, infofield, required);
  if (stat != proceed) return stat;

  var tfld = trim(valfield.value);  // value of field with whitespace trimmed off
  var email = /^[^@]+@[^@.]+\.[^@]*\w\w$/  ;
  if (!email.test(tfld)) {
    msg (infofield, "error", "No es un e-mail valido");
    setfocus(valfield);
    return false;
  }

  var email2 = /^[A-Za-z][\w.-]+@\w[\w.-]+\.[\w.-]*[A-Za-z][A-Za-z]$/  ;
  if (!email2.test(tfld)) 
    msg (infofield, "warn", "Direccion de e-mail inusual - compruebe si es correcto.");
  else
    msg (infofield, "warn", "");
  return true;
}


// --------------------------------------------
//            validateTelnr
// Validate telephone number
// Returns true if so (and also if could not be executed because of old browser)
// Permits spaces, hyphens, brackets and leading +
// --------------------------------------------

function validateTelnr  (valfield,   // element to be validated
                         infofield,  // id of element to receive info/error msg
                         required)   // true if required
{
  var stat = commonCheck (valfield, infofield, required);
  if (stat != proceed) return stat;

  var tfld = trim(valfield.value);  // value of field with whitespace trimmed off
  var telnr = /^\+?[0-9 ()-]+[0-9]$/  ;
  if (!telnr.test(tfld)) {
    msg (infofield, "error", "No es un numero telefonico valido. Caracteres permitidos: digitos, espacio ()- y +");
    setfocus(valfield);
    return false;
  }

  var numdigits = 0;
  for (var j=0; j<tfld.length; j++)
    if (tfld.charAt(j)>='0' && tfld.charAt(j)<='9') numdigits++;

  if (numdigits<6) {
    msg (infofield, "error", "" + numdigits + " digitos - muy pocos para un mumero telefonico");
    setfocus(valfield);
    return false;
  }

  if (numdigits>14)
    msg (infofield, "warn", numdigits + " digitos - verifique si es correcto");
  else { 
    if (numdigits<6)
      msg (infofield, "warn", "Solo " + numdigits + " digitos - compruebe si es correcto");
    else
      msg (infofield, "warn", "");
  }
  return true;
}

// --------------------------------------------
//             validateAge
// Validate person's age
// Returns true if OK 
// --------------------------------------------

function validateAge    (valfield,   // element to be validated
                         infofield,  // id of element to receive info/error msg
                         required)   // true if required
{
  var stat = commonCheck (valfield, infofield, required);
  if (stat != proceed) return stat;

  var tfld = trim(valfield.value);
  var ageRE = /^[0-9]{1,3}$/
  if (!ageRE.test(tfld)) {
    msg (infofield, "error", "No es una edad valida");
    setfocus(valfield);
    return false;
  }

  if (tfld>=200) {
    msg (infofield, "error", "No es una edad valida");
    setfocus(valfield);
    return false;
  }

  if (tfld>110) msg (infofield, "warn", "Mayor que 110: compruebe que es correcto");
  else {
    if (tfld<3) msg (infofield, "warn", "Un poco joven para esto, no crees?");
    else        msg (infofield, "warn", "");
  }
  return true;
}


// --------------------------------------------
// Validate fecha dd-mmm-aaaa
// --------------------------------------------

function validateFecha    (valfield,   // element to be validated
                         infofield,  // id of element to receive info/error msg
                         required)   // true if required
{
  var stat = commonCheck (valfield, infofield, required);
  if (stat != proceed) return stat;


   var RegExPattern = /(0[1-9]|[12][0-9]|3[01])[-](0[1-9]|1[012])[-](19|20)[0-9]{2}/;
   
   var tfld = trim(valfield.value);
  
   if (!RegExPattern.test(tfld)) {
     msg (infofield, "error", "No es una fecha valida");
     setfocus(valfield);
     return false;
   }
   else{
   	msg (infofield, "error", "");
   }
  return true;
}





// --------------------------------------------
// Validate rut valido
// --------------------------------------------
function revisarDigito(dvr, valfield, infofield)
{	

	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')	
	{		
			msg (infofield, "error", "Debe ingresar un digito verificador valido");
			setfocus(valfield);
			return false;			
	}
	msg (infofield, "warn", "");   // OK	
	return true;
}

function revisarDigito2(texto, valfield, infofield) 
{	
	
	var crut=texto;
	largo = crut.length;	
		
	if ( largo < 2 )	
	{		
		msg (infofield, "error", "Debe ingresar el rut completo");
		setfocus(valfield);
		return false;
	}	
	if ( largo > 2 )		
		rut = crut.substring(0, largo - 1);	
	else		
		rut = crut.charAt(0);	
	dv = crut.charAt(largo-1);	
	revisarDigito( dv ,valfield,infofield);	
	
	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() )	
	{		
		msg (infofield, "error", "EL rut es incorrecto");
		setfocus(valfield);
		return false;
	}
    msg (infofield, "warn", "");   // OK
	return true
}

function validateRut(valfield, infofield, required) 
{	
	var tmpstr = "";	
	var texto=valfield.value;
	var stat = commonCheck (valfield, infofield, required);
	if (stat != proceed) return stat;	
	
	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 < 8 )	
	{		
		msg (infofield, "error", "Verifique que el rut este bien escrito");
		setfocus(valfield);
		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" )
 		{			
			msg (infofield, "error", "El valor ingresado no corresponde a un R.U.T valido");
			setfocus(valfield);
			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++ )	
	{		
		//alert("i=[" + i + "] j=[" + 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>=0; i--,j++ )		
		invertido = invertido + dtexto.charAt(i);	

	valfield.value = invertido.toUpperCase();		
	if ( revisarDigito2(texto,valfield,infofield) ){		
		msg (infofield, "warn", "");   // OK
		return true;	
	}	

	return false;
}

