//--------------------------------------------
// Franc. 2004
//--------------------------------------------

var decallowed = 3;  // Cuantos decimales están permitidos
var texto_validacion_importe= "El valor introducido no es un importe válido. ";
var texto_validacion_entero = "El valor introducido no es numérico ";
var texto_validacion_decimal = "El valor introducido no es decimal ";
var texto_validacion_fecha  = " no es una fecha valida.Por Favor use el formato  dd/mm/yy. ";
var texto_validacion_hora  = " no es una hora valida.Por Favor use el formato  hh:mm. ";
var texto_validacion_no_nulo= "El valor introducido no puede ser nulo ";
var texto_no_real= "El valor introducido no es válido, recuerde que sólo se permiten " + decallowed + " decimales.";
var error = 0;


/*********************************************************************/
/* DESCRIPTION: Pone una mascara de importe con puntos y comas.      */
/* PARAMETERS:                                                       */
/*********************************************************************/    
function num_comas()
{            
  if ( !(event.keyCode >= 48 && event.keyCode <= 57))
  {
    if (event.keyCode != 44)
    {
      event.keyCode=0;
    }           
  }
}                      

function checkNum(data) {      
  var valid = "0123456789,";   
  var ok = 1; var checktemp;
  for (var i=0; i<data.length; i++) {
    checktemp = "" + data.substring(i, i+1);
    if (valid.indexOf(checktemp) == "-1") return 0; 
  }
  return 1;
}

function Mascara(field,val) { 

  if (val == null)            
    Num = field.value;            
  else
    Num = val;            

  if (Num.indexOf(".") == -1){            
    dec = Num.indexOf(",");
    end = ((dec > -1) ? "" + Num.substring(dec,Num.length) : ",00");
    Num = "" + parseInt(Num);

    var temp1  = "";
    var temp2  = "";
    var v_cont = 0;         

    if (checkNum(Num+end) == 0)
    {
      null; //alert("error");
    }            
    else 
    { 
      var total = Num.length - 1;
      for (var i=total;i>=0;i=i-1)
      {
        if (v_cont == 3)
        {
          temp1+="."+Num.charAt(i); 
          v_cont = 0;
        }
        else
        {
          temp1+=Num.charAt(i);
        }                
        v_cont++;
      }                        
      // damos la vuelta
      for (var i=temp1.length;i>=0;i=i-1)
      {
        temp2+= temp1.charAt(i);
      }

      if (val == null)
        field.value = temp2+end;
      else
        return temp2+end;
    }
  }
}




//============================================
// Valida el NIF       =======================
//============================================

function validaNIF(num)
{
  var error = false;
  var pos;
  //Comprobamos que no sea nulo
  if(num == "")
  {
    alert ("El campo NIF no puede estar vacio.");
    error = true;
  }
  //Comprobamos que tenga 9 digitos
  if (!error)
  {
    if (num.length != 9)
    {
    alert("Formato de NIF incorrecto.");
    error = true;
    }
  }
  //Comprobamos que los 8 primeros digitos sean numericos
  if (!error)
  {
    for (var i=0; i<8 ;i++)
    {
      pos = num.substr(i,1);
      if ((pos < "0") || (pos > "9"))
      {
        alert("Formato de NIF incorrecto.");
        error = true;
        break;
      }
    }
  }
  //Comprobamos que el ultimo caracter es una letra
  if (!error)
  {
    pos = num.substr(8,1); 
    pos2 = pos.toUpperCase ();
    if (isNaN(pos2) == false)
    {
      alert("Formato de NIF incorrecto.");
      error = true;
    }
  }
  //Comprobamos que la letra sea la correcta
  if (!error)
  {
    var numero = num.substr(0,8);
    var letra  = num.substr(8,1);
    var d =(numero/23);
    d = Math.floor(d);
    var e = d*23;
    var r = numero - e;
    switch (r)
    {
      case 0:
      if (letra != "T") {error = true;  alert("Letra de NIF incorrecta.");}
      break;
      case 1:
      if (letra != "R") {error = true;  alert("'||EW_LEE_TEXTO('LETRA_NIF_INCORRECTA')||'");}
      break;
      case 2:
      if (letra != "W") {error = true; alert("Letra de NIF incorrecta.");}
      break;
      case 3:
      if (letra != "A") {error = true; alert("Letra de NIF incorrecta.");}
      break;
      case 4:
      if (letra != "G") {error = true; alert("Letra de NIF incorrecta.");}
      break;
      case 5:
      if (letra != "M") {error = true; alert("Letra de NIF incorrecta.");}
      break;
      case 6:
      if (letra != "Y") {error = true; alert("Letra de NIF incorrecta.");}
      break;
      case 7:
      if (letra != "F") {error = true; alert("Letra de NIF incorrecta.");}
      break;
      case 8:
      if (letra != "P") {error = true; alert("Letra de NIF incorrecta.");}
      break;
      case 9:
      if (letra != "D") {error = true; alert("Letra de NIF incorrecta.");}
      break;
      case 10:
      if (letra != "X") {error = true; alert("Letra de NIF incorrecta.");}
      break;
      case 11:
      if (letra != "B") {error = true; alert("Letra de NIF incorrecta.");}
      break;
      case 12:
      if (letra != "N") {error = true; alert("Letra de NIF incorrecta.");}
      break;
      case 13:
      if (letra != "J") {error = true; alert("Letra de NIF incorrecta.");}
      break;
      case 14:
      if (letra != "Z") {error = true; alert("Letra de NIF incorrecta.");}
      break;
      case 15:
      if (letra != "S") {error = true; alert("Letra de NIF incorrecta.");}
      break;
      case 16:
      if (letra != "Q") {error = true; alert("Letra de NIF incorrecta.");}
      break;
      case 17:
      if (letra != "V") {error = true; alert("Letra de NIF incorrecta.");}
      break;
      case 18:
      if (letra != "H") {error = true; alert("Letra de NIF incorrecta.");}
      break;
      case 19:
      if (letra != "L") {error = true; alert("Letra de NIF incorrecta.");}
      break;
      case 20:
      if (letra != "C") {error = true; alert("Letra de NIF incorrecta.");}
      break;
      case 21:
      if (letra != "K") {error = true; alert("Letra de NIF incorrecta.");}
      break;
      case 22:
      if (letra != "E") {error = true; alert("Letra de NIF incorrecta.");}
      break;
    }
  }
  return error;
}





