document.write ("<script language='JavaScript' src='validaemail.js' /></script />")
document.write ("<script language='JavaScript' src='validamoneda.js' /></script />")
document.write ("<script language='JavaScript' src='validarut.js' /></script />")

function validaForm(form)
{var i;
 var arr;
 var e;
 var x;

 for (i=0;i<form.elements.length;i++)
 {if (form.elements[i].name.substr(0,4) == "chk_")
  {
   e = GetFieldValueByName(form, form.elements[i].name.substr(4));
   if (e.value != null)
   {e.value = Trim(e.value);
    arr = form.elements[i].value.split("|");      
    switch(arr[0])
    {
    case "rdo":
	  if ((!e.checked) && (arr[3] == "true") && (e.disabled!=true))
	  {
		alert("El campo '" + arr[4].substr(4) + "' debe ser seleccionado.");
		setfocus(e);
		return false;
	  }
	  break;
      
	case "cbo":

       //check mandatory field              
      if ((e.value.length == 0) && (arr[1] == "true") && (e.disabled!=true))
      {
        alert("El campo '" + arr[2].substr(4) + "' debe ser seleccionado.");
        setfocus(e);
        return false;
      }
      break;

    case "str":

       //check mandatory field              
      if ((e.value.length == 0) && (arr[3] == "true") && (e.disabled!=true))
      {
        alert("El campo '" + arr[4].substr(4) + "' debe ser ingresado.");
        e.select();
        setfocus(e);
        return false;
      }
              
      //check min length  
      if (e.value.length < parseInt(arr[1]))
      {
        alert("El valor ingresado en el campo '" + arr[4].substr(4) + "' es demasiado pequeño.");
        e.select();
        setfocus(e);
        return false;
      }
              
      //check max length
      if (e.value.length > parseInt(arr[2]))
      {
        alert("El valor ingresado en el campo '" + arr[4].substr(4) + "' es demasiado grande.");
        e.select();
        setfocus(e);
        return false;
      }
      break;

    case "int":
                                
      //check mandatory field
      if ((e.value.length == 0) && (arr[3] == "true") && (e.disabled!=true))
      {
        alert("El campo '" + arr[4].substr(4) + "' debe ser ingresado.");
        e.select();
        setfocus(e);
        return false;
      }
            
      //check sanity
      if(!(IsNumeric(e.value)))
      {
        alert("El valor ingresado en el campo '" + arr[4].substr(4) + "' debe ser solo con números.");
        e.select();
        setfocus(e);
        return false;
      }
                        
      //check min value
      if (arr[1] != "x")
      {
        if (parseInt(e.value) < parseInt(arr[1]))
        {
          alert("El valor ingresado en el campo '" + arr[4].substr(4) + "' es muy pequeño.");
          e.select();
          setfocus(e);
          return false;
        }
      }
            
      //check max length
      if (arr[2] != "x")
      {
        if (parseInt(e.value) > parseInt(arr[2]))
        {
          alert("El valor ingresado en el campo '" + arr[4].substr(4) + "' es muy grande.");
          e.select();
          setfocus(e);
          return false;
        }
      }
            
      break;
          
    case "float":
                                    
      //check mandatory field
      if ((e.value.length == 0) && (arr[3] == "true") && (e.disabled!=true))
      {
        alert("El campo '" + arr[4].substr(4) + "' debe ser ingresado.");
        e.select();
        setfocus(e);
        return false;
      }
            
      //check sanity
      if(!(IsNumeric(e.value)))
      {
        alert("El valor ingresado en el campo '" + arr[4].substr(4) + "' debe ser solo con números.");
        e.select();
        setfocus(e);
        return false;
        }
                        
      //check min value
      if (arr[1] != "x")
      {
        if (parseFloat(e.value) < parseFloat(arr[1]))
        {
          alert("El valor ingresado en el campo '" + arr[4].substr(4) + "' no puede ser menor que " + arr[1] + ".");
          e.select();
          setfocus(e);
          return false;
        }
      }
            
      //check max length
      if (arr[2] != "x")
      {
        if (parseFloat(e.value) > parseFloat(arr[2]))
        {
          alert("El valor ingresado en el campo '" + arr[4].substr(4) + "' no puede ser mayor que " + arr[2] + ".");
          e.select();
          setfocus(e);
          return false;
        }
      }
            
      break;
                    
    case "date":
            
      //check mandatory field
      if ((e.value.length == 0) && (arr[3] == "true") && (e.disabled!=true))
      {
        alert("El campo '" + arr[4].substr(4) + "' debe ser ingresado.");
        e.select();
        setfocus(e);
        return false;
      }
            
      //check sanity
      if((e.value.length != 0) && (IsDate(e.value)!=true))
      {
        alert("El valor ingresado en el campo '" + arr[4].substr(4) + "' no es una fecha válida (DD/MM/YYYY).");
        e.select();
        setfocus(e);
        return false;
      }
            
      //check min value
      if (arr[1] != "")
      {
        alert(e.value + " " + arr[1])
        if (GetDate(e.value) < GetDate(arr[1]))
        {
          alert("La fecha ingresada en el campo '" + arr[4].substr(4) + "' no puede ser menor que " + setFormatDate(arr[1]) + ".");
          e.select();
          setfocus(e);
          return false;
        }
      }
            
      //check max length
      if (arr[2] != "")
      {
        if (GetDate(e.value) > GetDate(arr[2]))
        {
          alert("El valor ingresado en el campo '" + arr[4].substr(4) + "' no puede ser mayor que " + setFormatDate(arr[1]) + ".");
          e.select();
          setfocus(e);
          return false;
        }
      }
            
      break;
                    
    case "time":
            
      //check mandatory field
      if ((e.value.length == 0) && (arr[3] == "true") && (e.disabled!=true))
      {
        alert("El campo '" + arr[4].substr(4) + "' debe ser ingresado.");
        e.select();
        setfocus(e);
        return false;
      }
            
      //check sanity
      if((e.value.length != 0) && (IsValidTime(e.value)!=true))
      {
        //alert("El valor ingresado en el campo '" + arr[4] + "' no es una hora valida (hh:mm).");
        e.select();
        setfocus(e);
        return false;
      }
            
      break;
        }
      }
    }
  }
  
return true;
}

