/*//////////// MODULO GESTION ARCONET //////////////Arconet 2006 */

// VALIDA EL FORMULARIO DE REGISTRO
function LoginValidator(elform){
	if (elform.usuario.value==''){
		elform.usuario.focus(); alert('Introduzca su nombre de usuario'); return(false);}
	if (elform.clave.value==''){
		elform.clave.focus(); alert('Introduzca su clave'); return(false);}
	return(true);
}

function RecuperaValidator(elform){
	if (!EmailCorrecto(elform.adminemail.value)){
		elform.adminemail.focus();alert('Introduzca una direccion de email correcta.'); return(false);}
	return(true);
}

// VALIDA EL FORMULARIO DE REGISTRO
function ValidarAcceso(elform){
	if (elform.adminuser.value==''){
		elform.adminuser.focus(); alert('Introduzca su nombre de usuario'); return(false);}
	if (elform.adminpass.value==''){
		elform.adminpass.focus(); alert('Introduzca su clave'); return(false);}
	if (!EmailCorrecto(elform.adminemail.value)){
		elform.adminemail.focus();alert('Introduzca una direccion de email correcta.'); return(false);}
	return(true);
}


/************ INSERCION IMAGENES FORMULARIOS **********************************/
function VistaPrevia(imagen,source){
	if (source==''){
	document.images[imagen].src="../img/blank.gif";
	document.images[imagen].width=100;
	document.images[imagen].height=100;
	}else{
	document.images[imagen].src="file:///" + source;
	document.images[imagen].width=100;
	document.images[imagen].height=100;
	}
}

// Reinicia los campos de vista previa de imagen -----	
function LimpiarVistaPrevia(){VistaPrevia('foto0','');}
function LimpiarVistaPreviaId(nombre){VistaPrevia(nombre,'');}

// Reinicia los campos de vista previa de imagen -----	
function LimpiarVistaPrevia2(){
	VistaPrevia('fotopre1','');
	VistaPrevia('fotopre2','');
	VistaPrevia('fotopre3','');
}

// Llama al CFM que borrar el reg ------------------------
function Eliminar(ID,NOMBRE,TIPO){
var confirma = "¿ Confirma que desea eliminar el siguiente registro ? " + String.fromCharCode(13,13) + NOMBRE;
if (confirm(confirma)){location.href = TIPO + "_borra.cfm?selectos=" + ID;}
}

// CHEQUEA LA LONGITUD DEL TEXTAREA
function CheckText(objeto,tope){
var cadena = new String('');
if (objeto.value.length>tope){
	cadena = objeto.value.toString().replace(/\r/,'');
	cadena = cadena.toString().slice(0,parseInt(tope-1));
	objeto.value=cadena;}
}

function EsNumerico (valor) { return !(isNaN(valor)); }

// VALIDACION DEL FORMULARIO DE ALTA DE SERVICIOS
function ValidarServiciosAlta(elform){
var todok=true;
var msgerror='Los siguientes datos son obligatorios:\n\n';
if (elform.texto.value==""){msgerror+=' - Texto del servicio.\n';todok=false;}
if (!todok){alert(msgerror);return(false)} else {return(true)}
}

// VALIDACION DEL FORMULARIO DE ALTA DE DOCUMENTOS
function ValidarDocumentosAlta(elform){
var todok=true;
var msgerror='Los siguientes datos son obligatorios:\n\n';
if (elform.documento.value==""){msgerror+=' - Nombre del documento.\n';todok=false;}
if (elform.descripcion.value==""){msgerror+=' - Descripcion del documento.\n';todok=false;}
if (!todok){alert(msgerror);return(false)} else {return(true)}
}

// VALIDACION DEL FORMULARIO DE ALTA DE PLATAFORMAS
function ValidarPlataformasAlta(elform){
var todok=true;
var msgerror='Los siguientes datos son obligatorios:\n\n';
if (elform.texto.value==""){msgerror+=' - Texto de la plataforma.\n';todok=false;}
if (!todok){alert(msgerror);return(false)} else {return(true)}
}

