// JavaScript Document
// Funciones comunes

function check_email (email) 
{
	// Por defecto, se entiende que la dirección de e-mail es correcta

	// 1 - Que la dirección contenga únicamente caracteres válidos
	allowed_chars = new Array ("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", ".", "@", "_", "-");
	for (i = 0; i < email.length; i++) 
	{
		comparations = 0;
		for (j = 0; j < allowed_chars.length; j++) 
		{
			if ((email.charAt (i) != allowed_chars [j]) && (email.charAt (i) != allowed_chars [j].toUpperCase()))
			{
				comparations++;
			} 
			else 
			{
				break;
			}
		}
		if (comparations == allowed_chars.length) 
		{
			return (false);
		}
	}
	delete allowed_chars;

	
	// 2 - Comprobación de uso de una única arroba
	count_arrobas = 0;
	for (i = 0; i < email.length; i++) 
	{
		if (email.charAt (i) == '@') 
		{
			count_arrobas++;
		}
	}
	if (count_arrobas != 1) 
	{
		return (false);
	}
	

	// 3 - Comprobación de dominios
	haypunto=false
	for (i = email.length-5; i < email.length-2; i++) 
	{
		if (email.charAt (i) == '.') 
		{
			haypunto=true;
		}
	}
	if (haypunto)
	{
		return (true);
	}
	else
	{
		return(false);
	}
}

function trim(texto)
{
	if (texto)
	{
		var longitud=texto.length;
		var i;
		var j;
		
		if (texto=="undefined")
		{
			return "";
		}
		for (i=0; i<longitud; i++){
			if (texto.substring(i,i+1)!==" "){
				break;
			}
		}
		for (j=longitud; j>0; j--){
			if (texto.substring(j-1,j)!==" "){
				break;
			}
		}
		if (j==0) {
			texto = "";
		}else{
			texto = texto.substring(i,j);
		}
		return texto;
	}
}

//Retorna: 1 = NIF ok, 2 = CIF ok, 3 = NIE ok, -1 = NIF error, -2 = CIF error, -3 = NIE error, 0 = ??? error
function valida_nif_cif_nie(a) 
{
	var temp=a.toUpperCase();
	var cadenadni="TRWAGMYFPDXBNJZSQVHLCKE";
 
	if (temp!==''){
		//si no tiene un formato valido devuelve error
		if ((!/^[A-Z]{1}[0-9]{7}[A-Z0-9]{1}$/.test(temp) && !/^[T]{1}[A-Z0-9]{8}$/.test(temp)) && !/^[0-9]{8}[A-Z]{1}$/.test(temp))
		{
			return 0;
		}
 
		//comprobacion de NIFs estandar
		if (/^[0-9]{8}[A-Z]{1}$/.test(temp))
		{
			posicion = a.substring(8,0) % 23;
			letra = cadenadni.charAt(posicion);
			var letradni=temp.charAt(8);
			if (letra == letradni)
			{
			   	return 1;
			}
			else
			{
				return -1;
			}
		}
 
		//algoritmo para comprobacion de codigos tipo CIF
		suma = parseInt(a[2])+parseInt(a[4])+parseInt(a[6]);
		for (i = 1; i < 8; i += 2)
		{
			temp1 = 2 * parseInt(a[i]);
			temp1 += '';
			temp1 = temp1.substring(0,1);
			temp2 = 2 * parseInt(a[i]);
			temp2 += '';
			temp2 = temp2.substring(1,2);
			if (temp2 == '')
			{
				temp2 = '0';
			}
 
			suma += (parseInt(temp1) + parseInt(temp2));
		}
		suma += '';
		n = 10 - parseInt(suma.substring(suma.length-1, suma.length));
 
		//comprobacion de NIFs especiales (se calculan como CIFs)
		if (/^[KLM]{1}/.test(temp))
		{
			if (a[8] == String.fromCharCode(64 + n))
			{
				return 1;
			}
			else
			{
				return -1;
			}
		}
 
		//comprobacion de CIFs
		if (/^[ABCDEFGHJNPQRSUVW]{1}/.test(temp))
		{
			temp = n + '';
			if (a[8] == String.fromCharCode(64 + n) || a[8] == parseInt(temp.substring(temp.length-1, temp.length)))
			{
				return 2;
			}
			else
			{
				return -2;
			}
		}
 
		//comprobacion de NIEs
		//T
		if (/^[T]{1}/.test(temp))
		{
			if (a[8] == /^[T]{1}[A-Z0-9]{8}$/.test(temp))
			{
				return 3;
			}
			else
			{
				return -3;
			}
		}
 
		//XYZ
		if (/^[XYZ]{1}/.test(temp))
		{
			pos = str_replace(['X', 'Y', 'Z'], ['0','1','2'], temp).substring(0, 8) % 23;
			if (a[8] == cadenadni.substring(pos, pos + 1))
			{
				return 3;
			}
			else
			{
				return -3;
			}
		}
	}
 
	return 0;
}

// Funciones específicas

function inscripcion()
{
	document.location.href="inscripcion.php";
}

