// ----------------------------------------------------------------
// clase ToggleSelect
// __________________________
// argumentos:    id_select  -  id del elemento select
//              opciones  -  array asociativo con el siguiente par [varlor_option, id_div]
// ----------------------------------------------------------------


// Popup
function openWindow(theURL,winName,features) {
  window.open(theURL,winName,features);
}


var ToggleSelect = Class.create();

ToggleSelect.prototype = {
  
  initialize: function (id_select, options) {
                this.id_select = id_select;
                this._options = options;
                Event.observe (this.id_select, 'change', this.actua.bindAsEventListener (this), true);
                this.actua ();
            },

  actua:      function (e) {
              var seleccionada = $F(this.id_select);
              var div_seleccionado = false;
              for (var a = 0 ; a < this._options.length ; a++)
              {
                if (this._options[a][0] == seleccionada) {
                  div_seleccionado = this._options[a][1];
                }
                style = this._options[a][0] == seleccionada || div_seleccionado == this._options[a][1] ? 'block' : 'none';
                if ($(this._options[a][1]))
                  $(this._options[a][1]).style.display = style;  
              }
            }
};  

// JavaScript Document

function validaForm(f) {
	
	if ( $F('nombre') == "" ) {
		alert("El nombre es obligatorio.")
		f.Nombre.focus()
		return false
	}
	
	if ( $F('nombre') == "" ) {
		alert("Los apellidos son obligatorios.")
		f.Apellidos.focus()
		return false
	}
	
	if ( f.Direccion.value == "" ) {
		alert("La dirección es obligatoria.")
		f.Direccion.focus()
		return false
	}
	
	if ( f.Localidad.value == "" ) {
		alert("La localidad es obligatoria.")
		f.Localidad.focus()
		return false
	}	
	
	
	if ( f.Provincia.value == "" ) {
		alert("La provincia o el país es obligatoria.")
		f.Provincia.focus()
		return false
	} 
	
	if ( f.Cp.value == "" ) {
		alert("El código postal es obligatorio.")
		f.Cp.focus()
		return false
	} else {
		if ( f.Cp.value.length < 5 || isNaN(f.Cp.value) || 
	     	 f.Cp.value.substring(0,2) < 1 || f.Cp.value.substring(0,2) > 52 ) {
			alert("El código postal no es correcto, deben ser números.")
			f.Cp.focus()
			return false
		}	 
	}
	
	//Comprueba que se introduzca uno de los dos los telefonos
	if(f.Telefono.value=="") {
		alert("El teléfono es obligatorio.")
		f.Telefono.focus()
		return false
	}
	
	if(f.Tipoalojamiento.value=="op_00") {
		alert("El tipo de alojamiento es obligatorio.")
		f.Tipoalojamiento.focus()
		return false
	}
	
	if ( f.Adultos.value == "" ) {
		alert("El Nº de Adultos es obligatorio.")
		f.Adultos.focus()
		return false
	} 
	
	if(f.Fechaentrada.value=="" )
    {
     alert("Debes introducir la fecha de entrada.")
     f.Fechaentrada.focus()
     return false;
    }
   
    if(f.Fechasalida.value=="" )
    {
     alert("Debes introducir la fecha de salida.")
     f.Fechasalida.focus()
     return false;
    }
		
	if(!isValidDate(f.Fechaentrada.value)) {
		f.Fechaentrada.focus()
		return false
	}
	
	if(!isValidDate(f.Fechasalida.value)) {
		f.Fechasalida.focus()
		return false
	}
	
	
	//Comprueba que se introduzcan los telefonos
		
	var tamTelf = 9
	if ( f.Telefono.value!="" && (isNaN(f.Telefono.value) || f.Telefono.value.length != tamTelf) ) {
		  alert("Por favor, escribe los " + tamTelf + " dígitos de tu teléfono fijo.")
		  f.Telefono.focus()
		  return false
	}
	

	if( f.Email.value.length == 0 || !validamail(f.Email.value) ) {
		alert("El e-mail parece incorrecto.");
	    f.Email.focus()
		return false
    }

    //if(f.TxtDiallegada.value=="" || f.TxtMesllegada.value=="" || f.TxtAnollegada.value=="" || !checkdata($fechallegada)){
	//	alert("Debes introducir unos datos correctos en la Fecha de Llegada")
	//	f.TxtDiallegada.focus()
	//	return false
	//}
	
			
	// Todo OK, enviamos el formulario
	return true
}


function validamail(email){

	// Mínimo de 5 caracteres
	if (email.length < 5)
		return false
		
	// Cadena de caracteres no permitidos
	var iChars = "+*|,\":<>[]{}`';()&$#% ";	
	
	// Primero comprobamos que en el email no haya algún 
	// caracter no permitido
	var eLength = email.length;	
	for (var i=0; i < eLength; i++)	{		
		if (iChars.indexOf(email.charAt(i)) != -1)
			return false
	}	
	
	// Comprobamos que la @ tenga algún caracter delante y alguno detrás
	var atIndex = email.lastIndexOf("@");	
	if(atIndex < 1 || (atIndex == eLength - 1))
		return false

	// Comprobamos que exista '.' a partir del cuarto carácter, pero
	// que no acabé en '.'
	var pIndex = email.lastIndexOf(".");	
	if(pIndex < 3 || (pIndex == eLength - 1))	
		return false;	

	// Por último, comprobamos que el punto esté detrás de la @
	if(atIndex > pIndex)	
		return false	

	return true
}


function isValidDate(dateStr) {
var datePat = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{2})$/;

var matchArray = dateStr.match(datePat); // is the format ok?
if (dateStr==""){
return true
}
if (matchArray == null) {
alert("El formato de la Fecha debe ser dd/mm/aa")
return false;
}
month = matchArray[3]; // parse date into variables
day = matchArray[1];
year = matchArray[4];
if (month < 1 || month > 12) { // check month range
alert("El mes debe estar entre 1 y 12.");
return false;
}
if (day < 1 || day > 31) {
alert("El Día debe estar entre 1 y 31.");
return false;
}
if ((month==4 || month==6 || month==9 || month==11) && day==31) {
alert("Este mes no tiene 31 días!")
return false
}
if (month == 2) { // check for february 29th
var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
if (day>29 || (day==29 && !isleap)) {
alert("Febrero " + year + " no tiene " + day + " dias!");
return false;
}
}
if (year < 07) {
alert("El año debe ser mayor o igual a 2007")
return false
}

var daynew = new Date();

/*if (year > daynew.getYear()) {
alert("La fecha no puede ser superior a la actual")
return false
}

if (month > (daynew.getMonth()+1) && year == daynew.getYear()) {
alert("La fecha no puede ser superior a la actual")
return false
}

if (day > (daynew.getDate()) && month == (daynew.getMonth()+1) && year == daynew.getYear()) {
alert("La fecha no puede ser superior a la actual")
return false
}
*/

return true; // date is valid
}

