var processingAjax = false;

function selectHabitaciones(control, id)
{
	var numRooms = parseInt($F(control));

	var listItems = $(control).up('ul').childElements();

	if (numRooms > 0)
	{
		listItems[0].select('select','input').invoke('enable');
	}
	else
	{
		listItems[0].select('select','input').reject(function(el){return el.id.match(/^quantity/)}).invoke('disable');
		listItems[0].select('div.price').invoke('update', '<span>-</span>');
	}

	//
	for (var s = 1; s < listItems.length; s++)
	{
		if (s < 3*numRooms) // Son 3 li por habitación (habitación + extras + edades)
		{
			listItems[s].select('select','input').invoke('enable');
			listItems[s].id.match(/^rextras/) ? ( listItems[s].select('div').length == 0 ? listItems[s].hide() : listItems[s].show() ) : listItems[s].show();
		}
		else
		{
			listItems[s].hide();
			listItems[s].select('div[id^=el_]').invoke('remove');// Elimino selectores de edades
			listItems[s].select('select','input').invoke('disable');
			listItems[s].select('div.price').invoke('update', '<span>-</span>');
		}
	}

	for (var n = 0; n < numRooms; n++)
	{	//Actualizar las edades
		displayAge(id+"_"+n);
	}
}

function displayAge(idstr)
{
	//Limpiamos
	$$('li#ages_'+idstr+' div[id^=el_]').invoke('remove');
	$('ages_'+idstr).select('div').each(function(e){e.select('select[class="template"]')[0].disable()});

	ch = $('selectC_'+idstr);
	for(var i = 0; i < ch.value; i++)
	{
		var s = $('ages_'+idstr).select('div')[0].cloneNode(true);
		s.style.display = "block";
		s.select('select')[0].enable();
		s.id = 'el_'+idstr+"_"+i;
		$('ages_'+idstr).insert(s);
	}

	bb = $('selectB_'+idstr);
	for(var i = 0; i < bb.value; i++)
	{
		var s = $('ages_'+idstr).select('div')[1].cloneNode(true);
		s.style.display = "block";
		s.select('select')[0].enable();
		s.id = 'el_'+idstr+"_"+i;
		$('ages_'+idstr).insert(s);
	}
}

/*
 Template habitaciones con error
 Errores posibles:
 1. Hotel cerrado (ERR3)
 2. Error de estancia mínima: mostramos el error con la estancia mínima para la fecha de entrada (ERR10)
 3. Error de release: mostramos el error con el release para la fecha de entrada (ERR11)
 4. Error día entrada (ERR14)
 5. Error día salida (ERR15)
 6. No ha disponibilidad: mostramos en rojo ON REQUEST (ERR12)
 7. No hay precios: mostramos en rojo CONSULTAR
*/

var txtError = 'NO DISPONIBLES - NOT AVAILABLE';
var txtRequest = 'RESERVA BAJO PETICIÓN - RESERVATION ON REQUEST';
var txtPrice = 'PRECIO PENDIENTE - PENDING PRICE';

function setError(data, setfirst)
{
	var strTemplate = $('template_otras_condiciones').innerHTML;
	var txtNoDispo = $$('#nodisponibilidad h2.header5 span')[0];

	switch(data.code)
	{
		case 'ERR3':
			var fechas_hotel = data.targetvalue.split(",");

			var apertura_hotel   = fechas_hotel[0] != undefined ? fechas_hotel[0] : "";
			var cierre_hotel     = fechas_hotel[1] != undefined ? fechas_hotel[1] : "";
			var reapertura_hotel = fechas_hotel[2] != undefined ? fechas_hotel[2] : "";

			var apertura = reapertura_hotel!="" ? reapertura_hotel : apertura_hotel;
			data.strcode = str_error_fechas_hotel.interpolate({apertura: apertura});

			//data.strcode_en = str_error_fechas_hotel_en.interpolate({apertura: apertura});
			//data.strcode = str_error_fechas_hotel.interpolate({apertura: apertura_hotel});
			//if(!cierre_hotel.blank()) data.strcode += str_fecha_cierre.interpolate({cierre: cierre_hotel});
			//if(!reapertura_hotel.blank()) data.strcode += str_fecha_reapertura.interpolate({reapertura: reapertura_hotel});

		break;
		case 'ERR10':
			data.strcode = str_error_release.interpolate({dias: data.targetvalue});
		break;
		case 'ERR11':
			data.strcode = str_error_estancia_minima.interpolate({dias: data.targetvalue});
		break;
		case 'ERR12':
			data.strcode = str_error_disponibilidad.interpolate({});
		break;
		case 'ERR14':
			data.strcode = str_error_dia_entrada.interpolate({dia_es: eval("str_day_"+data.targetvalue+"_es"), dia_en: eval("str_day_"+data.targetvalue+"_en")});
		break;
		case 'ERR15':
			data.strcode = str_error_dia_salida.interpolate({dia_es: eval("str_day_"+data.targetvalue+"_es"), dia_en: eval("str_day_"+data.targetvalue+"_en")});
		break;
		// No hay precio
		default:
			var noprice = true;
			data.strcode = str_error_precio;
		break;
	}

	if(hotel_onrequest == 'si' && data.code != 'ERR3')
	{
		$('explanation-onrequest').show();
		//txtNoDispo.update(txtRequest);
		txtNoDispo.hide();
	}
	else
	{
		$('explanation-onrequest').hide();
		txtNoDispo.update(noprice ? txtPrice : txtError);
	}

	var li = new Element('li');
	li.insert(strTemplate.interpolate(data));
	var text = $('errores').insert(li);

	if(setfirst)
	{
		$('nodisponibilidad').show();
		$('errores').down('li').writeAttribute('class', "otrascondiciones first");
	}
}

