/*-----------------------------------------------------------
 
  Utilidades para la validación de Formularios
 
  NUM (numericos enteros)
  DATE (fechas inglesas mm/dd/yyyy )
  FECHA (fechas en español dd/mm/aaaa)
  CHAR (solo caracteres) y apartir de ahora tambien Caracteres especiales
  NUMCHAR (numeros y/o caracteres)
  NIF (Nif)
  EMAIL (Valida que tenga arroba, y un dominio correcto) 
  WEB (Que no tenga caracteres de ' al ,)
  PATH (Tipo ruta  Unidad:\Ruta\fichero.extension
  AREA (Alfanumerico y que permita el formato).
  SELECT (por lo menos se ha elegido una opcion) 
  TELEPHONE (Numeros enteros que pueden estar separados por / - y ())
  HORA (del tipo HH:MM)
  
 	Nalcom®

	Para utilizar este script de forma parcial o total se debe comunicar
	a Nalcom.
	
	desarrollo@nalcom.com
	
------------------------------------------------------------*/

var camposIni="";
var reWhitespace = /^\s+$/
var reLetter = /^[a-zA-Z]$/
var reAlphabetic = /^[a-zA-ZÑñáéíóú &.]+$/
//var reAlphanumeric = /^.+$/  // Alfabeto Internacional
var reAlphanumeric = /^[\wÑñáéíóú .&-]+$/  // Alfabeto Internacional  
var reDigit = /^\d$/
var reLetterOrDigit = /^([a-zA-Z]|\d)$/
var reArea = /^[\s.]+$/
var reInteger = /^\d+$/
var reDecimal = /^[\d+\.{1}]+$/

var reEmail=/\b(^[\w.]+@[\w.]+((\.com)|(\.net)|(\.edu)|(\.mil)|(\.gov)|(\.org)|(\..{2}))$)\b/gi;
// var reWeb = /^[\w%/.]+$/
var reWeb = /^(\http\72\57\57)?[\w%/.]+$/
var rePath = /^([a-zA-Z]\:\\)?[\w%\\~_()]+\.([\w~]{3})$/     //Tipo fichero
var reTelefono = /^[\d+\55/() ]+$/
var formulario = "";

/********* Variables del idioma ********************************/
var DIC_JS_HAY_ERRORES_DATOS_INTRODUCIDOS 
var DIC_JS_ESREQUERIDO 
var DIC_JS_ERROR_FECHAS
var DIC_JS_ELCAMPO 
var DIC_JS_ELCAMPO 
/***************************************************************
  Objeto vFormulario: Crea el objeto de validacion 
  
  Parametros:
  
		**nombre : es el nombre del formulario que se hace 
				   referencia. (REQUERIDO)
				   
		**devMensaje : Boolean, determina que devuelva un mensaje 
				   con todos elemento que no sean validos.(OPCIONAL)				   
				   
		**devFocoError : Boolean, determina que devuelva el foco
				   al elemento que no sea valido.(OPCIONAL)
				   
		**devColorAdvert : Boolean, determina que cambie el 
				   color de los elementos que no sean validos.(OPCIONAL)
				 
  Metodos:
  
		**vFormulario.validar(): Realiza la validacion de todo el formulario
			de acuerdo a los atributos definidos anteriormente.
			
		**vFormulario.esCampoValido(sTipo, el): Comprueba que es valido un elemento del
			formulario. Devueve true o false.
			sTipo : tipo de atributo que tiene el elemento.
			el : elemento del formulario.
			
		**vFormulario.escribeMsgError(label): Escribe en la propiedad del objeto el 
			mensaje que mostraremos al final de la validacion.
			Label es la etiqueta que se mostrará en le mensaje de error.

***************************************************************/ 

function vFormulario(nombre,devMensaje,devFocoError,devColorAdvert){
	var bFocoError = true;
	var bColorAdvert = true;
	var bMensaje = true;
	this.obj = nombre;
	this.formulario = "";
	this.msgError = "";
	this.firstError = "";
	if (vFormulario.arguments.length == 2) bMensaje = devMensaje;
	this.Error_Mensaje = bMensaje;
	if (vFormulario.arguments.length == 3) bFocoError = devFocoError;
	this.Error_devolver_Foco = bFocoError;
	if (vFormulario.arguments.length == 4) bColorAdvert = devColorAdvert;
	this.Error_Color_Advert = bColorAdvert;
	this.Error_Color = 'red';
	this.Original_Color = 'black';
	
	this.ponerColorRequerido()	
	this.chequearIdioma()
}

