//onsubmit="return validar('document.agenda','Nom','Nom','','Lloc','Lloc','','DataInici','Data inici','di','DataFi','Data fi','df')"

function validar(){
//alert("aca estamos");
    var color2='#FFFFE1'
    var color='#ffffff'
	var args=validar.arguments;
	var numargs=args.length;
	var envia,missatge,tipus
	var incorrecte=''
	
	for (i=1; i<(numargs-1); i+=3)
	{
		if (numargs==3)
		{
			obj=args[0];
			envia=false;
			missatge=args[1]
			tipus=args[2]
		}
		else 
		{
			obj=eval(args[0] + '.' + args[i])
			envia=true;
			missatge='"' + args[i+1] + '"'			
			tipus=args[i+2]
		}

		if ((tipus == 'doc') || (tipus == 'img'))
		{
			
			if (tipus == 'doc')
				ext = ['doc', 'pdf']
			else
				ext = ['gif', 'jpg', 'swf']

			elem=obj.value;
			tamanio = elem.length;
			tmp = elem.substr(tamanio-3);
			tmp = tmp.toLowerCase();
			typevalid = false
			
			if (elem != '')
			{
				for(cont = 0; cont < ext.length && !typevalid; cont++)
				{
					if (tmp == ext[cont])
					{		
						typevalid = true
						obj.style.backgroundColor=color
					}
				}
			
				if (!typevalid)
				{
					if (!incorrecte){obj.focus()};
					incorrecte+= missatge + ' is not an archive of correct type.\n'
					obj.style.backgroundColor=color2		
				}
				else
					obj.style.backgroundColor=color
			 }
			 else
				obj.style.backgroundColor=color
		  }

		  if (tipus == 'ext')
		  {
			ext = args[i+3].split("-"); 
			i = i + 1;
			elem=obj.value;
			tamanio = elem.length;
			tmp = elem.substr(tamanio-3);
			tmp = tmp.toLowerCase();
			typevalid = false
			
			if (elem != '')
			{
				for(cont = 0; cont < ext.length; cont++)
				{
					if (tmp == ext[cont])
					{		
						typevalid = true
						obj.style.backgroundColor=color
					}
				}
				
				if (!typevalid)
				{
					if (!incorrecte){obj.focus()};
					incorrecte+= missatge + ' is not an archive of correct type.\n'
					obj.style.backgroundColor=color2		
				}
				else
					obj.style.backgroundColor=color
			}
			else
				obj.style.backgroundColor=color
		}

        // obligatori
        if ((tipus=='') || (tipus=='no') || (tipus=='mo')){
			
			tmpStr = Trim(obj.value);
			tmpStr = tmpStr.replace(String.fromCharCode(160), '');	
			if ((tmpStr=="")||(tmpStr==" "))
				{
					if (!incorrecte){obj.focus()};
					incorrecte+=missatge + ' is obligatory\n'
					obj.style.backgroundColor=color2
					//obj.focus()
				}
				else
				{		
					obj.style.backgroundColor=color
					if (tipus=='no'){tipus='n'};
					if (tipus=='mo'){tipus='m'};
				}
		}
		// mail
        if ((tipus=='m')  && (obj.value!='')){
		mail=obj.value
		arrob=mail.indexOf('@')
		punt=mail.indexOf('.',arrob+2)
		ultim=mail.length-1		
			if ((arrob==-1) || (punt==-1) || (arrob==0) || (punt==ultim))
			{
				if (!incorrecte){obj.focus()};
				incorrecte+= missatge + ' is not a valid direction of email\n'
				obj.style.backgroundColor=color2						
			}
			else
			{		
				obj.style.backgroundColor=color
			}
		}

		// número 
        if(tipus=='n'){
			if ((obj.value!=Number(obj.value)) && (obj.value!=''))
			{
				if (!incorrecte){obj.focus()};
				incorrecte+= missatge + ' must be numerical value\n'
				obj.style.backgroundColor=color2				
			}
			else
			{		
				obj.style.backgroundColor=color
			}
			if (obj.value==''){obj.value='0'}
		}

		// cp
		if (tipus=='cp')
		{
			if ((obj.value!=Number(obj.value)) && (obj.value!='')  || (obj.value<10000))
			{			
				if (!incorrecte){obj.focus()};
				incorrecte+= missatge + ' must be numerical value of 5 digits.\n'
				obj.style.backgroundColor=color2				
			}
			else
			{		
				obj.style.backgroundColor=color
			}
		}

		// llargada maxima 
        if(tipus>1){
			if (obj.value.length > tipus)
			{
				if (!incorrecte){obj.focus()};
				incorrecte+= missatge + ' contains ' + obj.value.length + ' characters, cannot be but wide of  ' + tipus + ' \n'
				obj.style.backgroundColor=color2				
			}
			else
			{		
				obj.style.backgroundColor=color
			}
		}

		// data
		if (tipus=='di')
		{
			var obj2=eval(args[0]);
			var Any=obj2.ano.value;
			var Mes=obj2.mes.options[obj2.mes.selectedIndex].value;
			var Dia=obj2.dia.options[obj2.dia.selectedIndex].value;
			
			if ((Any == "") || (Any!=Number(Any)))
			{
			incorrecte+= missatge + "forgets the year or it has introduced a nonnumerical value\n"
			}
			else
				{
				if ((Any<999) || (Any>9999))
					{
					incorrecte+= missatge + "The year is incorrect\n"
					}
				}
			
		    if ((Mes==2) && (Dia>28))
			{
				if (((Any/4)==parseInt(Any/4)) && (Dia<30))
				{
				}
				else
				{
				incorrecte+= missatge + 'The date is incorrect\n'
				}
			}
			if ((Mes==4) || (Mes==6) || (Mes==9) || (Mes==11))
			{
				if (Dia>30)
				{
					incorrecte+= missatge + 'The date is incorrect \n'
				}
			}
		}
		
// valor del select 
        if(tipus.indexOf('VAL')!=1){
			if (('VAL' + obj.value)==tipus)
			{
				if (!incorrecte){obj.focus()};
				incorrecte+='Must select ' + missatge + ' \n'
//				obj.style.backgroundColor=color2				
			}
			else
			{		
				//obj.style.backgroundColor=color
			}
		}
		

// fecha
        if(tipus=='data'){
        var tmp=obj.value
			if (!validaData(obj) && (tmp!=''))
				{
					if (!incorrecte){obj.focus()};
					incorrecte+= missatge + ' is not correct\n'
					obj.style.backgroundColor=color2			
				}	
			else
				{
				obj.style.backgroundColor=color
				} 
		}
		

// fi validacio
	}
	if (incorrecte){
	    incorrecte= '\nHas not filled up the form correctly:\n\n' + incorrecte
		alert (incorrecte)
	}
	if (envia){
		return (incorrecte=='')
	}
}

