/******************************************************************************
* funcionesFormulario.js     Natra                                            *
*                                                                             *
* Funciones basicas para la validacion de formularios                         *
* Ultima modificacion: 27/7/00                                                *
*                                                                             *
******************************************************************************/


function DateAdd(startDate, numDays, numWeeks, numMonths, numYears,p)
{
	var returnDate = new Date(startDate.getTime());
	var yearsToAdd = numYears;
	var month = returnDate.getMonth() + numMonths;
	if (month > 11)
	{
		yearsToAdd = Math.floor((month+1)/12);
		month -= 12*yearsToAdd;
		yearsToAdd += numYears;
	}
	returnDate.setMonth(month);

	returnDate.setFullYear(returnDate.getFullYear()	+ yearsToAdd);
	
	returnDate.setTime(returnDate.getTime()+60000*60*24*(numDays+7*numWeeks));
	
	mes=returnDate.getMonth()+1

	str=""+returnDate.getDate()+"/"+mes+"/"+returnDate.getFullYear()
	if (p==1){
		return returnDate.getDate();
	}
	if (p==2){
		return mes;
	}
	if (p==3){
		return returnDate.getFullYear();
	}
	return returnDate;
}

function YearAdd(startDate, numYears)
{
		return DateAdd(startDate,0,0,0,numYears);
}

function MonthAdd(startDate, numMonths)
{
		return DateAdd(startDate,0,0,numMonths,0);
}

function DayAdd(startDate, numDays)
{
		return DateAdd(startDate,numDays,0,0,0);
}

function eliminacaracteres (str, lista)
{   
	var i;
    var cadenafinal = "";

    // Buscar por el string, si el caracter no esta en "lista", 
    // agregarlo a returnString
    
    for (i = 0; i < str.length; i++)
    {   
		var aux = str.charAt(i);
        if (lista.indexOf(aux) == -1) cadenafinal += aux;
    }

    return cadenafinal;
}

	

var telChar = "()-+ "; // caracteres admitidos en numeros de telefono
// s es numero de telefono valido
//Autor: Jose Vicente Ruiz
function esNumeroTelefono (str)
{   
	var aux;
    aux = eliminacaracteres( str, telChar );
    return (esEntero(aux))
}


function cambiaDias(f1,nombre){
//	f1=document.formulario;
	nombred='d'+nombre;
	nombrem='m'+nombre;
	nombrea='a'+nombre;
	comboDia=eval('f1.'+nombred);
	comboMes=eval('f1.'+nombrem);
	comboAnyo=eval('f1.'+nombrea);
	var bloque31= new Array(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31);
	var diaSeleccionado=eval('f1.'+nombred+'.'+'options[f1.'+nombred+'.selectedIndex].value')-1;
	var mesSeleccionado=eval('f1.'+nombrem+'.'+'options[f1.'+nombrem+'.selectedIndex].value');
	var anyoSeleccionado=eval('f1.'+nombrea+'.'+'options[f1.'+nombrea+'.selectedIndex].value');
	
	if (eval('f1.'+nombrem+'.'+'options[f1.'+nombrem+'.selectedIndex].value')==4||eval('f1.'+nombrem+'.'+'options[f1.'+nombrem+'.selectedIndex].value')==6||eval('f1.'+nombrem+'.'+'options[f1.'+nombrem+'.selectedIndex].value')==9||eval('f1.'+nombrem+'.'+'options[f1.'+nombrem+'.selectedIndex].value')==11){
		diaMax=30;
	}
	if (eval('f1.'+nombrem+'.'+'options[f1.'+nombrem+'.selectedIndex].value')==0||eval('f1.'+nombrem+'.'+'options[f1.'+nombrem+'.selectedIndex].value')==1||eval('f1.'+nombrem+'.'+'options[f1.'+nombrem+'.selectedIndex].value')==3||eval('f1.'+nombrem+'.'+'options[f1.'+nombrem+'.selectedIndex].value')==5||eval('f1.'+nombrem+'.'+'options[f1.'+nombrem+'.selectedIndex].value')==7||eval('f1.'+nombrem+'.'+'options[f1.'+nombrem+'.selectedIndex].value')==8||eval('f1.'+nombrem+'.'+'options[f1.'+nombrem+'.selectedIndex].value')==10||eval('f1.'+nombrem+'.'+'options[f1.'+nombrem+'.selectedIndex].value')==12){
		diaMax=31;
	}
	if (eval('f1.'+nombrem+'.'+'options[f1.'+nombrem+'.selectedIndex].value')==2){
		if (anyoSeleccionado%4==0){
			diaMax=29;
		}
		else{
			diaMax=28;
		}
	}


	for (var i=0; i < diaMax; i++){
		eval('f1.'+nombred+'.options')[i]=new Option(eval("bloque31")[i],eval("bloque31")[i],true,true);
		selectedArray=new Array(diaMax);
	}
	if (diaSeleccionado>diaMax){
		diaSeleccionado=diaMax-1;
	}
	comboDia.selectedIndex=diaSeleccionado;

	while (selectedArray.length < eval('f1.'+nombred+'.length')) {
		eval('f1.'+nombred+'.'+'options')[eval('(f1.'+nombred+'.options.length - 1)')] = null;
	}

	if (eval('f1.'+nombred+'.options')[0].value == '') {
		eval('f1.'+nombred+'.options')[0]= null;
		if ( navigator.appName == 'Netscape') {
			if (parseInt(navigator.appVersion) < 4) {
				window.history.go(0);
			}
			else {   	
				if (navigator.platform == 'Win32' || navigator.platform == 'Win16') {
					window.history.go(0);
	            }
        	}
		}
	}

}