//============================================================================================

function Replace(string,replacechar,replacewith) 
{
  var temp = "";
  var i;
  
  string = '' + string;
  splitstring = string.split(replacechar);
  for(i = 0; i < splitstring.length; i++)
  {
    if(i < (splitstring.length -1))
      temp += splitstring[i] + replacewith;
    else
      temp += splitstring[i];
  }
  return temp;
}

//============================================================================================

function GetFieldValueByName(form,name)
{
  var i;
  
  for (i=0;i<form.elements.length;i++)
  {
    if(form.elements[i].name == name)
      return (form.elements[i]);
  }
  return null;
}

/*

======================= STANDARD HELPER FUNCTIONS BELOW =======================================

*/
function IsNumeric(str)
{
  var i;
  for(i=0;i<str.length;i++)
  {
    if(!(  ((str.charAt(i) <= '9') && (str.charAt(i) >= '0')) ||
        (str.charAt(i) == ' ') || (str.charAt(i) == '.') || (str.charAt(i) == '-')))
      return(false);
  }
  return(true);
}

//============================================================================================

function IsAlphaNumeric(str)
{
  var i;
  for(i=0;i<str.length;i++)
  {
    if(!(  ((str.charAt(i) <= '9') && (str.charAt(i) >= '0')) ||
        ((str.charAt(i) <= 'z') && (str.charAt(i) >= 'a')) ||
        (str.charAt(i) == ' ') || (str.charAt(i) == '-') ||
        (str.charAt(i) == 'ü') || (str.charAt(i) == 'ä') ||
        (str.charAt(i) == 'ö') || (str.charAt(i) == 'Ü') ||
        (str.charAt(i) == 'Ä') || (str.charAt(i) == 'Ö') ||
        (str.charAt(i) == 'é') || (str.charAt(i) == 'ß') ||
        ((str.charAt(i) <= 'Z') && (str.charAt(i) >= 'A')) ))
      return(false);
  }
  return(true);
}