function validaData(obj)
{
	var fecha,DataNova;
	fecha = obj.value	
	fechaArray = fecha.split("/")
	
	if (fechaArray.length!=3)
		{
		fechaArray = fecha.split("-");
		}	
	
	if (fechaArray.length==3)
		{
		DataNova = new Date(fechaArray[2],fechaArray[1]-1,fechaArray[0]);
		}
	else
		{
		obj.value = '';
		return false;
		}
	if (isNaN(DataNova))
		{
		obj.value = '';
		return false;
		}
	else
		{
		obj.value = DataNova.getDate() + '/' + (DataNova.getMonth() + 1) + '/' + DataNova.getYear() ;
		return true;
		}
}

/*
 * Función agregada para validar  que fecha2 < fecha1.
 * Param: formulario es el form que contiene a los input.
 * descripcion: los input son type text (fecha1, fecha2) , separador "/".
 */
 
function DiferenciaFechas (msg_fecha_ini, fecha_ini, msg_fecha_fin, fecha_fin, separador) {

  //Obtiene los datos del formulario
//   CadenaFecha1 = fecha_ini.value
//   CadenaFecha2 = fecha_fin.value

   CadenaFecha1 = fecha_ini;
   CadenaFecha2 = fecha_fin;
   
   //Obtiene dia, mes y año
//   var fecha1 = new fecha( CadenaFecha1 , separador)   
//   var fecha2 = new fecha( CadenaFecha2 , separador)
   var fecha1 = new fecha( CadenaFecha1 );   
   var fecha2 = new fecha( CadenaFecha2 );
   
   //Obtiene objetos Date
   var miFecha1 = new Date(fecha1.anio, fecha1.mes ,fecha1.dia)
   var miFecha2 = new Date(fecha2.anio, fecha2.mes, fecha2.dia)

   //Resta fechas y redondea
   var diferencia = miFecha2.getTime() - miFecha1.getTime()
   var dias = Math.floor(diferencia / (1000 * 60 * 60 * 24))
/*   var segundos = Math.floor(diferencia / 1000)
   alert ('La diferencia es de ' + dias + ' dias,\no ' + segundos + ' segundos.')*/
   var segundos = Math.floor(diferencia / 1000)
   
   if (dias < 0)
   		alert (' ' + msg_fecha_fin +' must be greater than '+ msg_fecha_ini +'!');
  	
   return dias;
}



function fecha( cadena ) {
   //Separador para la introduccion de las fechas
   var separador = "/"

   //Separa por dia, mes y año
   if ( cadena.indexOf( separador ) != -1 ) {
        var posi1 = 0
        var posi2 = cadena.indexOf( separador, posi1 + 1 )
        var posi3 = cadena.indexOf( separador, posi2 + 1 )
        this.dia = cadena.substring( posi1, posi2 )
        txtMes = cadena.substring( posi2 + 1, posi3 ) - 1
		txtMes = "0" + txtMes;
		this.mes = txtMes.substring( txtMes.length -2, txtMes.length )
        this.anio = cadena.substring( posi3 + 1, cadena.length )
   } else {
        this.dia = 0
        this.mes = 0
        this.anio = 0   
   }
}


function Trim(TRIM_VALUE)
{
	if(TRIM_VALUE.length < 1)
	{
		return"";
	}
	
	TRIM_VALUE = RTrim(TRIM_VALUE);
	TRIM_VALUE = LTrim(TRIM_VALUE);
	if(TRIM_VALUE=="")
	{
		return "";
	}
	else
	{
		return TRIM_VALUE;
	}
} 


function RTrim(VALUE)
{
	var w_space = String.fromCharCode(32);
	var v_length = VALUE.length;
	var strTemp = "";
	if(v_length < 0)
	{
		return"";
	}
	var iTemp = v_length -1;

	while(iTemp > -1)
	{
		if(VALUE.charAt(iTemp) == w_space){	}
		else
		{
			strTemp = VALUE.substring(0,iTemp +1);
			break;
		}
		iTemp = iTemp-1;
	}	 
	return strTemp;
} 

function LTrim(VALUE)
{
	var w_space = String.fromCharCode(32);
	if(v_length < 1)
	{
		return"";
	}
	var v_length = VALUE.length;
	var strTemp = "";
	
	var iTemp = 0;
	
	while(iTemp < v_length)
	{
		if(VALUE.charAt(iTemp) == w_space){	}
		else
		{
			strTemp = VALUE.substring(iTemp,v_length);
			break;
		}
			iTemp = iTemp + 1;
		} 
		return strTemp;
} 