function updateRoomsAvailability(rooms)
{
	if (!rooms) return;

	var cont = 0;
	var setfirst = false;
	var oneavail = false;
	var showerrors = false;

	$('otherhotels').update();
	$('errores').update();

	rooms.each(function(room, index)
	{
		var id = room.id;
		var availability = room.availability.empty() ? 0 : parseInt(room.availability, 10);
		var error = room.error;
		var attention = '';

		// Precio medio para dos personas
		var price = room.price;
		var boards = room.boards.compact();
		var extras = room.extras.compact();

		if (error.code!='3' && ((availability > 0 && error.code.blank()) || hotel_onrequest == 'si'))
		{
			oneavail = true;

			if(!error.code.blank() || price.startsWith('0'))
			{
				attention = ' attention';

				showerrors = true;
				var errordata = {habitacion: $('texto_habitacion_'+id).innerHTML, code: "ERR"+error.code, targetvalue: error.targetvalue};
				setError(errordata, setfirst);
			}

			$('template_' + id).show();

			// Actualizamos la disponibilidad (max 3 habitaciones)
			var select = $('quantity_' + id);
			var maxQuantity = Math.min(availability, 3);

			while (select.options.length - 1 < maxQuantity)
			{
				select.options.add(new Option(select.options.length, select.options.length));
			}
			while (select.options.length - 1 > maxQuantity)
			{
				$(select.options[select.options.length - 1]).remove();
			}

			//Cambiar el color de fondo según si la fila es par o impar y el color de la letra si la habitación es onrequest (ahora no se cambia; las dos habitacion impar)
			$('template_' + id).writeAttribute('class', cont == 0 ? "habitacion impar first" + attention : (cont%2 == 1 ? ("habitacion impar" + attention) : ("habitacion impar" + attention)));

			if (!price.blank())
			{
				$('template_'+id).select('div.price').invoke('update', '<span>-</span>');
			}

			// Actualizamos las pensiones del template de cada habitación
			$('template_' + id).select('select[name="board[]"]').each(function(selectBoard)
			{
				var previousValue = selectBoard.value;
				selectBoard.options.length = 0;
				for (var i = 0; i < boards.length; i++)
				{
					var option = new Option(boards[i].name, boards[i].id);
					if (boards[i].id == previousValue) option.selected = 'selected';
					selectBoard.options.add(option);
				}
			});

			// Mostramos extras para esta habitación
			$('template_' + id).select('input[name="extra[]"]').each(function(selectExtra)
			{
				for (var i = 0; i < extras.length; i++)
				{
					if (extras[i].id == selectExtra.value)
					{
						selectExtra.up(1).show();
					}
				}
			});

			cont++;
		}
		else
		{
			$('template_' + id).hide();

			if(!setfirst) setfirst = true;

			showerrors = true;
			var errordata = {habitacion: $('texto_habitacion_'+id).innerHTML, code: "ERR"+error.code, targetvalue: error.targetvalue};
			setError(errordata, setfirst);
		}

		//Actualizar las filas de habitaciones
		selectHabitaciones($('quantity_' + id), id);

	});

	if(oneavail)
	{
		$('disponibilidad').show();
		$('agesnote').show();
		$('nextstep').show();

		calculatePrice();
	}
	else
	{
		$('disponibilidad').hide();
		$('nextstep').hide();
	}

	$('disponibilidad').setOpacity(1);
	$('nodisponibilidad').setOpacity(1);

	// Mostramos otros hoteles
	if(showerrors)
	{
		$('nodisponibilidad').show();
		updateOtherHotels();
	}
	else
	{
		$('nodisponibilidad').hide();
	}
}