vFormulario.prototype.validar = validar;
vFormulario.prototype.esCampoValido = esCampoValido;
vFormulario.prototype.escribeMsgError = escribeMsgError;	
vFormulario.prototype.ponerColorRequerido = ponerColorRequerido;	
vFormulario.prototype.chequearIdioma = chequearIdioma;

/***************************************************************
  quitarCaracter: Elimina el caracter indicado de una cadena. 
***************************************************************/ 

function quitarCaracter(campo, sCaracter){
var sCadena = "";
var sAuxCaracter = "";
	for(var f = 0; f < campo.length; f++){
		sAuxCaracter = campo.substring(f,f+1);
		if(sAuxCaracter != sCaracter)
			sCadena += sAuxCaracter;
	}
	return sCadena;	
}

function estaVacio(cadena){
	
	if (cadena == null) {
		return ''
	}	
	return (reWhitespace.test(cadena) || (cadena.length == 0))
}

function isEmpty(s){
	return ((s == null) || (s.length == 0))
}

function isLetter (c){
	return (reLetter.test(c))
}

function isDigit(c){
	return (reDigit.test(c))
}

function isInteger(c){
	return (reInteger.test(c))
}

function isDecimal(c){
	return (reDecimal.test(c))
}

function isDecimal(c)
{
	var bOK
	if ((isNaN(c)) || (c.length==0) ){
		bOK = false
	} else {
		bOK = true
	}
	
	return bOK
}


function isAlphabetic(c){
	return (reAlphabetic.test(c))
}

function isAlphaNumeric(c){
	return (reAlphanumeric.test(c))
}

function isLetterOrDigit (c){   
	return (reLetterOrDigit.test(c))
}	

function esHora(c) 
{
	
	var vhoras = c.split(':')
	
	if (vhoras.length!=2) {
		return false
	}
	
	if ((isNaN(vhoras[0])) || (isNaN(vhoras[1]))) {
		return false
	}
	
	if ((parseInt(vhoras[0])<0) || (parseInt(vhoras[0])>23) || (parseInt(vhoras[1])<0) || (parseInt(vhoras[1])>59)) {
		return false
	}

	return true
}

function esMes(c) 
{
	
	if (c.length!=2) 
	{
		return false
	}
	
	if (isNAN(c))
	{
		return false
	}
	
	if ((parseInt(c)<1) || (parseInt(c)>12)) 
	{
		return false
	}

	return true
}

function esAno(c) 
{
	
	if (c.length!=4) 
	{
		return false
	}
	
	if (isNAN(c))
	{
		return false
	}
	
	if ((parseInt(c)<2009) || (parseInt(c)>2050)) 
	{
		return false
	}

	return true
}


function fFormateaFecha(objFecha)
{
		var arrayfecha;
		var dia;
		var mes;
		var anno;
		
		
		arrayfecha = objFecha.value.split('/')
		
		
		if (arrayfecha.length==1)
		{
			if (objFecha.value.length!=8) {
				alert('El campo fecha es erróneo. Formato (ddmmaaaa ó dd/mm/aaaa)')
				objFecha.focus()
				return (false)	
			}
			
			dia = objFecha.value.substring(0,2)
			mes = objFecha.value.substring(2,4)
			anno= objFecha.value.substring(4)
			
			objFecha.value = dia + '/' + mes + '/' + anno
			
			
		}
		
		return (true)	
		
}

function checkDate(c){
	var pos1;
	var arrayfecha;
	var fecha;
	
	
	
	pos1 = c.indexOf('/')
	if (!pos1) return (false);
	pos1 = c.indexOf('/',pos1+1)
	if (!pos1) return (false);
	arrayfecha = c.split('/')
	if(arrayfecha.length!=3) {
		return (false)	
	}
	
	//if (arrayfecha[2].length != 4) return(false);
	fecha = new Date(arrayfecha[1] + '/' + arrayfecha[0] + '/' + arrayfecha[2])

	if (arrayfecha[2].length != 4) {
		alert(DIC_JS_ERROR_FECHAS)
		return (false)
	}

	
	if ((fecha.getDate() == parseInt(arrayfecha[0],10)) && ((fecha.getMonth()+1) == parseInt(arrayfecha[1],10)) && ((fecha.getYear() == arrayfecha[2]) || (fecha.getFullYear() == arrayfecha[2]))) {
		return (true)
	} else {
		return (false)
	}
}

