/***** ROLLOVER SENCILLO QE TE CAGAS *****/
//en la imagen --> onmouseover="this.src=Imagenes[0].src;" onmouseout="this.src=Imagenes[1].src;"
//en onLoad de <body> -->onLoad="Precargar('rutarelativa/imagen-ON', 'rutarelativa/imagen-OFF')"


Imagenes = new Array();
function Precargar() {
	
  for (var i=0; i<Precargar.arguments.length; i++) {    
    Imagenes[i]=new Image; 
    Imagenes[i].src=Precargar.arguments[i];
  }
}


/*******************************************************************************************************/


/***** VALIDADOR DE CONTENIDO DE FORMULARIOS *****/
//en <form>, añadir el siguiente comportamiento:  
//	onSubmit="return formCheck(this, 'mensaje', '\'campo-1\', \'campo-n\'', '\'Nombre-1\', \'Nombre-N\'' );">
//en el JS, 
function formCheck(formobj, mensaje, campos, nombresdecampo){
	// name of mandatory fields
	var fieldRequired = eval("Array("+campos+")");
	// field description to appear in the dialog box
	var fieldDescription = eval("Array("+nombresdecampo+")");
	// dialog message
	var alertMsg = mensaje+"\n";
	
	
	var l_Msg = alertMsg.length;
	
	for (var i = 0; i < fieldRequired.length; i++){
		var obj = formobj.elements[fieldRequired[i]];
		if (obj){
			if (obj.type == null){
				var blnchecked = false;
				for (var j = 0; j < obj.length; j++){
					if (obj[j].checked){
						blnchecked = true;
					}
				}
				if (!blnchecked){
					alertMsg += " - " + fieldDescription[i] + "\n";
				}
				continue;
			}

			switch(obj.type){
			case "select-one":
				if (obj.selectedIndex == -1 || obj.options[obj.selectedIndex].text == ""){
					alertMsg += " - " + fieldDescription[i] + "\n";
				}
				break;
			case "select-multiple":
				if (obj.selectedIndex == -1){
					alertMsg += " - " + fieldDescription[i] + "\n";
				}
				break;
			case "text":
			case "textarea":
				if (obj.value == "" || obj.value == null){
					alertMsg += " - " + fieldDescription[i] + "\n";
				}
				break;
			default:
			}
		}
	}

	if (alertMsg.length == l_Msg){
		return true;
	}else{
		alert(alertMsg);
		return false;
	}
}