//============================================
// Validation Routines =======================
//============================================

function validarEmail(valor) {
	if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(valor)){
		return (true)
	} else {
		return (false);
	}
}

function notNull(sent) {
  if(!sent)return false;
  return (sent.length != 0);
}
//--------------------------------------------
function isInteger(sent) {
  if(!sent)return false;
  if(!String(sent).match(/\d{1,}/)) return false;
  return sent == String(sent).match(/\d{1,}/)[0];
}
//--------------------------------------------
function isFloat(sent) {
  if(!sent)return false;
  //return sent == String(sent).match(/\d*\,{0,1}\d*/)[0];
  return sent == String(sent).match(/\d*\,{0,1}\d*\.{0,1}/)[0];  
}
//--------------------------------------------
function isMoney(sent) {
  return sent == String(sent).match(/^\${0,1}\d*\.{0,1}\d{0,2}/)[0];
}
//--------------------------------------------
function isStateCode(sent) {
  sent = trim(String(sent).toUpperCase());
  return (STATECODES.indexOf(sent) != -1 && sent.indexOf("/") == -1);
}
//--------------------------------------------
function trim(sent) {
  var S = new String(sent);
  S = S.replace(/^\s+/,"");
  return S.replace(/\s+$/,"");
}
//--------------------------------------------
function filterChars(sent,chars) {
  var reg= new RegExp();
  reg.compile(chars,"gi");
  return String(sent).replace(reg,"");
}
//--------------------------------------------
function filterNonDigits(sent) {
  return String(sent).replace(/[^\d\.]/g," ");
}
//--------------------------------------------
function padZeros(sent,num) {
  sent=String(sent);
  while(sent.length<num)sent="0"+sent;
  return sent;
}
//--------------------------------------------
function formatFloat(sent,num){
  if(!isFloat(sent))return sent;
  var result=Math.round(sent*Math.pow(10,num));
  return result/Math.pow(10,num);
}

//============================================
// date routines =============================
//============================================