function escribeMsgError(label){
	this.msgError += DIC_JS_ELCAMPO + label + " " + DIC_JS_NOVALIDO + "\n";
}

/***************************************************************
  esCampoValido: Pasa el elemento a validar por su respectivo
				 funcion y devuelve su resultado.
***************************************************************/ 

function esCampoValido(sTipo,el){	
	switch (sTipo){
		case 'NUM':						
			if (!isInteger(el.value)){				
				return false
			} else return true
				
		case 'DECIMAL':						
			if (!isDecimal(el.value)){				
				return false
			} else {
				return true
			}

		case 'DATE':
			if (!checkDate(el.value,'eng')){
				return false
			}else return true
				
		case 'FECHA':		
			if (!checkDate(el.value,'spa')){				
				return false
			}else return true
			
		case 'HORA':
			if (!esHora(el.value)){
				return false
			}else return true
				
		case 'CHAR':
			if (!isAlphabetic(el.value)){
				return false
			}else return true

		case 'NUMCHAR':
			if (!isAlphaNumeric(el.value)){
				return false
			}else return true

		case 'NIF':
			if (!isNIF(el)){
				return false
			}else return true
				
		case 'EMAIL':
			if (!reEmail.test(el.value)){
				return false
			} else return true
			
		case 'WEB':
			if (!reWeb.test(el.value)){
				return false
			}else return true
		
		case 'PATH':
			if (!rePath.test(el.value)){
				return false
			}else return true

		case 'AREA':
			if (!reArea.test(el.innerText)){
				return false
			}else return true
				
		case 'SELECT':
			if ((isEmpty(el.options[el.selectedIndex].value) && isEmpty(el.options[el.selectedIndex].text)) || (el.options[el.selectedIndex].value==-1)){
				return false
			}else return true

		case 'TELEPHONE':
			if (!reTelefono.test(el.value)){
				return false
			}else return true
		
		case 'MES':
			if (!esMes(el.value)){
				return false
			}else return true
			
		case 'ANO':
			if (!esAno(el.value)){
				return false
			}else return true
			
		default:     // Para los que no tengan tipo
			return true;				
	}
}


/***************************************************************
  validar: Hace la funcion principal de la validacion
		   dependiendo del tipo dado en el atributo TIPO
		   Tambien acepta TEXTAREAs.					 
***************************************************************/ 

function validar(){	
	this.msgError = "";
	this.firstError = "";
	for (var i = 0; i < this.obj.elements.length; i++){
		var el = this.obj.elements[i];
		
		var sValor = (el.getAttribute("TIPO") == 'AREA')?el.innerText: el.value;
		//if ((estaVacio(sValor)) || (sValor==0)){		
		if (estaVacio(sValor)){			
			if (el.getAttribute("REQUERIDO") == "SI"){
				this.msgError += (DIC_JS_ELCAMPO + el.getAttribute("ETIQUETA") + " " + DIC_JS_ESREQUERIDO + "\n");
				if (this.firstError == "") this.firstError = i;
			}
		}
		else{		
			if(!this.esCampoValido(el.getAttribute("tipo"),el)){								
				this.escribeMsgError(el.getAttribute("etiqueta"));				
				if (this.Error_Color_Advert) el.style.color = this.Error_Color;
				if (this.firstError == "") this.firstError = i;
			}
			else{
				if (el.type != "button" && el.tagName != "select")el.style.color = this.Original_Color;
			}
		}		
	}//end for	
	if (!estaVacio(this.msgError) && this.Error_Mensaje){
		alert (DIC_JS_HAY_ERRORES_DATOS_INTRODUCIDOS + "\n\n" + this.msgError);		
		if (this.Error_devolver_Foco && this.firstError != ""){
			eval("this.obj.elements[" + this.firstError + "].focus();");			
			return false;
		}		
	}	
	else return true;
}