function esVacio(str)
  //comprueba si el valor que se le pasa como argumento es vacio
  //Autor: Jose Ferrer
  {
  return ((str == null) || (str.length == 0))
  }


function IsAlpha( str )
  //comprueba si el valor que se le pasa como argumento es un texto
  //Autor: Jose Ferrer
	{
	if (str+"" == "undefined" || str+"" == "null" || str+"" == "")
		return false;
	var isValid = true;
	str += "";	// convert to a string for performing string comparisons.
  	for (i = 0; i < str.length; i++) {
		// Alpha must be between "A"-"Z", or "a"-"z"
		if ( !( ((str.charAt(i) >= "a") && (str.charAt(i) <= "z")) ||
      			((str.charAt(i) >= "A") && (str.charAt(i) <= "Z")) ) ) {
         				isValid = false;
         				break;
      			}
   		}

	return isValid;
	}



function esEntero(str)
  //comprueba si el valor que se le pasa como argumento es un entero
  //Autor: Jose Ferrer
  {
  var err = 0
  var valid = "0123456789"
  var ok = "yes";
  var temp;

  if (str=="")
  	{err=1;}
  else
  {
	  for (var i=0; i< str.length; i++)
	    {
		temp = "" + str.substring(i, i+1);
		if (valid.indexOf(temp) == "-1") {
			err = 1;
			}
		}
  }
  if (err==1)
  {
		return (false);
  }
  else
  {
		return (true);
  }
  }  // end esEntero
  
function IsInt(str)
  //comprueba si el valor que se le pasa como argumento es un entero
  //Autor: Jose Ferrer
  //Modificado: Marc Climent (may-2005)
  {
  //var err = 0
  var valid = "0123456789"
  var ok = "yes";
  var temp;

  for (var i = 0; i < str.length; i++)
    {
	  temp = "" + str.substring(i, i + 1);
	  if (valid.indexOf(temp) == "-1") { return (false); }
	}
	
  return (true);
}  // end IsInt
  
var defaultEmptyOK = false;
//var reEmail = /^[A-Z, a-z, 0-9,_]+\.{0,1}[A-Z, a-z, 0-9,_]+\@[A-Z, a-z, 0-9,_]+\.[A-Z, a-z, 0-9,_]+$/;
//var reEmail = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w+)+$/;
var reDecimal = /^[0-9]*[\.,]?[0-9]*$/;
function esDecimal (str)
{
	if ((str == '.') || (str == ','))
	{
		return (false);
	}
	else
	{
		if (!reDecimal.test(str))
		{
			return (false);
		}
		else
		{
			return (true);
		}
  	}
}  

function esReal(str)
  //comprueba si el valor que se le pasa como argumento es un real
  //es igual que la función esEntero solo que admite la ","
  //Autor: Jose Ferrer
  {
  var err = 0
  var valid = "0123456789,"
  var ok = "yes";
  var temp;

  for (var i=0; i< str.length; i++)
    {
	temp = "" + str.substring(i, i+1);
	if (valid.indexOf(temp) == "-1") err = 1;
	}
  
  if (err==1)
	{
	return (false);
	}
  else
    {
	return (true);
	}
  }  // end esEntero  
 /* 
Auto center window script- Eric King (http://redrival.com/eak/index.shtml)
Permission granted to Dynamic Drive to feature script in archive
For full source, usage terms, and 100's more DHTML scripts, visit http://dynamicdrive.com
*/