function updateChildrenCombo(room, id)
{
	var adSelect = room.select('select[name="adults[]"]').first();
	var chSelect = room.select('select[name="children[]"]').first();

	// Posición anterior
	var position = chSelect.selectedIndex;

	// Vaciamos el select
	chSelect.options.length = 0;

	// Rellenamos el select
	combos[id][adSelect.selectedIndex].compact().each(function(children)
	{
		chSelect.options.add(new Option(children.num, children.num));
	});

	// Reseteamos la posición
	chSelect.selectedIndex = (position < chSelect.options.length) ? position : 0;

	// Actualizamos el select de bebés
	updateBabiesCombo(room, id);
}

function updateBabiesCombo(room, id)
{
	var adSelect = room.select('select[name="adults[]"]').first();
	var chSelect = room.select('select[name="children[]"]').first();
	var baSelect = room.select('select[name="babies[]"]').first();

	// Posición anterior
	var position = baSelect.selectedIndex;

	// Vaciamos el select
	baSelect.options.length = 0;

	// Rellenamos el select
	combos[id][adSelect.selectedIndex].compact().each(function(children)
	{
		if (children.num == $F(chSelect))
		{
			children.babies.compact().each(function(baby)
			{
				baSelect.options.add(new Option(baby, baby));
			});

			throw $break;
		}
	});

	// Reseteamos la posición
	baSelect.selectedIndex = (position < baSelect.options.length) ? position : 0;
}

function checkAvailability()
{

	if (!$F('arrival').isDate() || !$F('departure').isDate() || processingAjax)
	{
		return;
	}

	processingAjax = true;

	new Ajax.Request
	(
		'/' + hotel_id + '/ajax-availability.html',
		{
			parameters :
			{
				arrival   : $F('arrival'),
				departure : $F('departure')
			},
			onSuccess : function(transport)
			{
				processingAjax = false;
				updateRoomsAvailability(transport.responseJSON);
				$('loading').hide();
			}
		}
	);

}

function updateOtherHotels()
{

	if (!$F('arrival').isDate() || !$F('departure').isDate() || processingAjax)
	{
		return;
	}

	processingAjax = true;

	new Ajax.Request
	(
		'/' + hotel_id + '/ajax-onrequest.html',
		{
			parameters :
			{
				arrival   : $F('arrival'),
				departure : $F('departure')
			},
			onSuccess : function(transport)
			{
				processingAjax = false;
				$('otherhotels').show();
				$('otherhotels').update(transport.responseText);
			}
		}
	);

}

function calendarAvailability(id_habitacion, setfirst)
{
	if (!$F('arrival').isDate() || !$F('departure').isDate())
	{
		return;
	}

	processingAjax = true;

	var strTemplate = $('template_hab_sin_disponibilidad').innerHTML;

	new Ajax.Request
	(
		'/' + language_acronym + '/' + hotel_id + '/ajax-availability-calendar',
		{
			parameters :
			{
				arrival   : $F('arrival'),
				departure : $F('departure'),
				id_habitacion : id_habitacion
			},
			onSuccess : function(transport)
			{
				var text = strTemplate.interpolate({habitacion: $('texto_habitacion_'+id_habitacion).innerHTML});

				li1 = new Element('li');
				li1.insert(text);

				li2 = new Element('li');
				li2.insert(transport.responseText).hide();

				$('errores').insert(li1).insert(li2);

				if(setfirst)
				{
					$('nodisponibilidad').show();
					$('errores').down('li').writeAttribute('class', "otrasfechas first");
				}

				processingAjax = false;
			}
		}
	);

}