// VALIDACION DEL FORMULARIO DE ALTA DE SUBVENCIONES
function ValidarSubvencionesAlta(elform){
var todok=true;
var msgerror='Los siguientes datos son obligatorios:\n\n';
if (elform.documento.value==""){msgerror+=' - Documento de la subvencion.\n';todok=false;}
if (!todok){alert(msgerror);return(false)} else {return(true)}
}

// VALIDACION DEL FORMULARIO DE ALTA DE NOTICIAS
function ValidarNoticiasAlta(elform){
var todok=true;
var msgerror='Los siguientes datos son obligatorios:\n\n';
if (elform.titulo.value==""){msgerror+=' - Titulo de la noticia.\n';todok=false;}
if (elform.cuerpo.value==""){msgerror+=' - Texto de la noticia.\n';todok=false;}
if (elform.fecha.value==""){msgerror+=' - Fecha de la noticia.\n';todok=false;}
if (document.getElementById('foto')){
	if (elform.foto.value.length > 0 && elform.foto.value.indexOf(".jpg",0) <= 0){msgerror+=' - El formato de la foto debe ser JPG.\n';todok=false;}
}
if (!checkDate(elform.fecha)){msgerror+=' - Formato de fecha incorrecto.\n';todok=false;}
if (!todok){alert(msgerror);return(false)} else {return(true)}
}
// VALIDACION DEL FORMULARIO DE ALTA DE CATEGORIAS NOTICIAS
function ValidarCatNoticias(elform){
var todok=true;
var msgerror='Los siguientes datos son obligatorios:\n\n';
if (elform.nombre.value==""){msgerror+=' - Nombre de la categoria.\n';todok=false;}
if (!todok){alert(msgerror);return(false)} else {return(true)}
}
// VALIDACION DEL FORMULARIO DE ALTA DE USUARIOS
function ValidarAltaUsuarios(elform){
var todok=true;
var msgerror='Los siguientes datos son obligatorios:\n\n';
if (elform.empresa.value==""){msgerror+=' - Nombre de la empresa.\n';todok=false;}
if (elform.usuario.value==""){msgerror+=' - Usuario.\n';todok=false;}
if (elform.clave.value==""){msgerror+=' - Clave.\n';todok=false;}
if (document.getElementById('idsector')){
	if (elform.idsector.selectedIndex==0 && elform.sector.value==''){msgerror+=' - Sector de actividad.\n';todok=false;}
} else {
	if (elform.sector.value==''){msgerror+=' - Sector de actividad.\n';todok=false;}
}
if (document.getElementById('foto')){
if (elform.foto.value.length > 0 && elform.foto.value.indexOf(".jpg",0) <= 0){msgerror+=' - El formato de la foto debe ser JPG.\n';todok=false;}
}
if (ExisteUsuario(elform.usuario.value)){msgerror+=' - El nombre de usuario ya existe.\n';todok=false;}
if (!todok){alert(msgerror);return(false)} else {return(true)}
}
// VALIDACION DEL FORMULARIO DE ALTA DE CATEGORIAS NOTICIAS
function ValidarSectores(elform){
var todok=true;
var msgerror='Los siguientes datos son obligatorios:\n\n';
if (elform.nombre.value==""){msgerror+=' - Nombre del sector.\n';todok=false;}
if (!todok){alert(msgerror);return(false)} else {return(true)}
}


// Comprueba que no exista el nombre de usuario. Codigo complementario CF:
// <CFQUERY NAME="sellogin" DATASOURCE="tarelausuario" SQL="SELECT usuario from usuarios WHERE usuario <> ''">
// var Ausers = [<cfoutput query="sellogin">"#usuario#",</cfoutput>"arconet"];
function ExisteLogin(nombre){
var i=0;
for (i=0;i<Ausers.length;i++){if (Ausers[i] == nombre){return(true)} }
	return(false);
}