var win = null;
function NewWindow(mypage,myname,w,h,scroll){
LeftPosition = (screen.width) ? (screen.width-w)/2 : 0;
TopPosition = (screen.height) ? (screen.height-h)/2 : 0;
settings =
'height='+h+',width='+w+',top='+TopPosition+',left='+LeftPosition+',scrollbars='+scroll+',toolbar'
win = window.open(mypage,myname,settings)
if(win.window.focus){win.window.focus();}
}



function abreControl(strURLVentana)
{

//abre la ventana auxiliar de control que lista las actividades tareas etc... del proyecto actual

w=475;
h=330;

LeftPosition = (screen.width) ? (screen.width-w-10) : 0;
//TopPosition = (screen.height) ? (screen.height-h) : 0;
TopPosition = 10;

var winopts =
        'toolbar=no,titlebar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,top='+TopPosition+',left='+LeftPosition+',width='+w+',height='+h

//var winopts='alwaysRaised=1,dependent=1,height=' + h + ',location=0,menubar=0,personalbar=0,systembar=0,scrollbars=0,status=0,toolbar=0,width=' + w + ',resizable=0,nobar,nobars'
		
CtrlWin = window.open(strURLVentana,"CtrlWin",winopts);
//CtrlWin.IMAWin = this.window;
}



var defaultEmptyOK = false;
//var reEmail = /^[A-Z, a-z, 0-9,_]+\.{0,1}[A-Z, a-z, 0-9,_]+\@[A-Z, a-z, 0-9,_]+\.[A-Z, a-z, 0-9,_]+$/;
//var reEmail = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w+)+$/;
var reEmail = /^(\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w+)+)(\;(\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w+)+))*\;?$/;
function comprueba_email (str)
  {
	if (!reEmail.test(str))
	  {
	  return (false);
	  }
	else
	  {
	  return (true);
	  }
  }


  

function comprueba_dni(frm)
{
	string1 = frm.NIF.value
	
	if (string1.length!=9)
	{
		alert('El DNI introducido no es correcto');
		frm.NIF.focus();
		return (false);
	}
	
	numerosDNI = string1.substring(0, 8) // numeros dni
	letrasDNI = string1.substring(8, 9) // letras dni
	
	if (!comprueba_nDNI(numerosDNI)) return (false);
	if (!comprueba_lDNI(letrasDNI)) return (false);
	if (!valida_DNI(numerosDNI,letrasDNI)) return (false);
	return (true);
}

/*
	comprobarNIF(frm)
	
	Esta función comprueba el NIF o el CIF.
	Es la única que se debe usar y todas las demás hacen referencia
	a esta por lo que no deberían usarse.
	
	Salida:
	
	-1 -> Longitud incorrecta
	-2 -> Datos incorrectos
	-3 -> Letra de NIF incorrecta
	-4 -> Caracteres inválidos
	-5 -> Letra de CIF inválida
	-6 -> Control de CIF inválido
	
	1 -> Valor correcto
*/
function comprobarNIF(nif)
{
	//NIF  [0-9]{8}[A-Za-z]
	//CIF  [A-Za-z][([0-9]{7}[A-za-z])([0-9]{8})]

	var esCIF = false;

	if (nif.match(/[,.-]/)) { return -4; /* Carácteres inválidos */	}
	if (nif.length != 9)    { return -1; /* Longitud incorrecta */ }
	
	pos = nif.search(/\D{1}/);

	if (pos == 0)
	{
		/**** CIF ****/
		esCIF = true;
		
		letra = nif.match(/^\D{1}/);
		numero = nif.match(/\d{7}/);
		control = nif.match(/\w{1}$/);
	}
	else
	{
		/**** NIF *****/
		esCIF = false;
		
		numero = nif.match(/\d{8}/);
		letra = nif.match(/\D{1}/);
	}

	if (!numero || !letra) { return -2; /* Datos incorrectos */ }
	
	if (esCIF)
	{
		// **** CIF ****
		letras = ['A','B','C','D','E','F','G','H','K','L','M','N','P','Q','S'];
		
		for (i in letras) { if (letras[i] == letra) { break; } }
		if (i == letras.length - 1)	{ return -5; /* Letra inválida de CIF */ }
		
		/*** TODO ***/
		/* Acabar la comprobación de CIF -> No necesario de momento */
		numero = numero.toString();

		suma = 0;
		
		/* Suma de las posiciones pares */
		for (i = 1; i < numero.length; i += 2)
		{
			suma = suma + parseInt(numero.charAt([i]));
		}
		
		/* Suma de las impares */
		for (i = 0; i < numero.length; i += 2)
		{
			aux = (parseInt(numero.charAt([i])) * 2).toString();
			for (j = 0; j < aux.length; j++)
			{
				suma = suma + parseInt(aux.charAt([j]));
			}
		}
		
		suma = suma.toString();
		digito = suma.charAt(suma.length - 1);
		digito = (10-digito).toString();;
		digito = digito.charAt(digito.length - 1);

		letras_validas = ['J','A','B','C','D','E','F','G','H','I']
		
		if ((control != digito) && (control != letras_validas[digito])) { return -6; /* Control inválido */ }
	}
	else
	{
		letra = letra.toString().toUpperCase();  // Pasar primero a string!
		res = (numero % 23);

		//obtengo la letra que se corresponde en teoria con los numeros
		letras = ['T','R','W','A','G','M','Y','F','P','D','X','B','N','J','Z','S','Q','V','H','L','C','K','E','T'];

		if (letra != letras[res])
		{
			return -3; // Letra incorrecta
		}
	}
	
	return 1; // Salida correcta
}