function calculatePrice()
{
	// Fechas inválidas
	if (!$F('arrival').isDate() || !$F('departure').isDate())
	{
		return;
	}

	// Limpiar los campos de extras
	$$('input[name^="extras"]').invoke('clear');

	var position = -1;

	$$('li[id^="rextras_"]').each
	(
		function(el)
		{
			if(el.style.display == '')
			{
				position++;

				if(!$$("input[type=hidden][name^='extras["+position+"]']").first())
				{
					var inp = document.createElement("input");
					inp.setAttribute("type", "hidden");
					inp.setAttribute("name", "extras["+position+"]");
					$('booking').appendChild(inp);
				}

				el.select('input[type=checkbox][name^="extra"]').each
				(
					function(c)
					{
						if(c.checked)
						{
							var found = $$("input[type=hidden][name='extras["+position+"]']").first();
							found.value += found.value != '' ? "," + c.value : c.value;
						}
					}
				);

			}
		}
	);

	$('myPrice').hide();
	if ($('myPricePro')) $('myPricePro').hide();
	$('myPriceLoading').show();

	new Ajax.Request
	(
		'/' + hotel_id + '/ajax-price.html',
		{
			parameters : $('booking').serialize(),
			onSuccess  : function(transport) {updateMyPrice(transport.responseJSON);}
		}
	);

}

function updateMyPrice(data)
{
	if (!data) return;

	$('myPrice').show();
	if ($('myPricePro')) $('myPricePro').show();
	$('myPriceLoading').hide();

	if (data.errorCode.empty())
	{
		$('error').hide();
		$('myPrice').update(data.price_ok == '0' ? 'Consultar - Consult' : data.price);
		if ($('priceProfessional')) $('priceProfessional').update(data.price_pro);
		if ($('priceCommision')) $('priceCommision').update(data.commision);

		// Mostramos precio final y total (si hay ofertas) por habitación
		data.breakdown.compact().each(function(br)
		{
			var pSelect = $('template_'+ br.id).select('div.price');

			if(data.price_ok == '0')
			{
				strPrice = '<span>n/d</span>';
			}
			else if(br.final != br.original)
			{
				strPrice = '<span class="anulado">' + br.original + '</span><br/><span class="destacado">' + br.final + '</span>';
			}
			else
			{
				strPrice = '<span>' + br.final + '</span>';
			}

			pSelect[br.index].update(strPrice);

		});

	}
	else
	{
		$('errorMsg').update(data.errorMsg);
		$('error').show();
	}
}

function optionsChanged()
{
	$('disponibilidad').hide();
	$('nextstep').hide();
	$('nodisponibilidad').hide();
	$('otherhotels').hide();
}

function manyNights()
{
	if (!($F('arrival').isDate()) || !($F('departure').isDate()))
	{
		return false;
	}

	var nights = $F('arrival').getDaysBetween($F('departure'));

	return nights > 0 ? nights : false;
}

function setNewArrival(arrival)
{
	if (typeof arrival == 'string' && arrival.isDate())
	{
		$('arrival').value = arrival;
	}

	$('arrival_back').value = $F('arrival');

	if ($F('arrival').isDate())
	{
		setNewDeparture($F('arrival').toDate().addDays($F('nights')).toStrDate());
	}
}

function setNewDeparture(departure)
{
	if (typeof departure == 'string' && departure.isDate())
	{
		$('departure').value = departure;
	}

	var newnights = manyNights();
	if($('nights').value != newnights || $('departure').value != $('departure_back').value)
	{
		optionsChanged();
	}

	$('departure_back').value = $F('departure');

	$('nights').value = manyNights() > 0 ? manyNights() : "--";
}

function initRoomInfo()
{
	//var Scriptaculous = typeof Effect != 'undefined';

	//Al hacer click sobre una imagen secundaria, cargarla sobre la imagen principal
	$('fotos').select('img').invoke('observe', 'click', function(event)
	{
		//Comprobar que la imagen de la miniatura está cargada y que no es la misma que la de la imagen principal
		if (event.element().complete && $('foto_principal').readAttribute('src') != event.element().readAttribute('src'))
		{
			//Efecto de reaparición

			$('foto_principal').setStyle({visibility:'hidden'});
			$('foto_principal').writeAttribute('src', event.element().readAttribute('src'));
			Effect.Queues.get('fotos').each(function(effect){effect.cancel()});
			new Effect.Appear($('foto_principal'), {
				duration:0.4, from:0, to:1, queue:{scope:'fotos'},
				beforeUpdate:function() {$('foto_principal').setStyle({visibility:'visible'});}
			});
		}
		event.stop();
	});

	return true;
}

