// validador.js
//
// JavaScript desarrollado por Julio Loayza para stanque.com
//
// Este JavaScript fue iniciado por Juan Luís Pérez para stanque.com
//
// Versión: 0.96
// Fecha: 26-03-2009
//
// JavaScript bajo licencia by-nc-sa 2.0 - http://creativecommons.org/licenses/by-nc-sa/2.0/
// JavaScript released under Creative Commons License - http://creativecommons.org/licenses/by-nc-sa/1.0/

function ValidarFormulario (formulario) {

	for (var i=0; i < formulario.length;i++) {
		//miramos que elementos del formulario hay que verificar
		campo_form = formulario.elements[i];
		
		if (campo_form.title !=null && campo_form.className !=null) {
			
			// primero desglosamos los distintos tipos de validacion
			//alert(document.forms[formnumero].elements[i].title);

			validaciones = campo_form.className.split (" ");

			for (n=0; n<validaciones.length; n++) {
			
				// Si el campo es tipo text:
				//--------------------------
			
				if (campo_form.type == "text") {
				
					// Si tiene que tener contenido y no lo tiene
									
					if (validaciones[n] == "not_empty" && campo_form.value == "") {
					
						alert (EL_CAMPO + '"' + campo_form.title + '"' + NO_VACIO);
						campo_form.select();
						campo_form.focus();
						return (false);
		
					// Si el campo no tiene por qué tener contenido verificamos si está vacío
					
					} else {
				
						// Si está vacío
					
						if (campo_form.value == "") {
						
							// No necesita pasar ninguna validación


						// Solo si el campo tiene algún valor verificamos que cumple las condiciones impuestas para su valor

						} else {
													
							if (validaciones[n] == "is_date") {
										
								if (check_date (campo_form)==false) {
									alert (EL_CAMPO + '"' + campo_form.title + '"' + FECHA_VALIDA);
									campo_form.select ();
									campo_form.focus ();
									return (false);
								}
			
							}
							
							if (validaciones[n] == "is_telephone") {
			
								if (check_telephone (campo_form.value)==false) {
									campo_form.select ();
									campo_form.focus ();
									return (false);
								}
			
							}
							
							if (validaciones[n] == "is_int") {
							
								if (check_int (campo_form.value)==false) {
									alert (EL_CAMPO + '"' + campo_form.title + '"' + DEBE_CIFRA_VALIDA);
									campo_form.select ();
									campo_form.focus ();
									return (false);
								}
			
							}
							
							if (validaciones[n] == "is_float") {
							
								if (check_float (campo_form.value)==false) {
									alert (EL_CAMPO + '"' + campo_form.title + '"' + DEBE_FLOAT_VALIDA);
									campo_form.select ();
									campo_form.focus ();
									return (false);
								}
			
							}
							
							if (validaciones[n] == "is_money") {
			
								if (check_money (campo_form.value, campo_form)==false) {
									alert (EL_CAMPO + '"' + campo_form.title + '"' + DEBE_DINERO);
									campo_form.select ();
									campo_form.focus ();
									return (false);
								}
			
							}
								
							if (validaciones[n]=="is_email") {
			
								if (check_email (campo_form.value)==false) {
									alert (EL_CAMPO + '"' + campo_form.title + '"' + DIRECCION_EMAIL_VALIDO);
									campo_form.select ();
									campo_form.focus ();
									return(false);
								}
			
							}
							
							if (validaciones[n]=="is_url") {
			
								if (check_url (campo_form.value) == false) {
									alert (EL_CAMPO + '"' + campo_form.title + '"' + DIRECCION_URL_VALIDA);
									campo_form.select ();
									campo_form.focus ();
									return (false);
								}
			
							}
						
						} // end if
											
					} // enf if
					
				} // End if tipo text
				
				
				
				// Si el campo es tipo textarea:
				//------------------------------

				if (campo_form.type == "textarea") {
				
					// Si tiene que tener contenido lo comprobamos
					
					if (validaciones[n] == "not_empty" && campo_form.value == "") {
					
						alert (EL_CAMPO + '"' + campo_form.title + '"' + NO_VACIO);
						campo_form.select();
						campo_form.focus();
						return (false);
						
					}
									
				} // End if tipo textarea
				
				
				
				// Si el campo es tipo checkbox:
				//------------------------------
				
				if (campo_form.type == "checkbox") {
				
					if (validaciones[n] == "not_empty" && campo_form.checked != true) {
					
						alert (NECESARIO_SELECCIONE + '"' + campo_form.title + '"');
						//campo_form.select();
						//campo_form.focus();
						return (false);
						
					}
					
				} // End if tipo checkbox
				
				
				
				// Si el campo es tipo file:
				//--------------------------
				
				if (campo_form.type == "file") {
				
					if (validaciones[n] == "not_empty" && campo_form.value == "") {
				
						alert (NECESARIO_ADJUNTAR + '"' + campo_form.title + '"');
						campo_form.select();
						campo_form.focus();
						return (false);
						
					}
				
				} // End if tipo file
				
				
				
				// Si el campo es tipo file:
				//--------------------------
				
				if (campo_form.type == "file") {
				
					if (validaciones[n] == "not_empty" && campo_form.value == "") {
				
						alert (NECESARIO_ADJUNTAR + '"' + campo_form.title + '"');
						campo_form.select();
						campo_form.focus();
						return (false);
						
					}
				
				} // End if tipo file


				
				// Si el campo es tipo select:
				//------------------------------

				if (campo_form.tagName == "SELECT") {
				
					// Si tiene que estar seleccionada al menos una opción
					
					if (validaciones[n]=="at_least_one") {
					
						if (campo_form.selectedIndex < 0) {
							alert (SE_HA_DE_SELECCIONAR + '"' + campo_form.title +'"');
							campo_form.focus ();
							return (false);
						}
					
					}
				
					// Si tiene que estar seleccionada cualquier opción con valor menos la primera
				
					if (validaciones[n]=="not_zero_selected") {
					
						if (campo_form.selectedIndex < 1) {
							alert (SE_HA_DE_SELECCIONAR + '"' + campo_form.title +'"');
							campo_form.focus ();
							return (false);
						}
					
					}
									
				} // End if tipo select


			} // End for
			
		} // End if

	} // End for
	
	return (true);

}