//============================================================================================

function IsAlpha(str)
{
  var i;
  
  for(i=0;i<str.length;i++)
  {
    if(!(  ((str.charAt(i) <= 'z') && (str.charAt(i) >= 'a')) ||
        (str.charAt(i) == ' ') || (str.charAt(i) == '-') ||
        (str.charAt(i) == 'ü') || (str.charAt(i) == 'ä') ||
        (str.charAt(i) == 'ö') || (str.charAt(i) == 'Ü') ||
        (str.charAt(i) == 'Ä') || (str.charAt(i) == 'Ö') ||
        (str.charAt(i) == 'é') || (str.charAt(i) == 'ß') ||
        ((str.charAt(i) <= 'Z') && (str.charAt(i) >= 'A')) ))
      return(false);
  }
  return(true);
}

//============================================================================================

function Trim(str)
{
  //trim leding spaces
  while(true)
  {
    if(str.charAt(0) == ' ')
      str = str.substr(1);
    else
      break;
  }
  
  //trim trailing spaces
  while(true)
  {
    if(str.charAt(str.length-1) == ' ')
      str = str.substr(0,str.length-1);
    else
      break;
  }
  return(str);  
}

//============================================================================================

function IsDate(argDate)
{
  var date_split;
  var i;
  var tdate, tmonth, tyear;
  
  date_split = argDate.split('/');
  
  //check for date parts
  if(date_split.length != 3)
    return(false);
  
  //check for zero values
  //for(i=0;i<date_split.length;i++)
  //{
  //  if (parseInt(date_split[i], 10) == 0){
  //    return(false);
  //  }
  //}
  
  //check for 4-digit year
  if(date_split[2].length != 4)
    return(false);
    
  //check for valid date, e.g. 29/02/1997
  tdate = parseInt(date_split[0], 10);
  tmonth = parseInt(date_split[1], 10);
  tyear = parseInt(date_split[2], 10);
  
  var date = new Date(parseInt(date_split[2], 10),parseInt(date_split[1], 10)-1,parseInt(date_split[0], 10));
  
  if(date.getDate() != tdate)
    return(false);
  
  if(date.getMonth() != (tmonth-1))
    return(false);
  
  if(date.getFullYear() != tyear)
    return(false);
    
  return(true);
}


function GetDate(argDate)
{
  //use IsDate() first !!!!
  
  var date_split;  
  var tdate, tmonth, tyear;
  
  date_split = argDate.split('/');
  
  tdate = parseInt(date_split[0], 10);
  tmonth = parseInt(date_split[1], 10);
  tyear = parseInt(date_split[2], 10);
  
  return date = new Date(parseInt(date_split[2], 10),parseInt(date_split[1], 10)-1,parseInt(date_split[0], 10)-1);
    
}

function round(number,X)
{// rounds number to X decimal places, defaults to 2
 if (X>0)
 {
	X = (!X ? 2 : X);
	return Math.round(number*Math.pow(10,X))/Math.pow(10,X);
 }
 else
	return Math.round(number);
 
}

function DateAdd(startDate, numDays, numMonths, numYears)
{

	var returnDate = new Date(startDate.getTime());
	var yearsToAdd = numYears;
	
	var month = returnDate.getMonth()	+ numMonths;
	if (month > 11)
	{
		yearsToAdd = Math.floor((month+1)/12);
		month -= 12*yearsToAdd;
		yearsToAdd += numYears;
	}
	returnDate.setMonth(month);
	returnDate.setFullYear(returnDate.getFullYear()	+ yearsToAdd);
	
	returnDate.setTime(returnDate.getTime()+60000*60*24*numDays);
	
	var dia = returnDate.getDate();
	if (dia<10) 
	  dia = '0' + dia;
	  
	var mes = returnDate.getMonth()+1;
	if (mes<10) 
	  mes = '0' + mes;
	
	return dia + '/' + mes + '/' + returnDate.getYear();

}

function YearAdd(startDate, numYears)
{
		return DateAdd(startDate,0,0,numYears);
}

function MonthAdd(startDate, numMonths)
{
		return DateAdd(startDate,0,numMonths,0);
}

