/*
	Funciones DHTML compatibles con el estándar DOM
*/
// Función para obtener el valor de un estilo dado el id del elemento
function getStyleById(id, style)
{
	var elm = document.getElementById(id);
	return getStyle(elm, style);
}
// Función para obtener el valor de un estilo dado el elemento
function getStyle(elm, style)
{
	if(typeof(document.defaultView) == 'object') return document.defaultView.getComputedStyle(elm, null).getPropertyValue(style);
	else if(elm.currentStyle) return elm.currentStyle[style];
}
// Función para establecer el valor de un estilo dado el id del elemento
function setStyleById(id, style, value)
{
	var elm = document.getElementById(id);
	setStyle(elm, style, value);
}
// Función para establecer el valor de un estilo dado el elemento
function setStyle(elm, style, value)
{
	elm.style[style] = value;
}
/*
	Funciones para Rollovers
*/
// Función para inicializar los rollovers
function RollInit()
{
	var imgs = document.getElementsByTagName('IMG');
	for(var i = 0; i != imgs.length; ++i) {
		if(/(\w+)ROLL$/.test(imgs[i].id)) {
			var roll_id = RegExp.$1;
			if(/(\w+)FOTO$/.test(roll_id)) {
				// ...
			} else {
				var elm = imgs[i];
				elm.img_over = new Image();
				elm.img_over.src = elm.src.replace(/(.gif|.jpg|.png)$/, '_over$1');
				elm.img_orig = new Image();
				elm.img_orig.src = elm.src;
				if(/(\w+)MENU$/.test(roll_id) || /(\w+)TIT$/.test(roll_id)) {
					elm.RollOver = RollOver;
					elm.RollOut = RollOut;
				} else {
					elm.onmouseover = RollOver;
					elm.onmouseout = RollOut;
				}
			}
		}
	}
}
// Función para hacer rollover de una imagen
function RollOver()
{
	this.src = this.img_over.src;
}
// Función para restaurar una imagen
function RollOut()
{
	this.src = this.img_orig.src;
}
/*
	Función para abrir una ventana. Puede recibir los siguientes parámetros:

	url	-> Página web que mostrará la ventana. Por defecto página en blanco. Ejemplo: 'aviso.phpl'.
	target	-> Ventana en la que se abrirá la url. Por defecto en una nueva ventana cada vez. Ejemplo: '_blank'.
	width	-> Ancho en píxeles de la ventana. Por defecto 250 píxeles. Ejemplo: 300
	height	-> Alto en píxeles de la ventana. Por defecto 250 píxeles. Ejemplo: 125
	left	-> Distancia en píxeles al borde izquierdo de la pantalla. Por defecto centrada horizontalmente. Ejemplo: 100
	top	-> Distancia en píxeles al borde superior de la pantalla. Por defecto centrada verticalmente. Ejemplo: 100
	resizable	-> Indica si el usuario puede modificar el tamaño de la ventana. Por defecto no. Ejemplo: 'yes' o true
		Valores posibles: 'yes', 'no', '1', '0', true, false.
	scrollbars	-> Indica si la ventana tendrá barras de scroll. Por defecto no. Ejemplo: 'no' o false
		Valores posibles: 'yes', 'no', '1', '0', true, false.

	Poner un parámetro a null o no pasarlo es lo mismo.

	Ejemplo:

	// Abrir aviso.phpl en una nueva ventana, con tamaño 250x125, centrada horizontalmente
	// pero a 100 píxeles del borde superior.

	AbrirVentana('aviso.php', '_blank', 250, 125, null, 100);
*/
function AbrirVentana(url, target, width, height, left, top, resizable, scrollbars)
{
	if(typeof(url) == 'undefined' || url == null) url = '';
	if(typeof(target) == 'undefined' || target == null) target = '';

	if(typeof(width) == 'undefined' || width == null) width = 275;
	if(typeof(height) == 'undefined' || height == null) height = 275;

	if(typeof(window.screen) == 'undefined') {
		var sw = 800;
		var sh = 600;
	} else {
		var sw = window.screen.width;
		var sh = window.screen.height;
	}

	if(typeof(left) == 'undefined' || left == null) left = Math.round(0.5 * (sw - width));
	if(typeof(top) == 'undefined' || top == null) top = Math.round(0.5 * (sh - height));

	if(typeof(resizable) == 'undefined' || resizable == 'no' || !resizable) resizable = 0;
	else resizable = 1;

	if(typeof(scrollbars) == 'undefined' || scrollbars == 'no' || !scrollbars) scrollbars = 0;
	else scrollbars = 1;

	var win = window.open(url, target, 'left=' + left + ',top=' + top + ',width=' + width + ',height=' + height + ',directories=0,location=0,menubar=0,resizable=' + resizable +',scrollbars=' + scrollbars + ',status=0,toolbar=0');
	win.focus();
}
/*
	Funciones auxiliares comúnmente usadas
*/
// Función para mostrar un elemento
function Muestra(id)
{
	setStyleById(id, 'visibility', 'inherit');
}
// Función para ocultar un elemento
function Oculta(id)
{
	setStyleById(id, 'visibility', 'hidden');
}
// Función para los combos que saltan a urls
function Saltar(elm)
{
	var url = elm[elm.selectedIndex].value;
	if(url == '') elm.selectedIndex = 0;
	else location.href = url;
}
/*
	Funciones para chequear un formulario
*/
// Función para comprobar el formato de una dirección de correo
function isEmail(str) {
	// are regular expressions supported?
	var supported = 0;
	if (window.RegExp) {
		var tempStr = "a";
		var tempReg = new RegExp(tempStr);
		if (tempReg.test(tempStr)) supported = 1;
	}
	if (!supported) return (str.indexOf(".") > 2) && (str.indexOf("@") > 0);
	var r1 = new RegExp("(@.*@)|(\\.\\.)|(@\\.)|(^\\.)");
	var r2 = new RegExp("^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$");
	//alert (!r1.test(str) && r2.test(str));
	return (!r1.test(str) && r2.test(str));
}
// Función para comprobar el formato de la fecha
function CheckDate(fecha){
	// formato de fecha: dia/mes/año (año >= 1970)
	if (fecha == "" || fecha == null) return(2);
	fecha_date = fecha.match(/^(\d+)\/(\d+)\/(\d+)$/);
	if (fecha_date == "" || fecha_date == null ) return(0);
	fecha_dia = Number(fecha_date[1]);
	fecha_mes = Number(fecha_date[2]);
	fecha_ano = Number(fecha_date[3]);
	if (isNaN(fecha_dia) || isNaN(fecha_mes) || isNaN(fecha_ano)) return(0);
	if (fecha_ano > 70 && fecha_ano <= 99 ) fecha_ano = fecha_ano + 1900
	if (fecha_ano < 1970 || fecha_ano > 9999) return(0);
	if (fecha_ano % 4 == 0) bisiesto = true; // año bisiesto
	else bisiesto = false;
	if (fecha_mes == 2) {
		if (!bisiesto) {
			if (fecha_dia > 28 || fecha_dia < 1) return (0);
		} else {
			if (fecha_dia > 29 || fecha_dia < 1) return (0);
		}
	} else if (fecha_mes==1 || fecha_mes==3 || fecha_mes==5 || fecha_mes==7 || fecha_mes==8 || fecha_mes==10 || fecha_mes==12) {
		if (fecha_dia > 31 || fecha_dia < 1) return (0);
	} else if (fecha_mes==9 || fecha_mes==4 || fecha_mes==6 || fecha_mes==11) {
		if (fecha_dia > 30 || fecha_dia < 1) return (0);
	} else return (0);
	return(1);
}

