//Declaracion de variables
var RE_CADENA = /\w+/;
var RE_CADENA_6 = /\w{6,}/;
var RE_NUMERIC = /^\d+$/;
var RE_FLOAT = /^(\d)+(\.(\d)+)?$/;
var RE_HORA = /^((0|1|2)\d:(0|1|2|3|4|5)\d)$/;
var RE_FECHA = /^(0|1|2|3)\d\/(0|1)\d\/\d{4}$/;
var RE_EMAIL = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
var RE_NIF = /^[0-9]{8}[a-zA-Z]{1}$/;
var RE_CIF = /^[ABCDEFGHKLMNPQS]\d{7}[0-9,A-J]$/;
var RE_CP = /^\d{4,}$/;
var RE_URL = /^((ftp|http|https):\/\/)(www)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?$/;
var RE_IMAGEN = /^.+(.jpg|.jpeg|.gif|.wbmp)$/i;
var RE_VIDEO = /^.+(.flv)$/;
var RE_ERROR = /^kkpp~~ll00ssmmQQ;;ººhhuu__99ii##bb@@ññ__11$/;
var RE_ESCAPE = /^^[0-9a-zA-Z]$/;

//solo permite que se pulsen valores numericos en el campo
//ej: <input type="text" onkeypress="return onKeyPressNumbers(event);" />
function onKeyPressNumbers(e) {
	var key = window.event ? e.keyCode : e.which;
	var keychar = String.fromCharCode(key);
	return /\d/.test(keychar);
}

//solo permite introducir valores validos para un campo hora
function onKeyPressHour(e) {
	var key = window.event ? e.keyCode : e.which;
	var keychar = String.fromCharCode(key);
	return /\d|:/.test(keychar);
}

//solo permite introducir valores validos para un campo hora
function onKeyPressDate(e) {
	var key = window.event ? e.keyCode : e.which;
	var keychar = String.fromCharCode(key);
	return /\d|\//.test(keychar);
}

//limita el numero de caracteres de un componente
//ej1: <textarea onkeyup="return limitLength(this, 20);"></textarea>
function limitLength(obj, maxlength) {
	if (obj.value.length > maxlength)
		obj.value = obj.value.substring(0, maxlength)
}

//valida el campo pasado como parametro segun la ER asociada
function validateCampo(campo, eReg) {
	var err = !eReg.test(campo.value);
	if (err) {
		var errDiv = document.getElementById("errFormulario");
		if (errDiv != null) errDiv.style.display = "block";
		if (campo.type != null) campo.style.borderColor = "red";
		campo.focus();
		campo.select();
	} else {
		if (campo.type != null)
			campo.style.borderColor = "gray";
	}
	return !err;
}

//valida los campo de password de forma especifica
function validatePass(pass1, pass2) {
	if (pass1 != null && pass2 != null && (pass2.value == "" || pass1.value != pass2.value))
		return validateCampo(pass2, RE_ERROR);
	return true;
}

//valida los campos pasados como parametro segun sus expReg asociadas
//ej1: <form id="f" onSubmit="return validateCampos([f.num, f.hora, f.fecha], [/\d+/, /\d*/, /\d*/]);">
//ej2: <form id="f" onSubmit="return validateCampos([f.num, f.hora, f.fecha], [RE_NUMERIC, RE_HORA, RE_FECHA]);">
function validateCampos(aCampos, aRegExp) {
	var hayErrores = false;
	for (var i = 0; i < aCampos.length; i++) {
		hayErrores = !validateCampo(aCampos[i], aRegExp[i]) || hayErrores;
	}
	var pass1 = document.getElementById("password");
	var pass2 = document.getElementById("repassword");
	var campo_nif = document.getElementById("nif");
	var campo_cif = document.getElementById("cif");
	return !hayErrores && validatePass(pass1, pass2) && validateNif(campo_nif) /*&& validateCif(campo_cif)*/;
}

//valida el formato de los campos opcionales
function validateFormatos(aCampos, aRegExp) {
	var hayErrores = false;
	for (var i = 0; i < aCampos.length; i++) {
		if (aCampos[i].value.length > 0)
			hayErrores = !validateCampo(aCampos[i], aRegExp[i]) || hayErrores;
	}
	return !hayErrores;
}

//validaciones especiales para subida y borrado de ficheros (comprobacion de formatos)
function validaFichero(form, id, fich) {
	var campo = document.getElementById(id);
	var isFichero = ((campo.name == "imagen" || campo.name == "logo" || campo.name == "galeria") && RE_IMAGEN.test(campo.value)) || 
			(campo.name == "video" && RE_VIDEO.test(campo.value)) || (campo.name == "fichero");
	if (campo.value == "" || !isFichero) {
		alert("Formato de fichero incorrecto");
		return false;
	}
	form.fich.value = fich; //fichero serializado a subir
	return true;
}

function borrarElemento(form, fich) {
	if (!confirm(String.fromCharCode(191) + "Confirma que desea borrar este elemento?"))
		return false;
	form.accion.value = 3; //accion de borrado de ficheros
	form.fich.value = fich; //fichero serializado a subir
	form.onsubmit = '';
	form.submit();
	return true;
}
//***************************************************

/**
  * Checks/unchecks all options of a <select> element
  *
  * @param   string   the form name
  * @param   string   the element name
  * @param   boolean  whether to check or to uncheck the element
  *
  * @return  boolean  always true
  */