function focoFormulario(campo, texto)
{
	var txtContenido="Introduzca " + texto;
	
	if (trim(campo.value)==txtContenido)
	{
		campo.value="";	
	}
}

function blurFormulario(campo, texto)
{
	var txtContenido="Introduzca " + texto;
	
	if (trim(campo.value)=="")
	{
		campo.value=txtContenido;	
	}	
}

function verImagen(img, ruta)
{
	$.ajax ({
		type: "GET",
		url: "includes/imagen.php",
		data: "img=" + img + "&ruta=" + ruta,
		async: true,
		dataType: "HTML",
		success: function(datos){
			$('#imagen').html(datos);
			$('#dialog').dialog({
			autoOpen: false,
			show: 'blind',
			hide: 'explode',
			modal: true, 
			width: (parseInt($('#width').val())+40),
			height: (parseInt($('#height').val())+70)
			});
			$('#dialog').dialog('open');
		},
		error: function(data, errortxt, objerror){
			alert("error");
		},
		timeout: 0
	});
}


function isDate(value) 
{ 
	if (typeof value == 'string') 
	{ 
		value = value.split('/'); 
		value = value.reverse(); 
	} 
	var d = parseInt(value.pop(), 10); 
	var m = parseInt(value.pop(), 10) - 1;
	var y = parseInt(value.pop()); 
	var date = new Date(y, m, d); 

	if((date.getFullYear() == y) && (date.getMonth() == m) && (date.getDate() == d) && y>1900 && y<2500)
	{ 
		if(d<10) 
				var d="0"+d; 
		var a=(m+1); 
		if(a<10) 
				var a="0"+a; 
		return (d+"/"+a+"/"+y) 
	} 
	else 
		return (''); 
}
function isHora(value) 
{ 
	if (value=="")
	{
		return ('');
	}
	var val1=value.substring(0,1)
	var val2=value.substring(1,2)
	var val3=value.substring(2,3)
	var val4=value.substring(3,4)
	var val5=value.substring(4,5)
	
	if (val1!="" && val2!="" && val3!="" && val4!="" && val5!="")
	{
		if (val1!="0" && val1!="1" && val1!="2")
		{
			return ('');	
		}
		if (IsNumeric(val2)==false || IsNumeric(val4)==false || IsNumeric(val5)==false)
		{
			return ('');
		}
		if (val3!=":")
		{
			return ('');
		}
		return (val1+val2+val3+val4+val5);
	}
	else
	{
		return ('');	
	}
} 


function IsNumeric(valor) 
{	
	if (valor==''){
		return true;	
	}
	if(valor=='') 
		return false; 
	var log=valor.length; 
	var sw="S"; 
	for (var x=0; x<log; x++) 
	{
		
		v1=valor.substr(x,1);
		if (x==0 && v1=="-"){
		}else{
			v2 = parseInt(v1);
			if (isNaN(v2)) 
			sw= "N";  
		}
		//Compruebo si es un valor numérico 
		
	} 
	if (sw=="S") 
		return true; 
	else 
		return false; 
}

function IsFloat(valor) 
{ 
	var nuevo="";
	if(valor=='') 
		return false;
	var log=valor.length; 
	var sw="S"; 
	for (var x=0; x<log; x++) 
	{ 
		v1=valor.substr(x,1);
		if (v1=="."){
			//alert(v1);
			v2=v1;
			nuevo=nuevo + v2;
		}else{
			if (v1==","){
				//alert(v1);
				v2=".";
				nuevo=nuevo + v2;
			}else{
				v2 = parseInt(v1);
				//alert(v2)
				nuevo=nuevo + v2;
				//Compruebo si es un valor numérico 
				if (isNaN(v2)) 
					sw= "N";
			}
		}
		
	} 
	if (sw=="S") 
		return nuevo; 
	else 
		return false;
}


function verErrorAjax(data, errortxt, obj)
{
	var start=data.responseText.search("<li>Tipo de error:<br>");
	alert("Se prudujo un error: " + data.responseText.substring(start, parseInt(start)+1000));
}


	function setCaretPosition(obj, pos)
	{ 
		 if(obj.createTextRange) { 
			/* Create a TextRange, set the internal pointer to
			   a specified position and show the cursor at this
			   position
			*/ 
			var range = obj.createTextRange(); 
			range.move("character", pos); 
			range.select(); 
		} else if(obj.selectionStart) { 
			/* Gecko is a little bit shorter on that. Simply
			   focus the element and set the selection to a
			   specified position
			*/ 
			obj.focus(); 
			obj.setSelectionRange(pos, pos); 
    } 
	} 	
	   
	function getCaret(el) { 
	  if (el.selectionStart) { 
		return el.selectionStart; 
	  } else if (document.selection) { 
		el.focus(); 
	
		var r = document.selection.createRange(); 
		if (r == null) { 
		  return 0; 
		} 
	
		var re = el.createTextRange(), 
			rc = re.duplicate(); 
		re.moveToBookmark(r.getBookmark()); 
		rc.setEndPoint('EndToStart', re); 
	
		return rc.text.length; 
	  }  
	  return 0; 
	}