/*
	comprueba_NIF(frm)
	
	Llama a comprobarNIF y interpreta los resultados
*/
function comprueba_NIF(frm)
{
	result = comprobarNIF(frm.NIF.value);

	switch(result)
	{
		case -1:
			alert('Longitud del NIF incorrecta');
			return (false);
			break;
		case -2:
			alert('El formato del NIF es incorrecto.');
			return (false);
			break;
		case -3:
			alert('Letra del NIF incorrecta.');
			return (false);
			break;
		case -4:
			alert('Carácteres inválidos.');
			return (false);
			break;
		case -5:
			alert('Letra de CIF inválida.');
			return (false);
			break;
		case -6:
			alert('Control de CIF inválido.');
			return (false);
			break;
		case 1:
			return (true);
	}
}

/*
	comprueba_CIF(frm)
	
	Llama a comprobarNIF y interpreta los resultados
*/
function comprueba_CIF(frm)
{
	result = comprobarNIF(frm.CIF.value);

	switch(result)
	{
		case -1:
			alert('Longitud del CIF incorrecta');
			return (false);
			break;
		case -2:
			alert('El formato del CIF es incorrecto.');
			return (false);
			break;
		case -3:
			alert('Letra del CIF incorrecta.');
			return (false);
			break;
		case -4:
			alert('Carácteres inválidos.');
			return (false);
			break;
		case -5:
			alert('Letra de CIF inválida.');
			return (false);
			break;
		case -6:
			alert('Control de CIF inválido.');
			return (false);
			break;
		case 1:
			return (true);
	}
}


/*
 * Genérico - Hay que pasar el campo completo, no solo el formulario
 *            y el texto que debe aparecer en el error y la posición
 *            de la letra: 0 -> inicial, 1 -> final
 */
/***** DEPRECATED ******/
function comprueba_ID(objID, strNombre, posLetra)
{
	var strID = objID.value;
	var numero, letra;
	
	if (strID.length != 9)
	{
		alert('El ' + strNombre + ' introducido no es correcto.');
		objID.focus();
		return (false);
	}
	
	if (posLetra = 0)
	{
		numero = strID.substring(1, 9) // numeros CIF
		letra  = strID.substring(0, 1) // letra CIF
	}
	else
	{
		numero = strID.substring(0, 8) // numeros CIF
		letra  = strID.substring(8, 9) // letra CIF
	}

	if (letra == "" || !IsAlpha(letra))
	{
		alert('Introduzca correctamente la letra del '+ strNombre +'.');
		objID.focus();
		return (false);
	}

	if (numero == "" || !IsInt(numero))
    {
	    alert('Introduzca correctamente los números del '+ strNombre +'.');
		objID.focus();
		return (false);
	}

	if (numero.length != 8)
	{
		alert('El ' + strNombre + ' debe contener 8 números.');
		objID.focus();
		return (false);
	}
	
	return (true);
}


/*
 * Esta función limpia el contenido del campo si contiene todavía el
 * valor por defecto. En otro caso, se deja el texto como está.
 * Utilidad: Para los formularios que ya aparecen rellenados por el
 * tema de accesibilidad
 */
function limpiarCampo(objeto, defecto)
{
	if (objeto.value == defecto) { objeto.value = ''; }
	return true;
}