function ponerColorRequerido()
{
	for (var i = 0; i < this.obj.elements.length; i++){
		var el = this.obj.elements[i];

		if (el.getAttribute("REQUERIDO") == "SI"){
			el.style.backgroundColor='#fafad2'
		}
	}
	return true
}

function chequearIdioma()
{
	idioma = getCookie('COD_IDIOMA')
	switch (idioma)
	{
		case '002':
			DIC_JS_HAY_ERRORES_DATOS_INTRODUCIDOS = "I_Hay errores en los datos introducidos:"
			DIC_JS_ELCAMPO = "I_- El campo "
			DIC_JS_ESREQUERIDO = " I_es requerido"
			DIC_JS_ERROR_FECHAS = "Error, en las fechas el año se ha de especificar con 4 dígitos"
			DIC_JS_NOVALIDO ="I_no es válido"
			
			break;
		default:
			DIC_JS_HAY_ERRORES_DATOS_INTRODUCIDOS = "Hay errores en los datos introducidos:"
			DIC_JS_ELCAMPO = "- El campo "
			DIC_JS_ESREQUERIDO = " es requerido"
			DIC_JS_ERROR_FECHAS = "I_Error, en las fechas el año se ha de especificar con 4 dígitos"
			DIC_JS_NOVALIDO ="no es válido"
			break;
	}

}



function getCookie(NameOfCookie)
{
	
	// First we check if there is a cookie stored at all.
	// Otherwise the length of document.cookie would be zero.
	
	  if (document.cookie.length > 0) 
	{ 
	
	// Second we check if the cookies name is stored in the
	// "document.cookie"-object for the page.
	
	// Since more than just one cookie can be set on a
	// single page it is possible that our cookie
	// is not present, even though the "document.cookie"-object
	// is not just an empty text.
	// If our cookiename is not present the value -1 is stored
	// in the variable called "begin".
	
	    begin = document.cookie.indexOf(NameOfCookie+"="); 
	    if (begin != -1)   // Note: != means "is not equal to"
	   { 
	
	// Our cookie was set. 
	// The value stored in the cookie is returned from the function.
	
	     begin += NameOfCookie.length+1; 
	      end = document.cookie.indexOf(";", begin);
	      if (end == -1) end = document.cookie.length;
	      return unescape(document.cookie.substring(begin, end));       } 
	  }
	return null;  
	
	// Our cookie was not set. 
	// The value "null" is returned from the function.

}

 
	function fComprobarFecha(Cual)
	{
		if (Cual.value != '')
			{
				var arr_fecha = Cual.value.split('/')
							
				if (arr_fecha.length != 3 || arr_fecha[0].length > 2 || arr_fecha[0].length < 1 || arr_fecha[1].length > 2 || arr_fecha[1].length < 1 || arr_fecha[2].length != 4)
					{
						alert ('El campo Fecha debe tener el formato DD/MM/YYYY')
						Cual.focus()
						//Cual.value = ''
					}
				else
					{
						var fecha = new Date(arr_fecha[1] + '/' + arr_fecha[0] + '/' + arr_fecha[2])
						if (!((fecha.getDate() == arr_fecha[0]) && ((fecha.getMonth()+1) == arr_fecha[1]) && (fecha.getFullYear() == arr_fecha[2])))
							{
								alert ('El valor campo Fecha no es correcto')
								Cual.focus()
								//Cual.value = ''
							}
					}
			}
	}



	function fComprobarFecha2(Cual)
	{
		if (Cual.value != '')
			{
				var arr_fecha = Cual.value.split('/')
							
				if (arr_fecha.length != 3 || arr_fecha[0].length > 2 || arr_fecha[0].length < 1 || arr_fecha[1].length > 2 || arr_fecha[1].length < 1 || arr_fecha[2].length != 4)
					{
						alert ('El campo Fecha debe tener el formato DD/MM/YYYY')
						Cual.focus()
						return false
						//Cual.value = ''
					}
				else
					{
						var fecha = new Date(arr_fecha[1] + '/' + arr_fecha[0] + '/' + arr_fecha[2])
						if (!((fecha.getDate() == arr_fecha[0]) && ((fecha.getMonth()+1) == arr_fecha[1]) && (fecha.getFullYear() == arr_fecha[2])))
							{
								alert ('El valor campo Fecha no es correcto')
								Cual.focus()
								return false
								//Cual.value = ''
							}
					}
			}
			return true
	}