// CONVIERTE CAMPO DE TEXTO A MAYUSCULAS
function Mayusculas(objetocad) {
cadena = objetocad.value.toUpperCase();
objetocad.value = cadena;
}

// Comprueba todos los checkbox ------------------------
function ValidaChecked(elform){
len=elform.elements.length;
var ninguno = true;
var i=0;
while ((i<len) && (ninguno) ) {
	if ((elform.elements[i].name=='selectos') && (elform.elements[i].checked)) ninguno = false;
	i++;
}
if (ninguno){alert('No ha seleccionado ninguno.');return(false)}
return(true)
}

// Activa-Desactiva todos los checkbox ------------------------
function CheckAll(elform){
	len=elform.elements.length;
	valor = elform.marca.checked;
	var i=0;
	for( i=0 ; i<len ; i++){
		if (elform.elements[i].name=='selectos'){elform.elements[i].checked= valor;}
	}
}



// Abre ventana para ver foto ------------------------
function OpenFoto(imagen,texto){
var codigo1='<html><head><title>Foto de ' + texto + '</title></head><body leftmargin=0 topmargin=0><table border=0 width="100%" height="92%"><tr><td width="100%" height="92%" align=center valign=middle bgcolor="white">';
var codigo2='</div></td></tr></table><div align=right style="background:silver"><input type=button value="cerrar" onclick="javascript:window.close()"></div></body></html>';
doctag = '<img src="' + imagen + '" border=0 style="border:1px solid silver"><div style="font-size:13px;font-family:arial,verdana,tahoma;padding-top:5px;color:white;">' + texto;
ventana=open("","IMAGEN","width=600,height=400,scrollbars=yes,resizable=yes,left=100,top=100,screenX=100,screenY=100");
ventana.document.write(codigo1);
ventana.document.write(doctag);
ventana.document.write(codigo2);
}

function VerFoto(foto,ancho,alto){
if (ancho == null) ancho=300;
if (alto == null) alto=200;
try{ ventana=open("foto.cfm?f="+foto,"FOTO","width="+ancho+",height="+alto+",scrollbars=yes,resizable=yes,left=200,top=200,screenX=200,screenY=200");
	} catch(e){alert(e)}
}


// Funciones para el chequeo del formato de fecha dd/mm/yyyy ----------------------
function isDigit(theDigit){ 
var digitArray = new Array('0','1','2','3','4','5','6','7','8','9'),j; 
for (j = 0; j < digitArray.length; j++)
		{if (theDigit == digitArray[j]); return true}
return false 
} 
/**********************************************************************/ 
function isPositiveInteger(theString){ 
var theData = new String(theString) 

if (!isDigit(theData.charAt(0))) 
	if (!(theData.charAt(0)== '+')) 
		return false 
		for (var i = 1; i < theData.length; i++) 
			if (!isDigit(theData.charAt(i))) 
			return false 
		return true 
}
/**********************************************************************/ 
function isDate(s,f){
var a1=s.split("/"); var a2=s.split("-"); var e=true; 
if ((a1.length!=3) && (a2.length!=3)){
		e=false;
	} else {
		if (a1.length==3) var na=a1; 
		if (a2.length==3) var na=a2; 
		if (isPositiveInteger(na[0]) && isPositiveInteger(na[1]) && isPositiveInteger(na[2])){
			if (f==1){
				var d=na[1],m=na[0];
			} else {
				var d=na[0],m=na[1];
			} 
		var y=na[2]; 
		if (((e) && (y<1000)||y.length>4)) e=false 
		if (e){ 
			v=new Date(m+"/"+d+"/"+y); 
			if (v.getMonth()!=m-1) 
			e=false;
			}
		} else { 
			e=false; 
		}
	}
return e 
} 
function checkDate(a){ 
var s=a.value; 
	if (isDate(s,0))	//dd/mm/yyyy format 
		//alert("El formato de fecha es valido"); 
		return true;
	else 
		//alert("El formato de fecha NO es valido"); 
		return false; 
}

