// General validation file

/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
                             C O N S T A N T S
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/

LETTERS = "áéíóúÁÉÍÓÚabcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
LETRAS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
DIGITS = "0123456789";
ZIP_VALID = DIGITS;
PHONE_VALID = DIGITS + "+- ";
MAIL_VALID = LETTERS + DIGITS + "._@-";
INVALID_FOR_TEXT = DIGITS + "!·\\\"$%&/()=?¿|@#`+*^[]{}´¨_<>:;";
DATE_VALID=DIGITS + "/";

CIF_CODE = "1";
NIF_CODE = "2";

/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
                             F U N C T I O N S
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/

// Checks that a given character string has any character other than spaces
function isFilled (str)
{
	for (c = 0; c < str.length; c++)
	{
		if (str.charAt(c) != " ")
		{
			return true;
		}
	}
	return false;
}

// Checks if all the characters of the given string 'str' are present in the 
// char set 'valStr'
function validate (str, valStr)
{
	for (c = 0; c < str.length; c++)
	{
		if (valStr.indexOf (str.charAt (c)) == -1)
		return false;
	}
	return true;
}

// Checks that none of the characters in the given string 'str' are present in 
// the char set 'valStr'.
// The name is a straight kick to the Webster's Dictionary, all right.
function unvalidate (str, valStr)
{
	for (c = 0; c < str.length; c++)
	{
		if (valStr.indexOf (str.charAt (c)) != -1)
		{
			return false;
		}
	}
	return true;
}

function validateAlphabeticStr (str, desc, compulsory)
{
	if (compulsory == true && !isFilled (str))
	{
		alert (desc + " es un apartado obligatorio, por favor rellénelo.");
		return false;
	}
	
	if (str.length > 0)
	{
		if (!unvalidate (str, INVALID_FOR_TEXT))
		{
			alert (desc + " sólo puede contener letras");
			return false;
		}
	}
	return true;
}

function validateTime(stime){
 var desplazamiento =0; 
 if ((stime.length < 4) || (stime.length > 5)) return "";
 if (stime.length==5) {
  	desplazamiento =1;
 }
 var hora = stime.substring(0,2);
 var min  = stime.substring(2+desplazamiento,4+desplazamiento);
  if ((!validate(hora,DIGITS))||(!validate(hora,DIGITS))) {
   return "";
 }
 ihora = parseInt(hora);
 imin = parseInt(min);
 if ((ihora>23)||(imin>59)) return "";
 
 if (stime.length==5){
   if (!stime.substring(3,4)==":"){
	    return "";
   }
 }else{
  stime=hora+":"+min;
 }

 return stime;
}

function isLeapYear (year)
{
	return ((((year%4)==0) && !((year%100)==0)) || (((year%4)==0) && ((year%400)==0)));
}