function makeFourDigitYear(sent) { // takes yy and tries to output yyyy
  if (sent.length>2) return sent;
  if (sent<50) return "20"+padZeros(sent,2);
  else return "19"+sent;
}
//--------------------------------------------
function getMonthLength(month,year) { // 1=jan
  year=makeFourDigitYear(year);  // year must be yyyy
  var monthlength = new Array(31,28,31,30,31,30,31,31,30,31,30,31);
  // leap year - any year divisible by 4 or 400 - add one day to february
  if (month==2 && (year/4==Math.floor(year/4) || year/400==Math.floor(year/400))) return 29;
  else return monthlength[month-1];
}
//--------------------------------------------
function addDaysToDate(date,days) {
  date=new Date(date);
  days=Math.floor(days); // forces a cast to integer
  var month=date.getMonth();
  var day  =date.getDate();
  var year =date.getFullYear();
  var tempday=day+days;
  if (tempday<1) {
    month--;
    if (month<0) month=11;
    tempday=getMonthLength(month,year)-tempday;
  }
  if (tempday>getMonthLength(month,year)) {
    tempday=getMonthLength(month,year)-tempday;
    month++;
    if (month>11) month=0;
  }
  return createDate(year,month,tempday);
}
//--------------------------------------------
function formatDate(date) { // converts date to m/d/yyyy format
  var month=date.getMonth();
  var day  =date.getDate();
  var year =date.getFullYear();
  return (month+1)+"/"+day+"/"+year;
}
//--------------------------------------------
function isDate(sent) {
  var dateArray=String(sent).split("/");
  if (dateArray.length != 3) return false;
  d=trim(dateArray[0]);
  m=trim(dateArray[1]);
  y=trim(dateArray[2]);
   
  if ((isInteger(m)==false) || (isInteger(d)==false) || (isInteger(y)==false)) return false;
  if (m<1 || m>12) return false;
  if (y.length != 4) y=makeFourDigitYear(y);
  if (y.length != 4) return false;
  if (d<1 || d>getMonthLength(m,y)) return false;
  return true;
}
//-------------------------------------------------
function isHora(hora)
{
  var hh = hora.substr(0,2);
  var mm = hora.substr(3,2);
  var err_hora = false;
                  
  if (hh.substr(0,1) == ":" || hh.substr(1,1) == ":")
  { 
    err_hora = true; 
  }
  else
  {
    if (mm.substr(0,1) == ":" || mm.substr(1,1) == ":")
    { 
      err_hora = true; 
    }
    else
    {
      if (hora.substr(2,1) != ":")
      { 
        err_hora = true; 
      }                      
    }
  }
  
  if (parseInt(hh,10)>=0 && parseInt(hh,10)<=23 && !err_hora)
  {
    if (parseInt(mm,10)>=0 && parseInt(mm,10)<=59)
    {                   
      return true;
    }
  }
  return false;
}  

//-------------------------------------------------
function isHoraT(hora)
{
  var hh = hora.substr(0,2);
  var mm = hora.substr(3,2);
  var err_hora = false;
                  
  if (hh.substr(0,1) == ":" || hh.substr(1,1) == ":")
  { 
    err_hora = true; 
  }
  else
  {
    if (mm.substr(0,1) == ":" || mm.substr(1,1) == ":")
    { 
      err_hora = true; 
    }
    else
    {
      if (hora.substr(2,1) != ":")
      { 
        err_hora = true; 
      }                      
    }
  }
  
  if (parseInt(hh,10)>=0 && !err_hora)
  {
    if (parseInt(mm,10)>=0 && parseInt(mm,10)<=59)
    {                   
      return true;
    }
  }
  return false;
} 

//--------------------------------------------
function getStartDay(month,year) { // returns day of week the first day of the month falls on
	var tempdate= new Date();
	tempdate.setDate(1);
	tempdate.setMonth(month);
	tempdate.setFullYear(year);
	return tempdate.getDay(); //0 to 6
}
//--------------------------------------------
function createDate(m,d,y) {
  return formatDate(new Date(parseInt(y),parseInt(m),parseInt(d)));
}

//============================================
// form validation routines ==================
//============================================

function valida_importe(formfield) {
  formfield.value=trim(formfield.value);
  if (notNull(formfield.value) && isMoney(formfield.value) ) return true;
  formfield.select();
  formfield.focus();
  error = error + 1;
  alert(texto_validacion_importe);
  return false;
}
//--------------------------------------------
function validateString(formfield, fieldname) {
  formfield.value=trim(formfield.value);
  if (notNull(formfield.value)) return true;
  formfield.select();
  formfield.focus();
  error = error + 1;
  alert("You must provide a "+fieldname);
  return false;
}
//--------------------------------------------
function validateStringLen(formfield, fieldname, len) {
  formfield.value=trim(formfield.value);
  if (formfield.value.length>=len) return true;
  formfield.select();
  formfield.focus();
  var temp= fieldname+" must be at least "+len+" character";
  if(len!=1)temp+="s"; 
  error = error + 1;
  alert(temp+" long.");
  return false;
}
//--------------------------------------------
function valida_no_nulo(formfield, fieldname) {
   formfield.value=trim(formfield.value);
   if (notNull(formfield.value)) return true;
  formfield.select();
  formfield.focus();
  error = error + 1;
  alert(texto_validacion_no_nulo);

}

