/******************************************************************************
* funcionesFormulario.js     Natra                                            *
*                                                                             *
* Funciones basicas para la validacion de formularios                         *
* Ultima modificacion: 18/12/06                                                *
*                                                                             *
******************************************************************************/


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('Dia',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');
	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+1; 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;
	}
	
	comboDia.selectedIndex=diaSeleccionado;
	
	while (diaMax < eval('f1.'+nombred+'.length')-1) {
		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 compara_fechas(obj)
  {
 
  var df1 = parseInt(obj.dFechaInicioE.options[obj.dFechaInicioE.selectedIndex].value); // dia fecha1
  var mf1 = parseInt(obj.mFechaInicioE.options[obj.mFechaInicioE.selectedIndex].value); // mes fecha1
  var af1 = parseInt(obj.aFechaInicioE.options[obj.aFechaInicioE.selectedIndex].value); // año fecha1
 
  var df2 = parseInt(obj.dFechaFinE.options[obj.dFechaFinE.selectedIndex].value); // dia fecha2
  var mf2 = parseInt(obj.mFechaFinE.options[obj.mFechaFinE.selectedIndex].value); // mes fecha2
  var af2 = parseInt(obj.aFechaFinE.options[obj.aFechaFinE.selectedIndex].value); // año fecha2
  //alert(af1+" "+af2);
  /*miro los años*/

  if (af2>af1)
    {
	return(true);
	}
  else if (af2<af1)
    {
	return(false);
	}
  else if (af2==af1)
    {
	/*miro los meses*/

	if (mf2>mf1)
	  {

	  return(true);
	  }
	  else if (mf2<mf1)
	    {
	
		return(false);
		}
	  else if (mf2==mf1)
	    {

		/*miro los dias*/
		if (df2>df1)
		  {
		  return(true);
		  }
		else if (df2<df1)
		  {
		  return(false);
		  }
		else if (df2==df1)
		  {
		  return(true);
		  }
	  	}
		/*fin miro los dias*/
	    }
	/*fin miro los meses*/
  }

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 esEntero2(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;

  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 if ((parseInt(str) > 10) || (parseInt(str) < 0))
  {
  	return (false)
  }
  if (err!=1)
  {	
	return (true);
  }  // end esEntero2
}
  
	
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;

  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
  
 function esDecimal(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 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+)+$/;
//aitex -> var reEmail = /^[\w,ñ,Ñ]+([\.-]?[\w,ñ,Ñ]+)*@[\w,ñ,Ñ]+([\.-]?[\w,ñ,Ñ]+)*(\.[\w,ñ,Ñ]+)+$/;

function comprueba_email (str)
  {
	if (!reEmail.test(str))
	  {
	  return (false);
	  }
	else
	  {
	  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]
	//NIE  XYZ[0-9]{7}[A-Za-z]
	//CIF  [A-Za-z][([0-9]{7}[A-za-z])([0-9]{8})]

	var esCIF = false;

	nif = nif.toUpperCase();
	
	if (nif.match(/[,.-]/)) { return -4; /* Carácteres inválidos */	}
	
	pos = nif.search(/\D{1}/);	

	// Los NIE empiezan por X,Y, ó Z
	if (pos == 0 && (nif.charAt(0) != 'X' && nif.charAt(0) != 'Y' && nif.charAt(0) != 'Z') )
	{
	
	  if (nif.length != 9)    { return -1; /* Longitud incorrecta */ }
		/**** CIF ****/
		esCIF = true;
  
		letra = nif.match(/^\D{1}/);
		numero = nif.match(/\d{7}/);
		control = nif.match(/\w{1}$/);
	}
	else
	{
		/**** NIF *****/
		esCIF = false;

		//Hay un caso especial de que si empieza por T, solo es necesario comprobar la longuitud de 8 caracteres
		//no tiene digito de control
		if ((nif.charAt(0) == 'X') || (nif.charAt(0) == 'Y') || (nif.charAt(0) == 'Z'))
		{
		  if (nif.length != 9)    { return -1; /* Longitud incorrecta */ }
		  
			numero = nif.match(/\d{7}/);			
		}		
		else
		{
		  if (nif.length != 9)    { return -1; /* Longitud incorrecta */ }
			numero = nif.match(/\d{8}/);
		}
		letra = nif.match(/\D{1}$/);
	}

	if (!numero || !letra) { return -2; /* Datos incorrectos */ }

	if (esCIF)
	{
		// **** CIF ****
		// La última se deja vacía a propósito, para que funcione bien si no encuentra ninguna		
		letras = ['A','B','C','D','E','F','G','H','J','K','L','M','N','P','Q','R','S','U','V',''];

		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!
		//TQP: 05/02/2010: Para cada comienzo de NIE se debe añadir un valor para el calculo del código de control.
		if (nif.charAt(0) == 'X')
			numero="0"+numero;
		if (nif.charAt(0) == 'Y')
			numero="1"+numero;
		if (nif.charAt(0) == 'Z')
			numero="2"+numero;
							
		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. El formato del NIF debe ser 00000000A.\n\nVerifique NIF y Nacionalidad');
			return (false);
			break;
		case -2:
			alert('El formato del NIF es incorrecto. El formato del NIF debe ser 00000000A.\n\nVerifique NIF y Nacionalidad');
			return (false);
			break;
		case -3:
			alert('Letra del NIF incorrecta.');
			return (false);
			break;
		case -4:
			alert('Carácteres inválidos. El formato del NIF debe ser 00000000A.');
			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 El formato del CIF debe ser A00000000.');
			return (false);
			break;
		case -2:
			alert('El formato del CIF es incorrecto.El formato del CIF debe ser A00000000.');
			return (false);
			break;
		case -3:
			alert('Letra del CIF incorrecta.');
			return (false);
			break;
		case -4:
			alert('Carácteres inválidos.El formato del CIF debe ser A00000000.');
			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_NIE(frm)
	El NIE es la letra "X" + NIF = "X44850268"	
	Comprobamos que la primera letra sea X. en ese caso comprobamos si el resto es un NIF.
	Llama a comprobarNIF y interpreta los resultados
*/
function comprueba_NIE(frm)
{
	longitud = frm.NIF.value.length;
	x = frm.NIF.value.substring(0,1);
	NIF = frm.NIF.value.substring(1,longitud);
	x = x.toUpperCase();	
	if (x=="X" || x=="Y" || x=="Z")
	{
		result = comprobarNIF(frm.NIF.value);
		switch(result)
		{
			case -1:
				alert('Longitud del NIE incorrecta. El formato del NIE debe ser X00000000A o Y00000000A.\n\nVerifique NIE y Nacionalidad');
				return (false);
				break;
			case -2:
				alert('El formato del NIE es incorrecto. El formato del NIE debe ser X00000000A o Y00000000A.\n\nVerifique NIE y Nacionalidad');
				return (false);
				break;
			case -3:
				alert('Letra del NIE incorrecta.');
				return (false);
				break;
			case -4:
				alert('Carácteres inválidos. El formato del NIE debe ser X00000000A o Y00000000A.');
				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);
		}
	}
	else //el primer caracter no es X
	{
		alert('El formato del NIE es incorrecto. El formato del NIE debe ser X00000000A o Y00000000A.\n\nVerifique NIF/NIE y Nacionalidad');
		return (false);
	}
}




function existeNIF(strNIFBD, IdUsuarioActual)
{
	var result = existeNIFExtendida(strNIFBD, IdUsuarioActual);

	switch(result)
	{
		case -1: // Error normal
			alert('El NIF introducido pertenece a otro usuario. No se pueden tener dos usuarios con un mismo NIF. Si ya ha realizado algún curso, identifíquese a través del cajetín de identificación que queda a su izquierda.');
			return (true);
			break;
		case -2: // Falla respuesta
			alert('Error interno. La respuesta del servidor ha sido incorrecta. Póngase en contacto con el administrador indicando hora de acceso y navegador utilizado.');
			return (true);
			break;
		case -3: // Falla XMLHttp
			alert('Error interno 2. No se ha podido comprobar la existencia de su NIF. Póngase en contacto con el administrador indicando hora de acceso y navegador utilizado.');
			return (true);
			break;
		case -4: // NIF vacío
			alert('El NIF introducido no puede estar vacío'); // Este caso no se debería producir
			return (true);
			break;
		case 1:
			return (false);
	}
}


function existeNIFExtendida(strNIFBD, IdUsuarioActual)
{
	if (strNIFBD != '')
	{
		xmlhttp = cargarXMLhttp();
		if(xmlhttp)
		{
			pagina = '/AdaptingSystem/include/compruebaNIF.asp?NIF=' + strNIFBD + '&IdUsuarioActual=' + IdUsuarioActual;
			xmlhttp.open("GET", pagina, false);
			xmlhttp.send(null);
			if (xmlhttp.responseText == "0")
			{
				return (1); // No existe, éxito!
			}
			else if (xmlhttp.responseText == "1")
			{
				return (-1); // Ya existe NIF para el usuario
			}
			else
			{
				return (-2); // Respuesta incorrecta
			}
		}
		else
		{
			return (-3); // No se puede cargar XMLHttp
		}
	}
	else {
		return (-4); // No se ha indicado NIF
	}
}


function cargarXMLhttp()
{
	var xmlhttp = false;

	try {
		xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
	} catch (e) {
		try {
			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		} catch (E) {
			xmlhttp = false;
		}
	}

	if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
		xmlhttp = new XMLHttpRequest();
	}
	
	return xmlhttp
}

/*
 * Función que pasado un nombre comprueba si sirve como nombre de archivo o carpeta
 * de Windows (no puede contener los siguientes caracteres: \ / : * ? \" < > | ni punto al final)
 *
 * El punto final Windows lo machaca directamente sin decir nada, para el resto muestra
 * un mensaje. Nosotros mostraremos mensaje para todo opción no posible.
*/
function comprobarNombreFichero(nombre)
{
	// Caracter prohibido
	if (nombre.match(/[/:*?""<>|\\]/)) return false;

	// Puntos al princpio y al final
	if (nombre.match(/^\.+.*$/)) return false;
	if (nombre.match(/^.*\.+$/)) return false;
	return true;
}