//---------------------------------------------------------
// Funciones de validación para tipos de campos específicos
//---------------------------------------------------------

function check_date(field){
	var checkstr = "0123456789";
	var DateField = field;
	var Datevalue = "";
	var DateTemp = "";
	var seperator = "/";
	var day;
	var month;
	var year;
	var leap = 0;
	var err = 0;
	var i;

   err = 0;
   DateValue = DateField.value;
   /* Delete all chars except 0..9 */
   for (i = 0; i < DateValue.length; i++) {
	  if (checkstr.indexOf(DateValue.substr(i,1)) >= 0) {
	     DateTemp = DateTemp + DateValue.substr(i,1);
	  }
   }
   DateValue = DateTemp;
   /* Always change date to 8 digits - string*/
   /* if year is entered as 2-digit / always assume 20xx */
  // if (DateValue.length == 6) {
  //   DateValue = DateValue.substr(0,4) + '20' + DateValue.substr(4,2); }
   if (DateValue.length != 8) {
      err = 19;}
   /* year is wrong if year = 0000 */
   year = DateValue.substr(4,4);
   if (year == 0) {
      err = 20;
   }
   /* Validation of month*/
   month = DateValue.substr(2,2);
   if ((month < 1) || (month > 12)) {
      err = 21;
   }
   /* Validation of day*/
   day = DateValue.substr(0,2);
   if (day < 1) {
     err = 22;
   }
   /* Validation leap-year / february / day */
   if ((year % 4 == 0) || (year % 100 == 0) || (year % 400 == 0)) {
      leap = 1;
   }
   if ((month == 2) && (leap == 1) && (day > 29)) {
      err = 23;
   }
   if ((month == 2) && (leap != 1) && (day > 28)) {
      err = 24;
   }
   /* Validation of other months */
   if ((day > 31) && ((month == "01") || (month == "03") || (month == "05") || (month == "07") || (month == "08") || (month == "10") || (month == "12"))) {
      err = 25;
   }
   if ((day > 30) && ((month == "04") || (month == "06") || (month == "09") || (month == "11"))) {
      err = 26;
   }
   /* if 00 ist entered, no error, deleting the entry */
   if ((day == 0) && (month == 0) && (year == 00)) {
      err = 0; day = ""; month = ""; year = ""; seperator = "";
   }

	if (DateTemp=='' || DateTemp=='undefined') {
		err=27;
	}
   /* if no error, write the completed date to Input-Field (e.g. 13.12.2001) */
   if (err == 0) {
      DateField.value = day + seperator + month + seperator + year;
	  return (true);
   }
   /* Error-message if err != 0 */
   else {
     // alert("Fecha incorrecta. Formato válido DD/MM/AAAA");
      DateField.select();
	  DateField.focus();
	  return (false);
   }

}