function DayAdd(startDate, numDays)
{
		return DateAdd(startDate,numDays,0,0);
}

function DayAddFormato(startDate, numDays)
{
		var fecha = DateAdd(startDate,numDays,0,0);
    var dia = fecha.substring(0,2);
    var mes = fecha.substring(3,5);
    var ano = fecha.substring(6,10);
    return new Date(mes + '/' + dia + '/' + ano);
}

function setfocus(src)
{
  try 
  {
    if (document.all('fmt_' + src.name)!=null)
      document.all('fmt_' + src.name).focus()
    else
      src.focus();
  } 
  catch(e) 
  {
    //alert(e.description);
  }
}

function diaHabil(fecha)
{

  var dia = fecha.getDate();
  var mes = fecha.getMonth()+1;
  var ano = fecha.getYear();

  //Verifica si la fecha no corresponde a sabado o domingo
  if ((fecha.getDay()==0) || (fecha.getDay()==6))
    return false;
    
  //verifica que el dia no sea fin de semana.
  if (typeof(festivos)!="undefined")
    for (i=0;i<festivos.length; i++) 
      if (dia+'/'+mes+'/'+ano==festivos[i])
        return false;

return true
}

function buscarDiaHabil(fecha, dias)
{

  var date_split;  
  date_split = fecha.split('/');
  
  var tdate = parseInt(date_split[0], 10);
  if (tdate<10)
		tdate="0"+tdate;
		
  var tmonth = parseInt(date_split[1], 10);
  if (tmonth<10)
		tmonth="0"+tmonth;
  
  var tyear = parseInt(date_split[2], 10);
  
  var fch = new Date(tmonth+"/"+tdate+"/"+tyear);

  //avanza dia a dia para buscar dia habil
  //for (i = 0; i < dias; i++) {
    fch = DayAddFormato(fch, dias);
    while (diaHabil(fch)!=true)
    {
      fch = DayAddFormato(fch, 1);
    }
  //}  

	dia = fch.getDate();
	if (dia<10) 
	  dia = '0' + dia;
	  
	mes = fch.getMonth()+1;
	if (mes<10) 
	  mes = '0' + mes;
	
return dia + '/' + mes + '/' + fch.getYear();
}

function setFormatDate(argDate)
{
  var date_split;  
  date_split = argDate.split('/');
  
  var tdate = parseInt(date_split[0], 10);
  if (tdate<10)
		tdate="0"+tdate;
		
  var tmonth = parseInt(date_split[1], 10);
  if (tmonth<10)
		tmonth="0"+tmonth;
  
  var tyear = parseInt(date_split[2], 10);
  
  return tdate+"/"+tmonth+"/"+tyear;
}

function IsValidTime(timeStr) {
	// Checks if time is in HH:MM:SS AM/PM format.
	// The seconds and AM/PM are optional.

	var timePat = /^(\d{1,2}):(\d{2})(:(\d{2}))?(\s?(AM|am|PM|pm))?$/;

	var matchArray = timeStr.match(timePat);
	if (matchArray == null) {
		//alert("Time is not in a valid format.");
		return false;
	}
	
	hour = matchArray[1];
	minute = matchArray[2];
	second = matchArray[4];
	ampm = matchArray[6];

	if (second=="") { second = null; }
	if (ampm=="") { ampm = null }

	if (hour < 0  || hour > 23) {
		alert("Horas debe ser entre 1 y 12. (o bien 0 y 23 para horario militar)");
		return false;
	}

	/*if (hour <= 12 && ampm == null) {
		if (confirm("Por favor indique el formato a utilizar.  Si=Hora normal (AM/PM), No=Hora Militar (24:00)")) {
			alert("Debes especificar AM o PM.");
			return false;
	   }
	}*/

	if  (hour > 12 && ampm != null) {
		alert("No se puede especificar AM o PM para hora militar.");
		return false;
	}

	if (minute<0 || minute > 59) {
		alert ("Minutos deben ser entre 0 y 59.");
		return false;
	}

	if (second != null && (second < 0 || second > 59)) {
		alert ("Segundos deben ser entre 0 y 59.");
		return false;
	}
	return true;
}