/**** Validación de Formularios Genérica ****/
// Generic Form Validation
// Jacob Hage (jacob@hage.dk)
var checkObjects	= new Array();
var errors		= "";
var returnVal		= false;
var language		= new Array();
language["header"]	= "Los siguientes datos son obligatorios:"
language["start"]	= "->";
language["field"]	= " Campo ";
language["require"]	= " requerido";
language["min"]		= " y debe contener al menos ";
language["max"]		= " y no debe contener más de ";
language["minmax"]	= " y no más de ";
language["chars"]	= " caracteres";
language["num"]		= " y debe contener un número";
language["email"]	= " debe contener un correo válido";
// -----------------------------------------------------------------------------
// define - Call this function in the beginning of the page. I.e. onLoad.
// n = name of the input field (Required)
// type= string, num, email (Required)
// min = the value must have at least [min] characters (Optional)
// max = the value must have maximum [max] characters (Optional)
// d = (Optional)
// -----------------------------------------------------------------------------
function define(n, type, HTMLname, min, max, d) {
var p;
var i;
var x;
if (!d) d = document;
if ((p=n.indexOf("?"))>0&&parent.frames.length) {
d = parent.frames[n.substring(p+1)].document;
n = n.substring(0,p);
}
if (!(x = d[n]) && d.all) x = d.all[n];
for (i = 0; !x && i < d.forms.length; i++) {
x = d.forms[i][n];
}
for (i = 0; !x && d.layers && i < d.layers.length; i++) {
x = define(n, type, HTMLname, min, max, d.layers[i].document);
return x;       
}
eval("V_"+n+" = new formResult(x, type, HTMLname, min, max);");
checkObjects[eval(checkObjects.length)] = eval("V_"+n);
}
function formResult(form, type, HTMLname, min, max) {
this.form = form;
this.type = type;
this.HTMLname = HTMLname;
this.min  = min;
this.max  = max;
}
function validate() {
if (checkObjects.length > 0) {
errorObject = "";
for (i = 0; i < checkObjects.length; i++) {
validateObject = new Object();
validateObject.form = checkObjects[i].form;
validateObject.HTMLname = checkObjects[i].HTMLname;
validateObject.val = checkObjects[i].form.value;
validateObject.len = checkObjects[i].form.value.length;
validateObject.min = checkObjects[i].min;
validateObject.max = checkObjects[i].max;
validateObject.type = checkObjects[i].type;
if (validateObject.type == "num" || validateObject.type == "string") {
if ((validateObject.type == "num" && validateObject.len <= 0) || (validateObject.type == "num" && isNaN(validateObject.val))) { errors += language['start'] + language['field'] + validateObject.HTMLname + language['require'] + language['num'] + "\n";
} else if (validateObject.min && validateObject.max && (validateObject.len < validateObject.min || validateObject.len > validateObject.max)) { errors += language['start'] + language['field'] + validateObject.HTMLname + language['require'] + language['min'] + validateObject.min + language['minmax'] + validateObject.max+language['chars'] + "\n";
} else if (validateObject.min && !validateObject.max && (validateObject.len < validateObject.min)) { errors += language['start'] + language['field'] + validateObject.HTMLname + language['require'] + language['min'] + validateObject.min + language['chars'] + "\n";
} else if (validateObject.max && !validateObject.min &&(validateObject.len > validateObject.max)) { errors += language['start'] + language['field'] + validateObject.HTMLname + language['require'] + language['max'] + validateObject.max + language['chars'] + "\n";
} else if (!validateObject.min && !validateObject.max && validateObject.len <= 0) { errors += language['start'] + language['field'] + validateObject.HTMLname + language['require'] + "\n";
   }
} else if(validateObject.type == "email") {
// Checking existense of "@" and ".". 
// Length of must >= 5 and the "." must 
// not directly precede or follow the "@"
if ((validateObject.val.indexOf("@") == -1) || (validateObject.val.charAt(0) == ".") || (validateObject.val.charAt(0) == "@") || (validateObject.len < 6) || (validateObject.val.indexOf(".") == -1) || (validateObject.val.charAt(validateObject.val.indexOf("@")+1) == ".") || (validateObject.val.charAt(validateObject.val.indexOf("@")-1) == ".")) { errors += language['start'] + language['field'] + validateObject.HTMLname + language['email'] + "\n"; }
      }
   }
}
if (errors) {
alert(language["header"].concat("\n" + errors));
errors = "";
returnVal = false;
} else {
returnVal = true;
   }
}


/*****		FAVORITOS y PÁGINA DE INICIO		*****/
function a_favoritos()
{
	window.external.AddFavorite('http://www.guadalhorceturismo.com','Guadalhorce Turismo');
}

/***** popups *****/
// popups de imágenes de las galerías
function popup(ruta_base, id_imagen)
{
	//var features = "width=" + ancho + ", height=600";
	var features = "toolbar=no, location=no";
	
	nueva = window.open(ruta_base + "admin/contenidos/ver_imagen.php?id=" + id_imagen, "imagen", features);
	nueva.focus();
}

// popups de imágenes de la galería
function popup_galeria(ruta_base, ancho, id_imagen)
{
	var features = "width=" + ancho + ", height=600";
	
	nueva = window.open(ruta_base + "admin/catalogo/ver_producto.php?id=" + id_imagen, "imagen", features);
	nueva.focus();
}

// popup genérico
function g_popup(url)
{
	window.open(url,"","width=617,height=400,scrollbars");
}

/***** manejo de fechas en listas desplegables *****/
/**
* definimos las variables que almacenaran los componentes de la fecha actual
*/
ahora		= new Date();
ahoraDay	= ahora.getDate();
ahoraMonth	= ahora.getMonth();
ahoraYear	= ahora.getYear();

/**
* Nestcape Navigator 4x cuenta el anyo a partir de 1900, por lo que es necesario
* sumarle esa cantidad para obtener el anyo actual adecuadamente
**/
if (ahoraYear < 2000)
	ahoraYear += 1900;

/**
* funcion para saber cuantos dias tiene cada mes
*/
function cuantosDias(mes, anyo)
{
	var cuantosDias = 31;
	
	if (mes == "Abril" || mes == "Junio" || mes == "Septiembre" || mes == "Noviembre")
		cuantosDias = 30;
	if (mes == "Febrero" && (anyo/4) != Math.floor(anyo/4))
		cuantosDias = 28;
	if (mes == "Febrero" && (anyo/4) == Math.floor(anyo/4))
		cuantosDias = 29;
	
	return cuantosDias;
}