function check_float(str) {

	str = str.replace(".",",");

	var lstr=str.length;

	var numeros = "0123456789,";

	var contador_comas = 0;

	// Comprobamos que todo los caracteres sean numeros
	for (i = 0; i < lstr; i++) {
		if (numeros.indexOf(str.charAt(i)) == -1) {
			return false;
		}

		if (str.charAt(i) == ",") {
			contador_comas++;
		}

		if (contador_comas > 1) {
			// más de una coma
			return false;
		}
	}

	return true;
}

function check_int(str) {

	var lstr=str.length;

	var numeros = "0123456789";

	/* Comprobamoas que todo los caracteres sean numeros */
	for (i = 0; i < lstr; i++) {
		if (numeros.indexOf(str.charAt(i)) == -1) {
			return false;
		}
	}

	return true;
}

function check_telephone(str) {

		/* Comprobamos que tenga como máximo 20 digitos */
		var lstr=str.length;
		var numeros = "+0123456789 ";

		if (lstr > 20) {
			alert (TELEFONO_DIGITOS);
			return false;
		}

		/* Comprobamos que todo los digitos sean numeros */
		for (i = 0; i < lstr; i++) {
			if (numeros.indexOf(str.charAt(i)) == -1) {
				alert (CARACTER_NO_NUMERO);
				return false;
			}
		}

	 return true;
}

function check_money(str, objeto) {

	//str = str.replace(".",",");
	
	//objeto.value = str;
	
	var lstr=str.length;
	
	var numeros = "0123456789,";
	
	var contador_comas = 0;

	// Comprobamos que todo los caracteres sean numeros
	for (i = 0; i < lstr; i++) {
		if (numeros.indexOf(str.charAt(i)) == -1) {
			return false;
		}
		
		if (str.charAt(i) == ",") {
			contador_comas++;
		}
		
		if (contador_comas > 1) {
		
			// más de una coma
			
			return false;
		}
	}
	
	if (contador_comas == 0) {
	
		// si no hay comas la cifra es válida
		
		return true;
	
	} else {
	
		// si hay una coma vemos donde está
	
		if ((str.charAt(lstr - 3) == ",") || (str.charAt(lstr - 2) == ",")) {
		
			return true;
		
		} else {
		
			return false;
			
		}
	
	}

	 return false;
}

function check_email(str) {

	var at="@";
	var dot=".";
	var lat=str.indexOf(at);
	var lstr=str.length;
	var ldot=str.indexOf(dot);
	
	if (str.indexOf(at)==-1){
	   return false;
	}

	if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr) return false
	if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr) return false
	if (str.indexOf(at,(lat+1))!=-1)  return false
	if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot) return false
	if (str.indexOf(dot,(lat+2))==-1) return false
	if (str.lastIndexOf(dot) == 1) return false
	
	return true;
}

function check_url(str) {

	/* La "regular expresion" comentada es muy interesante pero exije que la URL
	termine con / y algún caracter p.e. http://www.losrealejos.es/es.
	Estaría bien analizarla y eliminar ese ultimo requisito. */

	//var urlFilter=/^http:\/\/.+\..+\..{2,3}\/.+$/;

	var urlFilter = null;

//	var urlFilter = /^(http:\/\/)/gi;

	var urlFilter = /^(ftp|http|https):\/\//gi;

	if (str.search(urlFilter)==-1) {
		return (false);
	} else {
		return (true);
	}

}