/* INIT */
document.observe('dom:loaded', function()
{
	//Validar el formulario booking
	$('booking').onsubmit = function()
	{
		var error = false;
		var errormsg = false;

		//Si ninguno de los selects de quantity tiene valor, detenemos el envío
		var selects = $('booking').select('select[id^=quantity]');
		if (!(selects.any(function(el){ return parseInt(el.value) })))
		{
			errormsg = "Por favor, seleccione la cantidad de habitaciones que desea.\r\nPlease, select the number of rooms you wish.";
			error = true;
		}

		// Chequeamos que se han seleccionado las edades
		if(!error){
			$$('div[id^="el_"]').each(
				function(d){
					d.select('select').each(
						function(el){
							if($F(el).empty()){
								errormsg = "Por favor, introduzca la edad de los niños y/o bebés.\r\nPlease, enter the children's and/or babies' ages";
								el.previous('span').addClassName('agesrequired');
								new Effect.Pulsate(el.previous('span'))
								error = true;
							}
							else{
								el.previous('span').removeClassName('agesrequired').addClassName('agesspan');
							}
						}
					)
				}
			);
		}

		if(error)
		{
			alert(errormsg);
			return false;
		}

		return true;
	};

	if(!datesbyurl && readCookie('arrival') && readCookie('departure'))
	{
		$('arrival').value = readCookie('arrival');
		$('departure').value = readCookie('departure');
	}

	new InitDatePicker();

	migas(1);

	$('nights').onchange = function() {
		setNewDeparture($F('arrival').toDate().addDays($F('nights')).toStrDate())
	};
	$('nights').onclick = function()
	{
		setNewDeparture();
		$('nights').select();
	}

	$('nights').observe('keypress', function(event) {
		if (event.keyCode == 13) {this.onchange(); goSearch();}
	});

	$('search').onclick = goSearch;

	$('next').onclick = function(){if($('booking').onsubmit())$('booking').submit(); return false;}

	$('arrival').onchange = setNewArrival;

	$('departure').onchange = setNewDeparture;

	if (!$F('arrival').length && $F('arrival_back').isDate())
	{
		$('arrival').value = $F('arrival_back');
	}

	if (!$F('departure').length && $F('departure_back').isDate())
	{
		$('departure').value = $F('departure_back');
	}

	if (datesbyurl && $F('arrival').length && $F('departure').length)
	{
		goSearch();
	}
});

function goSearch()
{
	createCookie('arrival', $F('arrival'));
	createCookie('departure', $F('departure'));

	// Limpiamos y actualizamos información
	$('loading').show();
	$('disponibilidad').setOpacity(0.2);
	$('nodisponibilidad').setOpacity(0.2);

	$('myPrice').update();
	if ($('myPricePro')) $('myPricePro').update();

	infoBox.close('room-info');

	if(manyNights())
	{
		$('nights').value = manyNights();
		checkAvailability();
	}
	else
	{
		alert(str_error_noches)
	}
}

var InitDatePicker = Class.create();
var lastclicked = '';

//Inicializar los inputs de arrival y departure
InitDatePicker.prototype =
{
	initialize : function()
	{
		$$("input.datepicker").each(function(elemento,indx)
		{
			options =
			{
				clickCallback		: function()
				{
					var calendar = this;

					if (elemento.id == 'departure' && !$F(elemento).isDate() && $F('arrival').isDate())
					{
						elemento.value = $F('arrival').toDate().addDays(7).toStrDate();
					}

					document.observe('click', function(event)
					{
						if (event.target != elemento && event.target != elemento.next('img') && !$(event.target).descendantOf($("datepicker-" + elemento.id)))
						{
							calendar.close();
						}
					});

				},
				cellCallback		: function()
				{
					switch(elemento.id)
					{
						case 'arrival':
							setNewArrival();
							break;

						case 'departure':
							setNewDeparture();
							break;
					}
					document.stopObserving('click');
				},
				relative			: elemento.id,
				language			: elemento.lang,
				keepFieldEmpty		: true,
				enableShowEffect	: false,
				enableCloseEffect	: false,
				topOffset			: 25,
				disableFutureDate	: false,
				disablePastDate		: true,
				topOffset			: elemento.offsetHeight + 1
			}

			var obj = new DatePicker(options);

			//Añadir evento click de la imagen del calendario
			elemento.next('img').onclick = obj.click.bind(obj);

		}.bind(this))
	}
}