function validateDate (str, desc, compulsory, canBeInTheFuture, mostrar)
{
	mensaje = "La fecha debe ser de la forma\ndd/mm/aaaa";

	if (compulsory && (!isFilled (str) || str=='dd/mm/aaaa'))
	{
		        if (mostrar)
			alert (desc + " es un apartado obligatorio.");
			return false;
	}
	
	if (str.length > 0)
	{
		if (!validate (str, DATE_VALID))
		{
		        if (mostrar)
			alert (desc + " no es una fecha valida.\n"+mensaje);
			return false;
		}
		if((str.length < 6) || (str.length == 7) || (str.length == 9))
		{
		        if (mostrar)
			alert (desc + " debe ser de la forma ddmmaa, ddmmaaaa, dd/mm/aa o dd/mm/aaaa.\n");
			return false;
		
		}
		if(str.length == 10){
			compactedDate = str.substring (0, 2) + str.substring (3, 5) + str.substring (6, 10);
			//alert ('Longitud 10 , fecha: '+compactedDate);
		}else if(str.length == 8){
			if(str.substring(2,3) == "/"){
				compactedDate = str.substring (0, 2) + str.substring (3, 5) + "20"+ str.substring (6, 8);
				//alert ('Longitud 8 con barras, fecha: '+compactedDate);
			}else{
				compactedDate = str;
				//alert ('Longitud 8 , fecha: '+compactedDate);
			}
		}else if(str.length == 6){
			compactedDate = str.substring (0, 4) +"20"+ str.substring (4, 6);
			//alert ('Longitud 6 , fecha: '+compactedDate);
		}
		if (!validate (compactedDate, DIGITS))
		{
		        if (mostrar)
			alert (desc + " no es una fecha valida.\n"+mensaje);
			return false;
		}
		if(compactedDate.substring (0, 1) == "0"){
			day = parseInt (compactedDate.substring (1, 2));
		}else{
			day = parseInt (compactedDate.substring (0, 2));
		}
		if(compactedDate.substring (2, 3) == "0"){
			month = parseInt (compactedDate.substring (3, 4));
		}else{
			month = parseInt (compactedDate.substring (2, 4));
		}
		year = parseInt (compactedDate.substring (4, 8));
		REGULAR_MONTHS = new Array (31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
		LEAP_MONTHS = new Array (31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
		curDate = new Date ();

		//alert("dia "+day);
		//alert("mes "+month);
		//alert("año "+year);
		//alert("hoy "+curDate);	

		if((month < 1) || (month > 12)){
		        if (mostrar)
			alert("Mes no válido.\nDebe estar entre 1 y 12.");
			return false;
		}

		if (!canBeInTheFuture)
		{
			curYear = curDate.getYear() + 1900;
			curMonth = curDate.getMonth () + 1;
//			alert ("current Date yyyy/mm/dd: " + curYear + "/" + curMonth + "/" + curDate.fate ());
//			alert ("input Date yyyy/mm/dd: " + year + "/" + month + "/" + day);

			if (curYear < year || 
			    curYear == year && curMonth < month ||
			    curYear == year && curMonth == month  && curDate.getDate () < day)
			{
                      		        if (mensaje)
					alert (desc + " es posterior a la fecha actual.");
					return false;
			}
		}
		//alert ("bisiesto : "+isLeapYear (year));		
		//alert ("day : "+day);
		//alert ("month : "+month);
		if (isLeapYear (year))
		{
			if (day < 1 || day > LEAP_MONTHS[month-1])
			{
        		        if (mostrar)
				alert (desc + " no es una fecha válida. 1");
				return false;
			}
		}
		else
		{
			//alert("max dia mes "+REGULAR_MONTHS[month-1]);	
			//alert("mes "+month);
			if (day < 1 || day > REGULAR_MONTHS[month-1])
			{
        		        if (mostrar)
				alert (desc + " no es una fecha válida. 2");
				return false;
			}
		}	
	}
	return true;
}

function parseDate(str){
	if(str.length == 10){
		compactedDate = str;
		//alert ('Longitud 10 , fecha final: '+compactedDate);
	}else if(str.length == 8){
		if(str.substring(2,3) == "/"){
			compactedDate = str.substring (0, 6) + "20"+ str.substring (6, 8);
			//alert ('Longitud 8 con barras, fecha: '+compactedDate);
		}else{
			compactedDate = str.substring (0, 2)+"/"+str.substring (2, 4)+"/" + str.substring (4, 8);
			//alert ('Longitud 8 , fecha: '+compactedDate);
		}
	}else if(str.length == 6){
		compactedDate = str.substring (0, 2)+"/" +str.substring (2, 4)+"/" +"20"+ str.substring (4, 6);
		//alert ('Longitud 6 , fecha: '+compactedDate);
	}
	return compactedDate;
}

function validateYear (str, desc, compulsory)
{
	if (compulsory == true && !isFilled (str))
	{
		alert (desc + " es un apartado obligatorio.");
		return false;
	}
	
	if (str.length != 4)
	{
		alert (desc + " debe tener 4 números como máximo.");
		return false;
	}
	
	if (!validate (str, DIGITS))
	{
		alert (desc + " es inválido.");
		return false;
	}
	
	year = parseInt (str);
	curYear = new Date().getYear() + 1900;
	
	if (year < 1800)
	{
		alert (desc + " es demasiado antiguo");
		return false;
	}
	
	if (year > curYear)
	{
		alert (desc + " debe ser menor del año actual (" + curYear + ")");
		return false;
	}
	return true;
}

function carga_cadena (el_string, el_array) 
{
	for(c=0; c < el_string.length; c++)
	{
  	el_array[c] = parseFloat (el_string.substring(c, c + 1));
  }
}

function getNextDate(date,days){

      if(date.substring(0,1) == "0"){
		day = parseInt (date.substring (1, 2));
	}else{
		day = parseInt (date.substring (0, 2));
	}
	if(date.substring(3,4) == "0"){
		month = parseInt (date.substring (4, 5)) -1;
	}else{
		month = parseInt (date.substring (3, 5))-1;
	}
	//month = parseInt (date.substring (3, 5))-1;
	year = parseInt (date.substring (6, 10));

	//alert(day);
	//alert(month);
	//alert(year);

	actualDate = new Date(year,month,day);

	//alert('Antes de actualizar '+actualDate);

	millis = actualDate.getTime()+days*24*60*60*1000;
	//alert('Tras actualizar '+actualDate+' en '+days+' dias '+millis);

	actualDate.setTime(millis);

	//alert(actualDate);


	nday = new Number(actualDate.getDate());
	nmonth = new Number(actualDate.getMonth())+1;
	nyear = new Number(actualDate.getYear());
	
	if(nyear < 1000){
		nyear += 1900;
	}

	//alert(nday);
	//alert(nmonth);
	//alert(nyear);


	if(nday < 10){
		aux = "0"+nday.toString()+"/";
	}else{
		aux = nday.toString()+"/";
	}

	if(nmonth < 10){
		aux = aux + "0"+nmonth.toString()+"/";
	}else{
		aux = aux + nmonth.toString()+"/";
	}

	aux = aux+nyear.toString();

	//alert(aux);
	return aux;
}

function getDays(date1,date2){
	if(date1.substring (0, 1) == "0"){
		day1 = parseInt (date1.substring (1, 2));
	}else{
		day1 = parseInt (date1.substring (0, 2));
	}
	//alert('day1 : '+day1);
	if(date1.substring (3, 4) == "0"){
		month1 = parseInt (date1.substring (4, 5))-1;
	}else{
		month1 = parseInt (date1.substring (3, 5))-1;
	}
	//alert('month1 : '+month1);
	year1 = parseInt (date1.substring (6, 10));

	actualDate1 = new Date(year1,month1,day1);

	millis1 = actualDate1.getTime();
	//alert('Fecha desde : '+millis1);

	if(date2.substring (0, 1) == "0"){
		day2 = parseInt (date2.substring (1, 2));
	}else{
		day2 = parseInt (date2.substring (0, 2));
	}
	if(date2.substring (3, 4) == "0"){
		month2 = parseInt (date2.substring (4, 5))-1;
	}else{
		month2 = parseInt (date2.substring (3, 5))-1;
	}
	year2 = parseInt (date2.substring (6, 10));

	actualDate2 = new Date(year2,month2,day2);

	millis2 = actualDate2.getTime();
	//alert('Fecha hasta : '+millis2);

	dif = millis2-millis1;

	days = dif/(24*60*60*1000);
	return days;
}
//**-------------------------------**
//email address checker!!
//**-------------------------------**
function emailChecker(email)
{
 var email_txt=email;
 var index_of_at = email_txt.indexOf("@");
 var index_of_last_dot = email_txt.lastIndexOf(".");
 var length = email_txt.length;

if (validate(email, MAIL_VALID)){

 if ((index_of_at < 1) || (index_of_last_dot < index_of_at) || (index_of_last_dot > length - 3) || (index_of_last_dot < length - 4))
 {
 	return false;
 }else{	
 	return true;

}
}
else 
return false;
}


//**-------------------------------**
//blank remover
//**-------------------------------**
function sinBlancos(valor){
	var index = valor.indexOf(" ");
	while(index != -1){
		valor = valor.substring(0,index)+valor.substring(index+1);
		index = valor.indexOf(" ");
		
	}
	return valor;
}