/**
* una vez que sabemos cuantos dias tiene cada mes
* asignamos dinamicamente este numero al combo de los dias dependiendo
* del mes que aparezca en el combo de los meses
*/
function asignaDias()
{
	comboDias = document.fReservas.seleccionaDia;
	comboMeses = document.fReservas.seleccionaMes;
	comboAnyos = document.fReservas.seleccionaAnyo;
	
	Month = comboMeses[comboMeses.selectedIndex].text;
	Year = comboAnyos[comboAnyos.selectedIndex].text;
	
	diasEnMes = cuantosDias(Month, Year);
	diasAhora = comboDias.length;
	
	if (diasAhora > diasEnMes)
	{
		for (i=0; i<(diasAhora-diasEnMes); i++)
		{
			comboDias.options[comboDias.options.length - 1] = null
		}
	}
	if (diasEnMes > diasAhora)
	{
		for (i=0; i<(diasEnMes-diasAhora); i++)
		{
			sumaOpcion = new Option(comboDias.options.length + 1);
			comboDias.options[comboDias.options.length]=sumaOpcion;
		}
	}
	if (comboDias.selectedIndex < 0)
		comboDias.selectedIndex = 0;
}

/**
* ahora selecionamos en los combos los valores correspondientes
* a la fecha actual del sistema
*/
function ponDia()
{
	comboDias = eval("document.fReservas.seleccionaDia");
	comboMeses = eval("document.fReservas.seleccionaMes");
	comboAnyos = eval("document.fReservas.seleccionaAnyo");
	/*comboDias = document.getElementById('seleccionaDia');
	comboMeses = document.getElementById('seleccionaMes');
	comboAnyos = document.getElementById('seleccionaAnyo');*/
	
	comboAnyos[0].selected = true;
	comboMeses[ahoraMonth].selected = true;
	
	asignaDias();
	
	comboDias[ahoraDay-1].selected = true;
}

/**
* esta funcion crea dinamicamente el combo de los anyos, empezando
* por el actual y acabando por el actual+masAnyos
*/
function rellenaAnyos(masAnyos)
{
	cadena = "";
	
	for (i=0; i<masAnyos; i++)
	{
		cadena += "<option>";
		cadena += ahoraYear + i;
	}
	return cadena;
}

/***** confirmación para enviar un formulario *****/
function enviar(formulario, mensaje)
{
	r = confirm(mensaje);
	if( r )
		eval("document." + formulario + ".submit();");
}

/***** confirmación para ir a url *****/
function ir(direccion, mensaje)
{
	r = confirm(mensaje);
	if( r )
		window.location.href = direccion;
}

/* funciones para escribir la hora y la fecha */
function escribir_fecha()
{
	fecha = new Date();
	dia = fecha.getDate();
	mes = fecha.getMonth();
	document.writeln( dia + "/" + (mes + 1) );
}

function escribir_hora()
{
	fecha = new Date();
	horas = fecha.getHours();
	minutos = fecha.getMinutes();
	document.writeln( horas + ":" + minutos );
}

/* función para determinar la estación */
function devolver_estacion(ruta_imagenes)
{
	var a_estaciones = Array("primavera", "verano", "otoño", "invierno");
	var fecha = new Date();
	mes = fecha.getMonth(); // el mes empieza en 0
	
	// elementos
	icono = "";
	alt_text = "";
	
	switch( mes )
	{
		case 0: // invierno
		case 1:
		case 11:
			icono = "invierno.gif";
			alt_text = a_estaciones[3];
			break;
		
		case 2: // primavera
		case 3:
		case 4:
			icono = "primavera.gif";
			alt_text = a_estaciones[0];
			break;
		
		case 5: // verano
		case 6:
		case 7:
			icono = "verano.gif"
			alt_text = a_estaciones[1];
			break;
		
		case 8: // otoño
		case 9:
		case 10:
			icono = "otono.gif";
			alt_text = a_estaciones[2];
			break;
	}
	
	document.write("<img border='0' width='22' height='22' src='" + ruta_imagenes + icono + "' alt='" + alt_text + "' title='" + alt_text + "'>");
	
}