function setSelectOptions(the_form, the_select, do_check) {
    var selectObject = document.forms[the_form].elements[the_select];
    var selectCount  = selectObject.length;
    for (var i = 0; i < selectCount; i++)
        selectObject.options[i].selected = do_check;
}

/**
  * Checks/unchecks all boxes on a form
  *
  * @param   string   Checkbox group name
  * @param   boolean  whether to check or to uncheck the element
  * @return  boolean  always true
  */
function checkAll(oform, check) {
    for (i = 0; i < oform.length; i++) {
		if (oform[i].type == "checkbox") 
			oform[i].checked = check;
	}
}

/**
  * Checks/unchecks all boxes on a form, which name match with param grupo
  *
  * @param   string   Checkbox group name
  * @param   string   String match
  * @param   boolean  whether to check or to uncheck the element
  * @return  boolean  always true
  */
function checkAllGroup(oform, grupo, check) {
    for (i = 0; i < oform.length; i++) {
        if (oform[i].id.match(grupo))
			oform[i].checked = check;
	}
}

/**
  * Cambia la visibilidad del elemento pasado como parametro.
  */
function cambiarVisibilidad(aCamposId) {
	for (var i = 0; i < aCamposId.length; i++) {
		var campo = document.getElementById(aCamposId[i]);
		if (campo.style.display != "none")
			campo.style.display = "none";
		else
			campo.style.display = "block";
	}
}

/**
  * Generacion aleatoria de claves
  */
function getRandomNum(lbound, ubound) {
	return (Math.floor(Math.random() * (ubound - lbound)) + lbound);
}

function getRandomChar(number, lower, upper, other, extra) {
	var numberChars = "0123456789";
	var lowerChars = "abcdefghijklmnopqrstuvwxyz";
	var upperChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
	var otherChars = "`~!@#$%^&*()-_=+[{]}\\|;:'\",<.>/? ";
	var charSet = extra;
	if (number == true) charSet += numberChars;
	if (lower == true) charSet += lowerChars;
	if (upper == true) charSet += upperChars;
	if (other == true) charSet += otherChars;
	return charSet.charAt(getRandomNum(0, charSet.length));
}

function getPassword(number, lower, upper, other, length) {
	var rc = "";
	if (length > 0) {
		for (var idx = 1; idx < length; ++idx)
			rc += getRandomChar(number, lower, upper, other, "");
	}
	return rc;
}

function clearString(cadena) {
	return cadena.split(" ").join("");
}

//funcion para la validacion del nif
function validateNif(campo) {
	if (campo == null) return true;
	var texto = clearString(campo.value);
	var dni = texto.substring(0, texto.length-1);
	var let = texto.charAt(texto.length-1);
	if (!isNaN(let))
		return validateCampo(campo, RE_ERROR);
	else {
		cadena = "TRWAGMYFPDXBNJZSQVHLCKET";
		posicion = dni % 23;
		letra = cadena.substring(posicion,posicion+1);
		if (letra!=let.toUpperCase())
			return validateCampo(campo, RE_ERROR);
	}
	return true;
}

//funcion para la validacion del cif de una empresa
function validateCif(campo) {
	if (campo == null) return true;	
	var suma, ultima, unumero; 
	var uletra = new Array("J", "A", "B", "C", "D", "E", "F", "G", "H", "I"); 
	var par = 0;
	var non = 0;
	var letras = "ABCDEFGHKLMNPQS";
	var texto = clearString(campo.value);
	ultima = texto.toUpperCase().substr(8,1); 
	
	for (zz=2;zz<8;zz+=2) {
		par += parseInt(texto.charAt(zz));
	}
	for (zz=1;zz<9;zz+=2) {
		nn = 2*parseInt(texto.charAt(zz));
		if (nn > 9) nn = 1+(nn-10)
		non = non+nn;
	}
	parcial = par + non;
	control = (10 - ( parcial % 10));
	if (control==10) control=0;
	if ((ultima == control) || (ultima == uletra[control])) 
		return true;
	else 
		return validateCampo(campo, RE_ERROR);
}
//fin_validacion de cif nif
//validar campos únicos en el evento onchange para evitar error devuelto desde la base de datos
function validateUniqId (tabla,campo,valor){
	$.ajax({
			     type: "POST",
			     url: "privada/ajax/validateUniqId.php",
			     data: "tabla=" + tabla + "&campo=" + campo + "&valor=" + valor,
			     cache: false,
			     success: function(xml){
			     if($.browser.msie){
					var aux=new String(xml);
					var pos1 = aux.indexOf('<res_1>');
					var pos2 = aux.indexOf('</res_1>');
					respuesta = aux.substring(pos1+7, pos2);							 
			    }else{
			    		respuesta=$("res_1",xml).text();			    
				}			       
			     },
			     complete: function(msg){
			     	if(respuesta>0) validateCampo($("#" + campo), RE_ERROR);
			    }
	});
}
//fin añadidos 12/11/08
//devuelve un dato aleatorio en funcion de la hora actual

function aleatorio() {
	var miFecha = new Date();
	var datoURL = miFecha.getYear().toString() + miFecha.getMonth().toString() + miFecha.getDate().toString() + 
			miFecha.getHours().toString() + miFecha.getMinutes().toString() + miFecha.getSeconds().toString();
	return datoURL;
}

