// JavaScript Document

//usuarios

function formulario_admin(formulario){
	var nombre= formulario.nombre.value;
		if (nombre == "")
	{
		alert ("Por favor, escriba un nombre");
		return false;
	}
	var password= formulario.pass1.value;
	var password2= formulario.pass2.value;
		if(password!=password2){
		alert ("La contraseña no coincide");
		return false;
	}
	window.location ='exito.php';
	return true;
	
}


//noticias

function noticias_BR()
{
	return  confirm ("Está a punto de borrar el registro.\n¿Desea continuar?");
}

function noticias_VF(formulario){
	var nombre = formulario.nombre.value;
	var foto = formulario.foto.value;
	var descripcion = formulario.descripcion.value;
	
	if ( nombre == "" )
	{
		alert ("Por favor, escriba el título de la noticia");
		return false;
	}
	
	if ( nombre == "" && foto == "" && descripcion == "")
	{
		alert ("Por favor, escriba el título de la noticia. \nAdemás, es recomendable incluir una imagen \n con la noticia y escribir el cuerpo de la noticia.");
		return false;
	}
	return true;

}


function erroresi(imagen, tamanio) {
			switch (imagen){
			case '1':alert (" el tamaño de la imagen no es el correcto (0 a 8 Mb)"+tamanio);break;
			case '2':alert ("No ha seleccionado un archivo de imagen válido");break;
			case '3':alert ("Error al subir el archivo");break;
			default:alert ("Error inesperado en la imagen, por favor vuelva a intentarlo");break;
			}
		}	
		
function erroresi2(archivo) {
			switch (archivo){
			case '1':alert (" el tamaño del archivo no es el correcto (0 a 1 Mb)");break;
			case '2':alert ("No ha seleccionado un archivo válido");break;
			case '3':alert ("Error al subir el archivo");break;
			default:alert ("Error inesperado en el archivo, por favor vuelva a intentarlo");break;
			}
		}	
		

function portfolio_BR()
{
	return  confirm ("Está a punto de borrar el registro.\n¿Desea continuar?");
}

function portfolio_VF(formulario){
	var nombre = formulario.nombre.value;
	var foto = formulario.foto.value;
	var descripcion = formulario.descripcion.value;
	if (nombre=="")
	{
		alert ("Por favor, escriba un nombre para la promoción");
		return false;
	}
	
	if ( nombre == "" && foto == "" && descripcion == "")
	{
		alert ("Por favor, escriba un nombre. \nAdemás, es recomendable incluir una imagen con \nla promoción (Logo empresa de tamaño nxn)\ny escribir el cuerpo de la noticia.");
		return false;
	}

	return true;

}

function ofertas_BR()
{
	return  confirm ("Está a punto de borrar el registro.\n¿Desea continuar?");
}

function ofertas_VF(formulario){
	var nombre = formulario.nombre.value;
	if (nombre=="")
	{
		alert ("Por favor, escriba el puesto de trabajo que se oferta");
		return false;
	}
	return true;

}


function productos_BR()
{
	return  confirm ("Está a punto de borrar el registro.\n¿Desea continuar?");
}

function trabajos_BR()
{
	return  confirm ("Está a punto de borrar el registro.\n¿Desea continuar?");
}

function descargas_VF(formulario){
	var nombre = formulario.nombre.value;
	var foto = formulario.archivo.value;
	var descripcion = formulario.descripcion.value;
	
	if ( nombre == "" )
	{
		alert ("Por favor, escriba el título de la noticia");
		return false;
	}
	
	if ( nombre == "" && archivo == "" && descripcion == "")
	{
		alert ("Por favor, escriba el nombre de la descarga. \nAdemás, es obligatorio incluir el fichero asociado \n escribir una descripcion.");
		return false;
	}
	return true;

}

