var count = 0;
var total = 0;

document.observe('dom:loaded', function()
{
	$('submit').observe('click', function(ev)
	{
		$('booking').submit();
		Event.stop(ev);
	});

	$('noavail_close').observe('click', function(ev)
	{
		$('noavailability').hide();
		Event.stop(ev);
	});

	$('searchdates').observe('click', function(ev)
	{
		checkAvailability();
		Event.stop(ev);
	});

	checkAvailability(true);
});

function addRoom(id)
{
	if (rooms_availability[id] == undefined) return;

	// Límite de 5 habitaciones por reserva
	if (total > 4)
	{
		alert(msg['error_max_reached']);
		return false;
	}

	// Comprobamos disponibilidad de la habitación
	if (rooms_availability[id].counter < 1)
	{
		alert(msg['error_availability']);
		return false;
	}

	// Obtenemos la copia del template de la habitación
	var clone_r = $('template_room_' + id).cloneNode(true);

	// Obtenemos la copia del template de los extras
	var clone_e = $('template_extras_' + id).cloneNode(true);

	// Cambiamos atributos
	clone_r.writeAttribute("rel", "room");
	clone_r.writeAttribute("id", "room_"+count);
	clone_e.writeAttribute("rel", "extras");
	clone_e.writeAttribute("id", "rextras_"+count);

	// Adultos por defecto seleccionados en el clon (esto sólo es necesario para IE)
	clone_r.select('select[name="adults[]"]').first().selectedIndex = $('template_room_' + id).select('select[name="adults[]"]').first().selectedIndex;

	/*
	 Ponemos el id de la habitación y cambiamos nombres.
	 Hay que hacerlo así para poder luego distinguir entre lo que es template o habitación seleccionada y asociar suplementos con dichas habitaciones.
	*/
	clone_r.select('input[name="room[]"]').first().setAttribute("value", id);

	// Cambiamos nombres y les ponemos el índice de habitación
	clone_r.select('*[name$="[]"]').each(function(fe){fe.setAttribute("name", fe.getAttribute("name").replace(/(\[\])/, "["+count+"]"))});
	clone_e.select('*[name$="[]"]').each(function(fe){fe.setAttribute("name", fe.getAttribute("name").replace(/(\[\])/, "["+count+"][]"))});

	// Insertamos el nodo clonado de la habitación
	$('myrooms').insert(clone_r);

	// Insertamos el nodo clonado de extras
	$('myrooms').insert(clone_e);

	if (total == 0)
	{
		clone_r.show();
		new Effect.Appear('selectedRooms', {duration: 0.5});
	}
	else
	{
		new Effect.Appear(clone_r, { duration: 0.5 });
	}

	// Si hay extras que mostrar ...
	if(clone_e.select('div[style=""]').length > 0)
	{
		new Effect.Appear(clone_e, { duration: 0.5 });
	}

	var scrollToRooms = function()
	{
		var roomsOffset = $('selectedRooms').viewportOffset()[1];
		var roomsHeight = $('selectedRooms').getDimensions()['height'];
		var viewportHeight = document.viewport.getDimensions()['height'];

		if (roomsOffset + roomsHeight > viewportHeight)
		{
			new Effect.ScrollTo($('selectedRooms'), {duration:0.5, offset:-(viewportHeight-roomsHeight)});
		}
	}

	scrollToRooms.delay(0.1);

	// Actualizamos contadores
	total++;
	count++;

	// Actualizamos disponibilidad
	rooms_availability[id].counter--;

	return true;
}

function delRoom(el, id)
{
	total--;

	if (total == 0)
	{
		$('selectedRooms').hide();
	}

	// Eliminamos extras
	el.parentNode.parentNode.next().remove();

	// Eliminamos habitación
	el.parentNode.parentNode.remove();

	// Actualizamos disponibilidad
	rooms_availability[id].counter++;

	return true;
}