// Funciones para el chequeo del formato del EMAIL ----------------------
function EmailCorrecto(email) {
caracNoValidos = " /:,;";
if(email=="") return false; // debe rellenarse
for(i=0;i<caracNoValidos.length; i++) {
// ¿hay algún carácter no válido ?
	caracMal = caracNoValidos.charAt(i);
	if(email.indexOf(caracMal,0) > -1){ alert('Hay caracteres no válidos en el campo Email');return false;}
	}
posArroba = email.indexOf("@",1); // debe haber una arroba
if(posArroba==-1) { alert('Debe haber una ARROBA en el campo Email');return false;}
if (email.indexOf("@",posArroba+1)!= -1){ alert('Hay más de una ARROBA en el campo Email');return false;}
// y sólo una arroba
posPunto = email.indexOf(".",posArroba);
if(posPunto == -1){ alert('Debe haber un PUNTO tras la ARROBA en el campo Email');return false;}
// y al menos un punto despues de la arroba
if (posPunto+3 > email.length){ alert('No es una dirección de email válida'); return false;}
// debe haber al menos 2 caracteres tras el punto
return true;
}


// Formatea un numero decimal ------------------------
// Sustituye el punto decimal por coma decimal
// El segundo parametro indica el numero de decimales
function FormatEuro(num,ce) {
	var cad=new String();
	num = num.toString().replace(/\,/,'.');
	num = num.toString().replace(/\$|\,/g,''); 
	pos=Math.pow(10,ce);
	if(isNaN(num)){return('Error')}
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*pos+0.50000000001);
	cents = num%pos;
	num = Math.floor(num/pos).toString();
	if(cents<10) cents = "0" + cents;
// PARA POENR PUNTUACION DE MILLAR
//	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
//	num = num.substring(0,num.length-(4*i+3))+'.'+ num.substring(num.length-(4*i+3));
	cad=((sign)?'':'-') + num.toString() + ((cents=="00")?'':',' +cents.toString());
	return cad;
}

// CHEQUEA LA LONGITUD DEL TEXTAREA
function CheckText(objeto,tope){
var cadena = new String('');
if (objeto.value.length>tope){
	cadena = objeto.value.toString().replace(/\r/,'');
	cadena = cadena.toString().slice(0,parseInt(tope-1));
	objeto.value=cadena;}
}

function CambiaDisplay(idobjeto){
var objeto = document.getElementById(idobjeto);
if (objeto=='[object]'){
if (objeto.style.display == ''){objeto.style.display = 'block';return false}
if (objeto.style.display == 'none'){objeto.style.display = 'block';return false}
if (objeto.style.display == 'block'){objeto.style.display = 'none';return false}
}
return(true)
} 

// VALIDACION DEL FORMULARIO DE ALTA DE OFERTAS
function ValidarOfertasAlta(elform){
var todok=true;
var msgerror='Los siguientes datos son obligatorios:\n\n';
if (elform.establecimiento.value==""){msgerror+=' - Establecimiento.\n';todok=false;}
if (elform.periodo.value==""){msgerror+=' - Periodo.\n';todok=false;}
if (elform.precio.value==""){msgerror+=' - Precio.\n';todok=false;}
if (!todok){alert(msgerror);return(false)} else {return(true)}
}

// VALIDACION DEL FORMULARIO DE JUNTA
function ValidarJunta(elform){
var todok=true;
var msgerror='Los siguientes datos son obligatorios:\n\n';
if (elform.nombre.value==""){msgerror+=' - Nombre.\n';todok=false;}
if (!todok){alert(msgerror);return(false)} else {return(true)}
}