//nuevos scripts arias
function dobleConfirmacion(mensaje){
	if (confirm(mensaje))
	{
		return  confirm('¿Está totalmente seguro de que quiere continuar?');
	}
	else return false;
}
/*
function dobleConfirmacionTipo(formObj){
	if (confirm('Está a punto de borrar el tipo de fichero, lo que conlleva también la eliminación de todos los ficheros asociados al mismo.\n\t\t\t\t\t\t\t¿Desea continuar?'))
	{
		return  confirm('¿Está totalmente seguro de que desea continuar?');
	}	
	else return false;
}

function dobleConfirmacionEmpleado(){
	if (confirm('Está a punto de borrar el empleado, lo que conlleva también la eliminación de los ficheros asociados al mismo.\n\t\t\t\t\t\t\t¿Desea continuar?'))
	{
		return  confirm('¿Está totalmente seguro de que quiere eliminar todos los datos del empleado?');
	}
	else return false;
}
*/
function CargarFoto(URL){
  /*derecha=(screen.width-ancho)/2;
  arriba=(screen.height-alto)/2;
  string="toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=1,width="+ancho+",height="+alto+",left="+derecha+",top="+arriba+"";
  fin=window.open(img,"",string);*/
  window.open(URL,"","left="+240+",top="+350+""); 
}

function MM_openBrWindow(theURL,winName,features) { //v2.0
  window.open(theURL,winName,features);
}

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function formulario_admin(formulario){
	var nombre= formulario.nombre.value;
		if (nombre == "")
	{
		alert ("Por favor, escriba un nombre");
		return false;
	}
	var password= formulario.pass1.value;
	var password2= formulario.pass2.value;
		if(password!=password2){
		alert ("La contraseña no coincide");
		return false;
	}
	window.location('exito.php');
	return true;
	
}

<!-- calendar ini
 var oldLink = null;
// code to change the active stylesheet
function setActiveStyleSheet(link, title) {
  var i, a, main;
  for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
    if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title")) {
      a.disabled = true;
      if(a.getAttribute("title") == title) a.disabled = false;
    }
  }
  if (oldLink) oldLink.style.fontWeight = 'normal';
  oldLink = link;
  link.style.fontWeight = 'bold';
  return false;
}

// This function gets called when the end-user clicks on some date.
function selected(cal, date) {
  cal.sel.value = date; // just update the date in the input field.
  if (cal.dateClicked && (cal.sel.id == "sel1" || cal.sel.id == "sel3"))
    // if we add this call we close the calendar on single-click.
    // just to exemplify both cases, we are using this only for the 1st
    // and the 3rd field, while 2nd and 4th will still require double-click.
    cal.callCloseHandler();
}

// And this gets called when the end-user clicks on the _selected_ date,
// or clicks on the "Close" button.  It just hides the calendar without
// destroying it.
function closeHandler(cal) {
  cal.hide();                        // hide the calendar
//  cal.destroy();
  _dynarch_popupCalendar = null;
}

// This function shows the calendar under the element having the given id.
// It takes care of catching "mousedown" signals on document and hiding the
// calendar if the click was outside.
function showCalendar(id, format, showsTime, showsOtherMonths) {
  var el = document.getElementById(id);
  if (_dynarch_popupCalendar != null) {
    // we already have some calendar created
    _dynarch_popupCalendar.hide();                 // so we hide it first.
  } else {
    // first-time call, create the calendar.
    var cal = new Calendar(1, null, selected, closeHandler);
    // uncomment the following line to hide the week numbers
    // cal.weekNumbers = false;
    if (typeof showsTime == "string") {
      cal.showsTime = true;
      cal.time24 = (showsTime == "24");
    }
    if (showsOtherMonths) {
      cal.showsOtherMonths = true;
    }
    _dynarch_popupCalendar = cal;                  // remember it in the global var
    cal.setRange(1900, 2070);        // min/max year allowed.
    cal.create();
  }
  _dynarch_popupCalendar.setDateFormat(format);    // set the specified date format
  _dynarch_popupCalendar.parseDate(el.value);      // try to parse the text in field
  _dynarch_popupCalendar.sel = el;                 // inform it what input field we use

  // the reference element that we pass to showAtElement is the button that
  // triggers the calendar.  In this example we align the calendar bottom-right
  // to the button.
  _dynarch_popupCalendar.showAtElement(el.nextSibling, "Br");        // show the calendar

  return false;
}

var MINUTE = 60 * 1000;
var HOUR = 60 * MINUTE;
var DAY = 24 * HOUR;
var WEEK = 7 * DAY;