function updateRoomsAvailability(rooms)
{

	$$('*[id^=avtxt2_]').invoke('update', '&nbsp');
	$$('*[id^=avtxt2_]').invoke('hide');
			
	rooms.each(function(room, index)
	{
		var id = room.id;
		var availability = parseInt(room.availability, 10);
		var errorcode = room.error.code;
		var price = room.price;
		var boards = room.boards.compact();
		var extras = room.extras.compact();

		// Actualizamos la disponibilidad de cada habitacion
		rooms_availability[id].counter = availability;

		// ¿Existe error (aunque haya disponibilidad)?
		if(!errorcode.blank())
		{
			$('avtxt_' + id).update(msg['info_no']);
			$('avnok_' + id).hide();
			$('avok_' + id).hide();
			$('room_' + id).select('div.bottom').first().addClassName('avok');
			
			$('avtxt2_' + id).update(room.error.text);
			$$('*[id^=avtxt2_]').invoke('show');			
		}
		else if (availability > 0)
		{
			// Escondemos calendarios por si estuviera abierto
			$('noavailability').hide();
			// Hay disponibilidad, mostramos los botones
			$('avok_' + id).show();
			$('avnok_' + id).hide();
			$('room_' + id).select('div.bottom').first().addClassName('avok');
			$('avtxt_' + id).update(msg['info_si']);

			if (availability == 1)
			{
				$('avtxt2_' + id).update(msg['info_last_room']);
				$$('*[id^=avtxt2_]').invoke('show');
						}
			else if (availability < 4)
			{
				$('avtxt2_' + id).update(msg['info_last_rooms']);
				$$('*[id^=avtxt2_]').invoke('show');			
			}

			if (!price.blank())
			{
				$('price_' + id).update(price);
			}

			// Actualizamos las pensiones del template de cada habitación
			var select = $('template_room_' + id).select('select[name="board[]"]').first();
			select.length = 0;

			boards.each(function(board)
			{
				select.options.add(new Option(board.name, board.id));
			});

			// Escondemos del template todos los suplementos
			$('template_extras_' + id).select('div').invoke('hide');

			// Mostramos los suplementos para este precio
			extras.each(function(extra)
			{
				var ex = $('template_extras_' + id).select(extra.type+'[id="extra_'+id+"_"+extra.id+'"]').first();
				ex.up('div').show();
			});
		}
		else
		{
			// No hay disponibilidad
			$('avtxt_' + id).update(msg['info_no']);
			$('avok_' + id).hide();
			$('avnok_' + id).show();
			$('room_' + id).select('div.bottom').first().removeClassName('avok');
		}
	});

	$('selectedRooms').hide();

	// Eliminamos las habitaciones que se seleccionaron y sus extras
	$$('tr[rel="room"]').invoke('remove');
	$$('tr[rel="extras"]').invoke('remove');

	// A cero contadores
	total = 0;
	count = 0;
}

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.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.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.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.length) ? position : 0;
}

function checkAvailability(first)
{
	if (!$F('arrival').isDate() || !$F('departure').isDate() || $F('arrival').getDaysBetween($F('departure')) < 1)
	{
		return;
	}

	if ($F('arrival').getDaysBetween($F('departure')) > 31)
	{
		alert(msg['error_dates_max'])
		return;
	}

	new Ajax.Request
	(
		'ajax-availability',
		{
			asynchronous: !first,
			parameters :
			{
				arrival   : $F('arrival'),
				departure : $F('departure')
			},
			onSuccess : function(transport) {
				updateRoomsAvailability(transport.responseJSON);

				//Custom event para auto-agregar la habitación clickada desde la ficha de hotel
				document.fire('roomsAvailability:load');
			}
		}
	);
}

function calculatePrice()
{
	if (!$F('arrival').isDate() || !$F('departure').isDate())
	{
		return;
	}

	$('myPrice').hide();
	$('myPriceLoading').show();

	// Limpiar los campos de extras
	$$('input[name^="extras"]').invoke('clear');

	// Extraemos la información del formulario de extras
	$('booking').select('tr[rel="extras"] input[type=checkbox][name^="extra"]', 'tr[rel="extras"] select[name^="extra"]').each(function(element)
	{
		if ((element.type == 'checkbox' && element.checked) || (element.type == 'select-one' && element.value.length))
		{
			var position = element.up('tr').id.match(/rextras_(\d+)/)[1];

			$$('input[name="extras[' + position + ']"]').first().value += ($$('input[name="extras[' + position + ']"]').first().value.length ? "," : "") + element.value;
		}
	});

	new Ajax.Request
	(
		'ajax-price',
		{
			parameters : $('booking').serialize(),
			onSuccess  : function(transport) { updateMyPrice(transport.responseJSON); }
		}
	);
}

function updateMyPrice(data)
{
	$('myPrice').show();
	$('myPriceLoading').hide();

	if (data.errorCode.empty())
	{
		$('error').hide();
		$('myPrice').update(data.price);
		$('price').show();
		$('submitDiv').show();

		if (!data.deposit.empty())
		{
			//Rellenar los span de pago fraccionado con los valores de deposit, rest y date
			data.deposit = '<strong>' + data.deposit + '</strong>';
			data.rest = '<strong>' + data.rest + '</strong>';
			$('spanPagoFraccionadoFecha').update($('spanPagoFraccionadoFecha').title.interpolate(data));
			$('spanPagoFraccionadoHotel').update($('spanPagoFraccionadoHotel').title.interpolate(data));

			if (data.hotel == '1')
			{
				$('divFraccionadoHotel').show();
				$('divFraccionadoFecha').hide();
			}
			else
			{
				$('divFraccionadoFecha').show();
				$('divFraccionadoHotel').hide();
			}
		}
		else
		{
			$('divFraccionadoFecha', 'divFraccionadoHotel').invoke('hide');
		}
	}
	else
	{
		$('price').hide();
		$('divFraccionadoFecha', 'divFraccionadoHotel').invoke('hide');
		$('submitDiv').hide();

		$('errorMsg').update(data.errorMsg);
		$('error').show();
	}
}

function calendarAvailability(id_habitacion, position)
{
	if (!$F('arrival').isDate() || !$F('departure').isDate() || $F('arrival').getDaysBetween($F('departure')) < 1 )
	{
		alert(msg['error_dates'])
		return;
	}

	$('noavailability').show();
	$('noavail_room').update($$('li#room_'+id_habitacion+' th').first().innerHTML);
	$('calendars').update('...');

	new Ajax.Updater
	(
		'calendars', 'ajax-availability-calendar',
		{
			parameters : "arrival="+$F('arrival')+"&departure="+$F('departure')+"&id_habitacion="+id_habitacion
		}
	);
}