// Funciones para comprobar que un número de cuenta bancaria es "correcto"
function obtenerDigito(valor){
	valores = new Array(1, 2, 4, 8, 5, 10, 9, 7, 3, 6);
	control = 0;
	for (i=0; i<=9; i++)
		control += parseInt(valor.charAt(i)) * valores[i];
	control = 11 - (control % 11);
	if (control == 11) control = 0;
	else if (control == 10) control = 1;
	return control;
}

function numerico(valor){
	cad = valor.toString();
	for (var i=0; i<cad.length; i++) {
		var caracter = cad.charAt(i);
		if (caracter<"0" || caracter>"9")
			return false;
	}
	return true;
}

function validarcc(cc1,cc2,cc3,cc4) {
	if (cc1 == ""  || cc2 == "" || cc3 == "" || cc4 == "")
		return false;
	else {
		if (cc1.length != 4 || cc2.length != 4 || cc3.length != 2 || cc4.length != 10)
			return false;
		else {
			if (!numerico(cc1) || !numerico(cc2) || !numerico(cc3) || !numerico(cc4))
				return false;
			else {
				if (!(obtenerDigito("00" + cc1 + cc2) == parseInt(cc3.charAt(0))) || !(obtenerDigito(cc4) == parseInt(cc3.charAt(1))))
					return false;
				else
					return true;
			}
		}
	}
}

function buscar_profesor()
{
var obj = document.getElementById('form_buscar_profesor');
	if (obj.id_profesor.value == '' && obj.dni.value == '')
	{
		alert("Tiene que elegir un profesor en el desplegable o introducir un DNI para buscar a un profesor.");
		return;
	}
	obj.iniciales.value = '';
	obj.accion.value = 'buscar_profesor';
	obj.submit();
}

/*
*	Funciones AHAH
*	http://microformats.org/wiki/rest/ahah
*/
function ahah(url, target) {
	document.getElementById(target).innerHTML = 'procesando petición';
	if(window.XMLHttpRequest) {
		var req = new XMLHttpRequest();
	} else if(window.ActiveXObject) {
		var req = new ActiveXObject("Microsoft.XMLHTTP");
	}
	if(req) {
		req.onreadystatechange = function() { ahahDone(req, target); };
		req.open("GET", url, true);
		req.send(null);
	}
}
function ahahDone(req, target) {
	if(req.readyState == 4) {
		if(req.status == 200 || req.status == 304) {
			document.getElementById(target).innerHTML = req.responseText;
		} else {
			document.getElementById(target).innerHTML = "error:\n" + req.statusText;
		}
	}
}
/*
*	Prueba
*/
function livesearch_profesores(elm)
{
	ahah('buscar_profesor.php?iniciales=' + elm.value, 'combo_profesores');
}
function livesearch_entidades(elm)
{
	ahah('buscar_entidad.php?iniciales=' + elm.value, 'combo_entidades');
}