// If this handler returns true then the "date" given as
// parameter will be disabled.  In this example we enable
// only days within a range of 10 days from the current
// date.
// You can use the functions date.getFullYear() -- returns the year
// as 4 digit number, date.getMonth() -- returns the month as 0..11,
// and date.getDate() -- returns the date of the month as 1..31, to
// make heavy calculations here.  However, beware that this function
// should be very fast, as it is called for each day in a month when
// the calendar is (re)constructed.
function isDisabled(date) {
  var today = new Date();
  return (Math.abs(date.getTime() - today.getTime()) / DAY) > 10;
}

function flatSelected(cal, date) {
  var el = document.getElementById("preview");
  el.innerHTML = date;
}

function showFlatCalendar() {
  var parent = document.getElementById("display");

  // construct a calendar giving only the "selected" handler.
  var cal = new Calendar(0, null, flatSelected);

  // hide week numbers
  cal.weekNumbers = false;

  // We want some dates to be disabled; see function isDisabled above
  cal.setDisabledHandler(isDisabled);
  cal.setDateFormat("%A, %B %e");

  // this call must be the last as it might use data initialized above; if
  // we specify a parent, as opposite to the "showCalendar" function above,
  // then we create a flat calendar -- not popup.  Hidden, though, but...
  cal.create(parent);

  // ... we can show it here.
  cal.show();
}
/**
Número de Campos Predefinidos: 6
Campos predefinidos Obligatorios:
	- nif: formato-> 47878878A
	- telefono1: formato-> numero de 15 cifras
	- nombre, apellido1, apellido2: formato -> cadena de letras no vacía de menos de 100 caracteres, sin números 
	- login: formato -> cadena de letras,números y caracteres "_ - . /" no vacías y de no mas de 50 caracteres
	- password: formato -> cadena de letras,números y caracteres "_ - . /" no vacías y de no mas de 32 caracteres
	- email: formatos 
	- titulo
	- descripcion
	- archivo 
	- tipo
**/
function compruebaCampos(formulario)
{
	
	var errores= new String("Los siguientes campos no son válidos:\n");
	var hayError=false;
	
	
	var numCampos= formulario.elements.length;
	
	
	for(i=0;i<numCampos;i++)
	{

	
			switch (formulario.elements[i].name) {
			  case 'nif' :
							var strLetras = 'TRWAGMYFPDXBNJZSQVHLCKE';
							var Letra;
							sNif=formulario.elements[i].valuetoUpperCase();
							if(sNif.length<9)
							{
								hayError=true;
								errores=errores+"dni - Número de caracteres inválido \n";
							}
							else
							{
								Letra=sNif.charAt(sNif.length-1);
								if(Letra<'A' || Letra>'Z')
								{
									hayError=true;
									errores=errores+"dni - La letra del dni es inválida \n";	
								}
								else
									Letra=strLetras.charAt((sNif.substr(0,sNif.length-1))%23);

								if(sNif.charAt(sNif.length-1)!=Letra)
								{
									hayError=true;
									errores=errores+"dni - Número de dni inválido \n";
								}
								
							}		
					break;
			  case 'telefono1' :
							var posibleTLF=new String(formulario.elements[i].value);
							if (posibleTLF=="" || posibleTLF==" "){
										hayError=true;
										errores=errores+"telefono1 -  este campo no puede ser vacío \n";		
							}	
					
							
					break;
			  case 'nombre' :	
			  			nombre=new String(formulario.elements[i].value);//nombre
						nombre=nombre.toUpperCase();
						
						//comprobamos que no sea vacío;
						if (nombre=="" || nombre==" "){
								hayError=true;
								errores=errores+"nombre -  este campo no puede ser vacío \n";		
							
						}
						else{
							//comprobamos que no tenga más de 100 caracteres
							if(nombre.length>100)
							{
								hayError=true;
								errores=errores+"nombre -  este campo no puede tener más de 100 caracteres \n";								
							}
							//comprobamos que no tenga numeros
							else{
								var continuar=true;
								var j=0;
								while (continuar && j<nombre.length)
								 {
									 //si no es una letra o espacio error
									if(!(nombre.charAt(j)>="A" && nombre.charAt(j)<="Z") && nombre.charAt(j)!=" " && nombre.charAt(j)!="-" && nombre.charAt(j)!="Á"&& nombre.charAt(j)!="É"&& nombre.charAt(j)!="Í"&& nombre.charAt(j)!="Ó"&& nombre.charAt(j)!="Ú"){
												hayError=true;
												errores=errores+"nombre -  contiene caracteres no válidos \n";		
												continuar = false;
									}
									j++;
								  }
								
							}
						}
		
					break;
			  case 'apellido1' :
			  			apellido1=new String(formulario.elements[i].value);//nombre
						apellido1=apellido1.toUpperCase();

						//comprobamos que no sea vacío;
						if (apellido1=="" || apellido1==" "){
								hayError=true;
								errores=errores+"apellido1 -  este campo no puede ser vacío \n";		
							
						}
						else{
							//comprobamos que no tenga más de 100 caracteres
							if(apellido1.length>100)
							{
								hayError=true;
								errores=errores+"apellido1 -  este campo no puede tener más de 100 caracteres\n";								
							}	
							//comprobamos que no tenga numeros
							else{
								var continuar=true;
								var j=0;
								while (continuar && j<apellido1.length)
								 {
									if(!(apellido1.charAt(j)>="A" && apellido1.charAt(j)<="Z") && apellido1.charAt(j)!=" " && apellido1.charAt(j)!="-" && apellido1.charAt(j)!="Á"&& apellido1.charAt(j)!="É"&& apellido1.charAt(j)!="Í"&& apellido1.charAt(j)!="Ó"&& apellido1.charAt(j)!="Ú" ){
												hayError=true;
												errores=errores+"apellido1 -  contiene caracteres no válidos \n";		
												continuar = false;
									}
									j++;
								  }//while
							
							}//else numeros
						}//else vacios
					  
		
					break;
			  case 'apellido2' :
			  			apellido2=new String(formulario.elements[i].value);//nombre
						apellido2=apellido2.toUpperCase();
						//comprobamos que no sea vacío;
						if (apellido2=="" || apellido2==" "){
								hayError=true;
								errores=errores+"apellido2 -  este campo no puede ser vacío \n";		
							
						}
						else{
							//comprobamos que no tenga más de 100 caracteres
							if(apellido2.length>100)
							{
								hayError=true;
								errores=errores+"apellido2 -  este campo no puede tener más de 100 caracteres \n";								
							}

							//comprobamos que no tenga numeros
							else{
								var continuar=true;
								var j=0;
								while (continuar && j<apellido2.length)
								 {
									if(!(apellido2.charAt(j)>="A" && apellido2.charAt(j)<="Z") && apellido2.charAt(j)!=" " && apellido2.charAt(j)!="-"&& apellido2.charAt(j)!="Á"&& apellido2.charAt(j)!="É"&& apellido2.charAt(j)!="Í"&& apellido2.charAt(j)!="Ó"&& apellido2.charAt(j)!="Ú" ){
												hayError=true;
												errores=errores+"apellido2 -  contiene caracteres no válidos \n";		
												continuar = false;
									}
									j++;
								  }//while
							
							}//else numeros
						}//else vacios
					break;
			  case 'email' :
						var filter=/^[A-Za-z][A-Za-z0-9_\-\.]*@[A-Za-z0-9_\-\.]+\.[A-Za-z0-9_\-.]+[A-za-z]$/;
						if (formulario.elements[i].value.length == 0 ){
								hayError=true;
								errores=errores+"email -  este campo no puede ser vacío \n";		
							
						}
						if (formulario.elements[i].value.length > 255 ){
								hayError=true;
								errores=errores+"email -  este campo no puede tener más de 255 caracteres \n";		
							
						}
						
						else{ 
								if (!(filter.test(formulario.elements[i].value))){
									hayError=true;
									errores=errores+"email -  direccion no reconocida \n";		
								}
							
						}

					break;
			  case 'login' :
			  			login=new String(formulario.elements[i].value);//nombre
						login=login.toUpperCase();
						//comprobamos que no sea vacío;
						if (login=="" || login==" "){
								hayError=true;
								errores=errores+"login -  este campo no puede ser vacío \n";		
							
						}
						else{
							//comprobamos que no tenga más de 50 caracteres
							if(login.length>50)
							{
								hayError=true;
								errores=errores+"login -  este campo no puede tener más de 50 caracteres \n";								
							}	
							var continuar=true;
							//comprobamos que tenga caracteres validos: numeros, letras, "-" , "_" , "/" , "." 							
							while (continuar && j<login.length){
								if(
								   !(login.charAt(j)>="A" && login.charAt(j)<="Z") && !(login.charAt(j)>="0" && login.charAt(j)<="9")  
									 && (login.charAt(j)!="-") && (login.charAt(j)!="_") && (login.charAt(j)!="/") && (login.charAt(j)!=".")
									
								   ){
											hayError=true;
											errores=errores+"login -  contiene caracteres no válidos \n";		
											continuar=false;
								}//if
								j++;
							}//while
						}//else
						
					break;					
			  case 'password' :
			  			password=new String(formulario.elements[i].value);//nombre
						password=password.toUpperCase();
						//comprobamos que no sea vacío;
						if (password=="" || password==" "){
								hayError=true;
								errores=errores+"password -  este campo no puede ser vacío \n";		
							
						}
						else{
							//comprobamos que no tenga más de 50 caracteres
							if(password.length>32)
							{
								hayError=true;
								errores=errores+"password -  este campo no puede tener más de 32 caracteres \n";								
							}	
							
							var continuar=true;
							//comprobamos que tenga caracteres validos: numeros, letras, "-" , "_" , "/" , "." 							
							while (continuar && j<password.length){
								
								if(
								  !(password.charAt(j)>="A" && password.charAt(j)<="Z") && !(password.charAt(j)>="0" && password.charAt(j)<="9")  
									 && (password.charAt(j)!="-") && (password.charAt(j)!="_") && (password.charAt(j)!="/") && (password.charAt(j)!=".")
									
								   ){
											hayError=true;
											errores=errores+"password -  contiene caracteres no válidos \n";		
											continuar=false;
								}//if
								j++;
							}//while
						}//else
						  
		
					break;					
			 case 'titulo' :	
							var titulo=new String(formulario.elements[i].value);
							if (titulo=="" || titulo==" "){
										hayError=true;
										errores=errores+"titulo -  este campo no puede ser vacío \n";		
							}	
							else 
								if(titulo.lenght>100){
								hayError=true;
								errores=errores+"titulo -  este campo no puede tener más de 100 caracteres \n";														
									
								}
							 
				break;		

			 case 'descripcion' :
							var descripcion=new String(formulario.elements[i].value);
							if (descripcion=="" || descripcion==" "){
										hayError=true;
										errores=errores+"descripcion -  este campo no puede ser vacío \n";		
							}	
								 
				break;	
			 case 'archivo' :
					var archivo=new String(formulario.elements[i].value);
					if (archivo=="" || archivo==" "){
								hayError=true;
								errores=errores+"archivo -  este campo no puede ser vacío \n";		
					}
					else
						if (archivo.length>200)
						{
								hayError=true;
								errores=errores+"archivo -  este campo no puede exceder de 200 caracteres \n";									
						}					
								 
				break;		
			 case 'tipo' :
					var tipo=new String(formulario.elements[i].value);
					if (tipo=="" || tipo==" "){
								hayError=true;
								errores=errores+"tipo -  este campo no puede ser vacío \n";		
					}
					else
						if (tipo.length>100)
						{
								hayError=true;
								errores=errores+"tipo -  este campo no puede exceder de 100 caracteres \n";									
						}
								 
				break;					

			default :
			  //comprobamos que no sean valores nulos
/*				  var campoi= formulario.elements[i];
				  if (campoi==" " || campoi==""){
							hayError=true;
							errores=errores+"No puede haber campos vacios\n";
				  }
//*/		
	
			}//switch
			
	
	}//for
	
	if (hayError){
		alert (errores);
		return false;
	}
	else 
		return true;	
}//function
