//Declaracion de variables
var RE_CADENA = /[a-zA-Z0-9_ñÑ]+/;
var RE_CADENA_6 = /[a-zA-Z0-9_ñÑ]{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,4})+$/;
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|.JPG|.jpeg|.JPEG|.gif|.GIF|.wbmp|.WBMP)$/;
var RE_VIDEO = /^.+(.flv|.FLV|.SWF|.swf)$/;
var RE_ERROR = /^kkpp~~ll00ssmmQQ;;ººhhuu__99ii##bb@@ññ__11$/;
var RE_ESCAPE = /^^[0-9a-zA-Z]$/;
var RE_TLF = /^[\d\s]{9,}$/;
var RE_SELECT = /^[1-9a-zA-Z]+[0-9a-zA-Z]*$/;

//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) {
			showInfErr();
		if (campo.type != null){
			campo.style.background='#ff0000';
			campo.style.color='#fff';
		}
			campo.focus();
			//campo.select();
			
	} else {
		if (campo.type != null){
			campo.style.background = "#fff";
			campo.style.color='#000';
		}
	}
	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++) {
		if (aCampos[i] != undefined)
			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;
}

function validateCamposMini(cLogin, cPass) {
	var hayErrores = !validateCampo(cPass, RE_CADENA_6);
	hayErrores |= !validateCampo(cLogin, RE_CADENA_6);
	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" || campo.name == "previa") && RE_VIDEO.test(campo.value)) || (/^(PDF)([a-zA-Z0-9]*)$/.test(campo.name));
	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
//funcion que oculta los mensajes de información anteriores si los hay.//
function showInfErr(){
	if (document.getElementById("errFormulario") != null)
		document.getElementById("errFormulario").style.display = "block";
		
	if (document.getElementById("errorCorrecto") != null)
		document.getElementById("errorCorrecto").style.display = "none";
	
	if (document.getElementById("errorExist") != null)
		document.getElementById("errorExist").style.display = "none";		
}