//--------------------------------------------
function valida_decimal(formfield, fieldname) {
  formfield.value=trim(formfield.value);
  if (formfield.value=="") return true;
  if (isInteger(formfield.value) ) return true;
  formfield.select();
  formfield.focus();
  error = error + 1;
  alert(texto_validacion_decimal+fieldname);
  return false;
}
//--------------------------------------------
function valida_Float(campo, valor) {
  valor=trim(valor);
  if (valor=="") return true;
  fieldName  = campo.Name;
  fieldValue = valor
  if (fieldValue.indexOf(',') == -1) fieldValue += ",";
  dectext = fieldValue.substring(fieldValue.indexOf(',')+1, fieldValue.length);
  if (dectext.length <= decallowed) return true;
  campo.select();
  campo.focus();
  alert (texto_no_real);
  error = error + 1;    
  return false;
}

//--------------------------------------------
function valida_fecha(formfield) {
  formfield.value=trim(formfield.value);
  if (formfield.value=="") return true;
  else {
  if (isDate(formfield.value)) return true;
  formfield.select();
  formfield.focus();
  error = error + 1;
  alert(formfield.value+texto_validacion_fecha);
  formfield.value ="";
  return false;
  }
}
//--------------------------------------------
function valida_hora(formfield) {
  formfield.value=trim(formfield.value);
  if (formfield.value=="") return true;
  else {
  if (isHora(formfield.value)) return true;
  formfield.select();
  formfield.focus();
  error = error + 1;
  alert(formfield.value+texto_validacion_hora);
  return false;
  }
}

//--------------------------------------------
function valida_horaT(formfield) {
  formfield.value=trim(formfield.value);
  if (formfield.value=="") return true;
  else {
  if (isHoraT(formfield.value)) return true;
  formfield.select();
  formfield.focus();
  error = error + 1;
  alert(formfield.value+texto_validacion_hora);
  return false;
  }
}

//--------------------------------------------
// Funciones propias del campo TEXTAREA
//--------------------------------------------
function amplia_textarea(formfield,filas){
 formfield.rows=filas;
}

function reduce_textarea(formfield){
 formfield.rows=1;
}
    var cadena=new String();
 // CONTADOR DE CARACTERES
    var varicontador=0;
 // FUNCION QUE CUENTA EL NUMERO DE CARACTERES MOSTRADOS ENM EL TEXTAREA
 // CUANDO SE PULSA UNA TECLA
   function KEYDOWN(CAMPO, MAX_CARAC)
          {
            varicontador= MAX_CARAC - CAMPO.value.length;
          	if (varicontador>=0)
          	{
          	  cadena=CAMPO.value
          	}
          	else
          	{
          	  comprobar=CAMPO.value.length;

              if (comprobar>MAX_CARAC-1)
              {
                CAMPO.value=cadena;
              }

              CAMPO.value=cadena;
          	}
          }

          function KEYUP(CAMPO, MAX_CARAC)
          {
          	varicontador=MAX_CARAC- (CAMPO.value.length);
          	if (varicontador>=0)
          	 {
            	 cadena=CAMPO.value
          	 }
          	else
          	 {
            	 comprobar=CAMPO.value.length;
               if (comprobar>MAX_CARAC-1)
               {
                 CAMPO.value=cadena;
               }

               CAMPO.value=cadena;
          	 }
          }


//--------------------------------------------
        function solo_numeros_coma(campo)
	{
	  if (!((event.keyCode >= 48 && event.keyCode <= 57) || (event.keyCode == 44) || (event.keyCode == 43) || (event.keyCode == 45) ))
          {
            event.keyCode=0;
          }
	  if ((event.keyCode == 44) && (campo.value.indexOf(",") > -1))
	  {
            event.keyCode=0;
	  }
	  if (((event.keyCode == 43) || (event.keyCode == 45)) && ((campo.value.indexOf("+") > -1) || (campo.value.indexOf("-") > -1)))
	  {
            event.keyCode=0;
	  }
        }

        function formato_hora(campo)
	{
          if (!((event.keyCode >= 48 && event.keyCode <= 57) || (event.keyCode == 58)))
          {
            event.keyCode=0;
          }
	  if ((event.keyCode == 58) && (campo.value.indexOf(":") > -1))
	  {
            event.keyCode=0;
	  }
        }

        function solo_numeros()
	{
          if (!(event.keyCode >= 48 && event.keyCode <= 57))
          {
            event.keyCode=0;
          }
        }

        function solo_mayusculas()
	{
	  if ((event.keyCode >= 97 && event.keyCode <= 122))
          {
            event.keyCode= event.keyCode-32;
          }
        }

        function solo_minusculas()
	{
	  if ((event.keyCode >= 65 && event.keyCode <= 90))
          {
            event.keyCode= event.keyCode+32;
          }
        }

