// Funciones comunes del buscador interior y el de la home
function AutoCompleter(textbox)
{
	var options =
	{
		script: '/autocomplete3.html?',
		varname: 'destination',
		minchars: 3,
		minWidth: 250,
		maxWidth: 300,
		setWidth: true,
		delay: 400,
		maxentries: 15,
		noresults: _msg_noMatchesFound,
		timeout: 99999,
		useNotifier: true,

		callback: function(obj)
		{
			$('resort_id').value = obj.id;
			$('valida_ajax').hide().update();
		}
	};

	return new AutoComplete(textbox.id, options);
}

function calendarArrival()
{
	$('valida_date').hide().update();
	var minDate = new Date();
	showCalendar('arrival', minDate);
}
function calendarLeaving()
{
	$('valida_date').hide().update();
	if ($F('arrival'))
	{
		var minDateSplit = $F('arrival').split(/\//);
		var minDate = new Date(parseInt(minDateSplit[2],10),parseInt(minDateSplit[1],10)-1,parseInt(minDateSplit[0],10)+1);
	}
	else
	{
		var minDate = new Date();
	}
	showCalendar('leaving', minDate);
}
/*
function arrivalChange()
{
	var arrival = $('arrival').value.split(/\//);
	if (arrival && arrival.length == 3)
	{
		var arrivalDate = new Date(arrival[2],arrival[1]-1,arrival[0]);
	}
	var leaving = $('leaving').value.split(/\//);
	if (leaving && leaving.length == 3)
	{
		var leavingDate = new Date(leaving[2],leaving[1]-1,leaving[0]);
	}
	if (arrivalDate && leavingDate && leavingDate <= arrivalDate)
	{
		leavingDate = new Date(arrivalDate.getFullYear(),arrivalDate.getMonth(),arrivalDate.getDate()+1);
		$('leaving').value = [pad(leavingDate.getDate(),2,'0'), pad(leavingDate.getMonth()+1,2,'0'), leavingDate.getFullYear()].join('/');
	}
}
*/

// Funciones para el buscador en páginas interiores

function updateUrlFromOrder(select_order)
{
	var orderSplit = $F(select_order).split('.');
	$('order_by').value = orderSplit[0];
	$('order_type').value = orderSplit[1];
	$('page').value = 1;

	//Actualizar la URL y provocar que se renueve la búsqueda por ajax (RSH)
	var myURL = document.location.href.split('#');
	document.location.href = myURL[0] + '#' + $F('order_by') + ',' + $F('order_type') + ',' + $F('page');
}

function setParametersAndSearch()
{
	var myURL = document.location.href.split('#');

	if (typeof myURL[1] != 'undefined')
	{
		var params = myURL[1].split(',');

		if (typeof params != "undefined")
		{
			for (i = 0; i < params.length; i++)
			{
				if (params[i] != '')
				{
					switch (i)
					{
						case 0:
							$('order_by').value = params[i];
							break;
						case 1:
							$('order_type').value = params[i];
							break;
						case 2:
							$('page').value = params[i];
							break;
					}
				}
			}
		}
	}

	updateHotels();
}

function updateHotels()
{
	//Detener la búsqueda anterior, si todavía estuviera activa
	//La petición anterior se guarda en document.myAjaxRequest
	if (typeof myAjaxRequest == 'object') {
		myAjaxRequest.abort();
	}

	var effect_searching;
	var progress = $('searching-progress').update().show();

	//Desplegar el marco de información de búsqueda
	if (!$('searching').visible()) {
		if (Scriptaculous)
		{
			effect_searching = new Effect.SlideDown($('searching'), {
				duration:0.5,
				afterUpdate: function() { progress.hide(); },
				afterFinish: function() { progress.update('.').show(); }
			});
		}
		else
		{
			$('searching').show();
		}
	}

	//Iniciar el indicador de progreso
	if (typeof progressInterval == 'number') clearInterval(progressInterval);

	progressInterval = setInterval(function()
	{
		progress.innerHTML += '.';
		if (progress.innerHTML.length > 40) clearInterval(progressInterval);
	}, 1000);

	//Mostrar el destino buscado en el campo destination
	$('searching-destination').update($F('destination'));

	//Realizar la búsqueda por ajax
	myAjaxRequest = new Ajax.Request('/hotels-list', {
		method: 'post',
		parameters: $('findandbook').serialize() + "&ajax=1",
		onSuccess: function(transport) {
				var updateHotelsSuccess = function()
				{
					if (transport.responseText.length)
					{
						$('hotelslistajax').hide();
						$('hotelslistajax').update(transport.responseText);
						if (typeof replaceSelects == 'function') replaceSelects();
						$('searching').hide();
						if (Scriptaculous)
							new Effect.Appear($('hotelslistajax'), { duration:0.5 });
						else
							$('hotelslistajax').show();

						clearInterval(progressInterval);
					}
				};
				if (effect_searching && effect_searching.state == 'running') {
					effect_searching.options.afterFinish = updateHotelsSuccess;
				}
				else {
					updateHotelsSuccess();
				}
			},
		onFailure: function() {
				clearInterval(progressInterval);
				progress.update('...error')
			}
	});

	//Desplazar la ventana hacia arriba
	if ($('resumen-resultados') && $('resumen-resultados').viewportOffset()['top'] < 0)
	{
		var destY = 168;
		if (Scriptaculous)
			new Effect.Tween(null, window.scrollY, destY, {duration:0.5}, function(val){window.scrollTo(0,val)});
		else
			$('resumen-resultados').scrollTo();
	}

}

function hotelInfo(id)
{
	if ($('hotelForm' + id))
		$('hotelForm' + id).submit();
}

//Recibe varias urls alternativas para la imagen y las asigna hasta encontrar una. Si ninguna funciona, se asigna una imagen de error
function swapImg(img,urls)
{
	urls = urls.split(/;/);
	var url = urls.shift();
	if (!url.length || typeof url == 'undefined') {
		img.onerror = null;
		img.src = '/img/img-error.png';
	}
	else {
		img.onerror = function() { swapImg(img,urls.join(';')) };
		img.src = url;
	}
}

function infantsNoteDisplay()
{
	var total = 0;

	//Si al menos uno de los selects de bebés tiene algún valor, mostrar el aviso
	if ($$('*[id^=infants_]').any(function(element) {return element.selectedIndex > 0}))
	{
		$('infantsnote').show();
		if (Scriptaculous) new Effect.Pulsate($('infantsnote'), {pulses:2,duration:0.7,from:0.5});
	}
	else
	{
		$('infantsnote').hide();
	}
}

function getTotalChildren()
{
	var total = 0;

	for (var i = 0; i <= $('rooms').selectedIndex; i++)
	{
		total += parseInt($('children_' + i).selectedIndex, 10);
	}

	return total;
}

function displayChildrenAge()
{
	var total = getTotalChildren();

	if ($('div_children_ages'))
	{
		if (Scriptaculous)
		{
			if (total > 0 && !$('div_children_ages').visible()) new Effect.BlindDown($('div_children_ages'), {duration:0.5});
			else if (total == 0 && $('div_children_ages').visible()) new Effect.BlindUp($('div_children_ages'), {duration:0.5});
		}
		else
		{
			if (total > 0) $('div_children_ages').show();
			else $('div_children_ages').hide();
		}
	}

	for (var i = 0; i < $('rooms').length * 2; i++)
	{
		if (Scriptaculous && !($('div_children_ages') && !$('div_children_ages').visible()))
		{
			if (i < total && !$('age_' + i).visible()) new Effect.BlindDown($('age_' + i), {duration:0.5});
			else if (i >= total && $('age_' + i).visible()) new Effect.BlindUp($('age_' + i), {duration:0.5});
		}
		else
		{
			if (i < total) $('age_' + i).show();
			else $('age_' + i).hide();
		}
	}
}

function displayRooms()
{
	for (var i = 0; i < $('rooms').length; i++)
	{
		if (i < $('rooms').value)
		{
			if (Scriptaculous) {
				if (!$('room_' + i).visible()) new Effect.SlideDown($('room_' + i), {duration:0.5});
			} else {
				$('room_' + i).show();
			}
		}
		else
		{
			if (Scriptaculous) {
				if ($('room_' + i).visible()) new Effect.SlideUp($('room_' + i), {duration:0.5});
			} else {
				$('room_' + i).hide();
			}
		}
	}

	displayChildrenAge();
	infantsNoteDisplay();
}

function displayAdvancedSearch() {

	//Habilitar o deshabilitar los inputs del buscador avanzado
	//$('buscador-avanzado').select('input','select').invoke( $('buscador-avanzado').visible() ? 'disable' : 'enable');

	if (Scriptaculous)
		new Effect.toggle($('buscador-avanzado'), 'blind', { duration:0.4 });
	else
		$('buscador-avanzado').toggle();
}

function check_dates(arrival,leaving)
{
	$('valida_date').hide().update();

	var datearrival = check_date(arrival);
	var dateleaving = check_date(leaving);
	if (datearrival && dateleaving)
	{
		if (dateleaving > datearrival)
		{
			return true;
		}
		else
		{
			window.scroll(0,0);
			$('valida_date').update(_msg_dateleaving).show();
			if (Scriptaculous) $('valida_date').pulsate({pulses:2});
			return false;
		}
	}
	return false;
}

function check_date(date)
{
	// Regular expression used to check if date is in correct format
	var pattern = /^(\d{1,2})(\/)(\d{1,2})(\/)(\d{2,4})$/;

	if ($(date).value.match(pattern))
	{
		var date_array = $(date).value.split('/');
		var day = date_array[0];

		// Attention! Javascript consider months in the range 0 - 11
		var month = date_array[1] - 1;
		var year = date_array[2] < 100 ? 2000 + date_array[2] : date_array[2];

		// This instruction will create a date object
		var source_date = new Date(year,month,day);
		var now = new Date();
		now = new Date(now.getFullYear(), now.getMonth(), now.getDate());

		if (year != source_date.getFullYear() || month != source_date.getMonth() || day != source_date.getDate())
		{
			$('valida_date').update(_msg_dates).show();
			if (Scriptaculous) $('valida_date').pulsate({pulses:2});
			window.scroll(0,0);

			return false;
		}
		else if (source_date < now)
		{
			$('valida_date').update(_msg_dategreater).show();
			if (Scriptaculous) $('valida_date').pulsate({pulses:2});
			window.scroll(0,0);

			return false;
		}
	}
	else
	{
		$('valida_date').update(_msg_dates).show();
		if (Scriptaculous) $('valida_date').pulsate({pulses:2});
		window.scroll(0,0);
		return false;
	}

	return source_date;
}

function checkFindandbook(newParameters)
{
	if (typeof newParameters != 'undefined' && typeof newParameters.resort_id != 'undefined')
		$('resort_id').value = newParameters.resort_id;
	if (typeof newParameters != 'undefined' && typeof newParameters.destination != 'undefined')
		$('destination').value = newParameters.destination;

	if ($F('destination').length > 0)
	{
		if (check_dates('arrival','leaving'))
		{
			new Ajax.Request('/autocomplete2.html', {
				method:'post',
				parameters:{
					'valida':true,
					'ajax_autocomplete':true,
					'destination':$F('destination')
				},
				onSuccess:function(transport) {sendform(transport.responseText)}
			});
		}
		else
		{
			if ($('content').viewportOffset()['top'] < 0) $('content').scrollTo();
			$('arrival').focus();
		}
	}
	else
	{
		if ($('content').viewportOffset()['top'] < 0) $('content').scrollTo();
		$('valida_ajax').update(_msg_destination).show();
		if (Scriptaculous) $('valida_ajax').pulsate({pulses:2});
	}
}

function findRooms()
{
	if (check_dates('arrival','leaving'))
	{
		$('roomslistajax').update();
		$('roomslistajax-notifier').show();
		new Ajax.Request('/rooms-list', {
			method: 'post',
			parameters: $('findrooms').serialize() + "&ajax=1",
			onSuccess: function(transport) {
				$('roomslistajax-notifier').hide();

				$('roomslistajax').update(transport.responseText);
				$("hotelForm").action = secure_base_href + "/basket-step1/" + $F('mynormalisedname') + "-" + $F('myitinerary') + ".html";

				if (typeof replaceSelects == 'function') replaceSelects();

				if ($('button-next')) $('button-next').show();
			}
		});
	}
	else
	{
		if ($('content').viewportOffset()['top'] < 0) $('content').scrollTo();

		if(!check_date('arrival'))
			$('arrival').focus();
		else
			$('leaving').focus();
	}
}

function changedata(data_r)
{
	eval(data_r);
}

function sendform(data_r)
{
	var todo_ok, morep;
	eval(data_r); //debe devolver todo_ok = true;

	if(todo_ok)
	{
		$('valida_ajax').hide().update();

		if ($('buscador-avanzado') && !$('buscador-avanzado').visible())
		{
			$('buscador-avanzado').select('input','select').invoke('clear');
		}

		var destination = $F('destination').toLowerCase();
		var arrival = $F('arrival');
		$('findandbook').setAttribute('action', $('findandbook').getAttribute('action') + '/' + _msg_hotels + '/' + destination + ',' + $F('arrival') + ',' + $F('leaving') + '#' + $F('order_by') + ',' + $F('order_type') + ',1');
		$('findandbook').submit();
	}
	else
	{
		$('valida_ajax').update(_msg_mean + ": " + morep).show();
		if (Scriptaculous) $('valida_ajax').pulsate({pulses:2});
		if ($('content').viewportOffset()['top'] < 0) $('content').scrollTo();
		$('destination').focus();
	}
}

function checkBook(formElement) {

	if(formElement.myitinerary == undefined)
	{
		alert(_msg_search_rooms);
		return false;
	}

	Element.extend(formElement); //IE
	var searchrooms = $("nrooms")!=null ? $("nrooms").value : 0;
	var sumrooms = 0;
	var quantities = formElement.select('[name="quantity[]"]');
	for (var i = 0; quantities[i]; i++) {
		sumrooms += parseInt($F(quantities[i]));
	}
	if (sumrooms != searchrooms || sumrooms == 0) {
		if ($F('nrooms') == 1) {
			alert(_msg_select_1room);
		} else {
			alert(_msg_select_nrooms.replace(/%rooms/,$F('nrooms')));
		}
		return false;
	}

	return true;
}
