function addCommas(nStr)
{
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? ',' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;

	while (rgx.test(x1))
	{
		x1 = x1.replace(rgx, '$1' + '.' + '$2');
	}

	return x1 + x2;
}

function formatPrice(price)
{
	if (price > 0)
	{
		return addCommas(price.toFixed(2)) + " €";
	}
	else
	{
		return '-';
	}
}

var processingAjax = false;

function displayRooms(el)
{
	optionsChanged();

	for(var i = 1; i < el.options.length+1; i++){
		if(el.value < i){
			$('room_'+i).hide();
			// Reset ages
			$('room_'+i).select("select#selectC_"+i)[0].selectedIndex = 0;
			$('room_'+i).select("select#selectB_"+i)[0].selectedIndex = 0;
			displayAge(i);
		}else{
			$('room_'+i).setStyle({backgroundColor: '#E1EFFF'});
			$('room_'+i).show();

			displayAge(i);
		}
	}
}

function displayAge(idstr)
{
	if(webservice == 'barcelo') return;

	//Limpiamos
	$$('li#ages_'+idstr+' div[id^=el_]').invoke('remove');
	$('ages_'+idstr).select('div.ageselect').each(function(e){e.select('select[class="template"]')[0].disable()});

	var ChDiv = document.createElement('div');
	ChDiv.id = "chdiv_"+idstr;
	$(ChDiv).addClassName('childrenAges');

	var BaDiv = document.createElement('div');
	BaDiv.id = "badiv_"+idstr;
	$(BaDiv).addClassName('babiesAges');

	$('ages_'+idstr).insert(ChDiv);
	$('ages_'+idstr).insert(BaDiv);

	ch = $('selectC_'+idstr);
	for(var i = 0; i < ch.value; i++)
	{
		var s = $('ages_'+idstr).select('div.ageselect')[0].cloneNode(true);
		s.style.display = "block";
		s.select('select')[0].enable();
		s.id = 'el_'+idstr+"_"+i;
		s.select('span')[0].update('Niño '+'#'+(i+1) + ' - Child '+'#'+(i+1)+": ");
		$('chdiv_'+idstr).insert(s);
	}

	bb = $('selectB_'+idstr);
	for(var i = 0; i < bb.value; i++)
	{
		var s = $('ages_'+idstr).select('div.ageselect')[1].cloneNode(true);
		s.style.display = "block";
		s.select('select')[0].enable();
		s.id = 'el_'+idstr+"_"+i;
		$('badiv_'+idstr).insert(s);
	}
}

// For auto offers (ex. cloud/dingus)
var checkboxdis = '<input type="checkbox" checked="checked" disabled="disabled" style="display:none;vertical-align:middle"/>';
var prices = new Object();
var offers = new Object();
var onrequest = new Object();
var availcode = new Object();
var totalprice;
var breakdown;

// Without Offers
var pricesno = new Object();
var totalpriceno;
var breakdownno;
var selectsdefault = Array();

function showPricesAndOffers(el)
{
	if(el)
	{
		var hashroom = el.id+"_"+el.value;
		var i = el.id.match(/rcandidates_(\d+)/)[1];
		var pvalue = Math.round(prices[hashroom]*100)/100;
		breakdown[i] = pvalue;

		if(globalOffers.length > 0)
		{
			updateSelect(i, 0);
			selectsdefault[i] = $('divnhabsametype').innerHTML;

		}else{

			$('stay_'+i).select('span.price')[0].update(formatPrice(pvalue));

			// Without Offers
			var pvalueno = Math.round(pricesno[hashroom]*100)/100;
			if(pvalue < pvalueno)
			{
				breakdownno[i] = pvalueno;
				$('stay_'+i).select('span.priceno')[0].update(formatPrice(pvalueno));
				$('stay_'+i).select('span.price')[0].setStyle("color:#CC0000");
			}else{
				$('stay_'+i).select('span.priceno')[0].update();
				$('stay_'+i).select('span.price')[0].setStyle("color:#01305C");
			}
		}

		if(onrequest[el.id+"_"+el.value] == "true")
		{
			$('stay_'+i).addClassName("attention");
			$('stay_'+i).select("select option:not([style!=''])").invoke("setStyle", "color:#01305C");
			$('stay_'+i).select('span.price')[0].setStyle("color:#CC0000");
		}
		else
		{
			$('stay_'+i).removeClassName("attention");
		}

		showOffers(i, hashroom);
		reasonNotAvail(i, hashroom);

	}else{ // Treatment of stays
		var selects = $('roomsavail').select("select[name!='notavail[]']");

		breakdown = Array();
		breakdownno = Array();

		selects.each(function(room, index)
		{
			var hashroom = room.id+"_"+room.value;
			var i = room.id.match(/rcandidates_(\d+)/)[1];
			var pvalue = Math.round(prices[hashroom]*100)/100;
			breakdown[i] = pvalue;

			if(globalOffers.length > 0)
			{
				selectprices = updateSelect(i, 0);
				selectsdefault[i] = $('divnhabsametype').innerHTML;

			}else{
				$('stay_'+i).select('span.price')[0].update(formatPrice(pvalue));
			}

			// Without Offers
			var pvalueno = Math.round(pricesno[hashroom]*100)/100;
			if(pvalue<pvalueno)
			{
				breakdownno[i] = pvalueno;
				$('stay_'+i).select('span.priceno')[0].update(formatPrice(pvalueno));
				$('stay_'+i).select('span.price')[0].setStyle("color:#CC0000");
			}

			if(onrequest[hashroom] == "true")
			{
				$('stay_'+i).addClassName("attention");
				$('stay_'+i).select("select option:not([style!=''])").invoke("setStyle", "color:#01305C");
			}

			showOffers(i, hashroom);
			reasonNotAvail(i, hashroom);
		});
	}

	updateTotalPrice(0, getNRoomsSelected());
}


function updateTotalPrice(discount, various)
{
	// This is only for complex offers like Barceló
	var various = various > 1 ? various : 1;

	totalprice = 0;
	totalpriceno = 0;

	breakdown.each(function(value)
	{
		if(!isNaN(value))
		{
			totalprice += various*(value - discount);
		}
	});

	breakdownno.each(function(value)
	{
		if(!isNaN(value))
		{
			totalpriceno += value;
		}
	});

	$('myPrice').update(formatPrice(Math.round(totalprice*100)/100));
}

function searchComplexOffers(code)
{
	var coffer = new Object();
	coffer.description = "";

	for(var c = 0; c < globalOffers.length; c++)
	{
		if(globalOffers[c].code == code)
		{
			coffer = globalOffers[c];
			break;
		}
	}

	return coffer;
}

function showOffers(i, hash)
{
	if(offers[hash] && offers[hash].length > 0)
	{
		$('stay_'+i).select('div.offer')[0].update();
		$('stay_'+i).select('li.offer')[0].show();

		// Applied offers
		offers[hash].each(function(offer)
		{
			if(offer.code == "")
			{
				$('stay_'+i).select('div.offer')[0].innerHTML += checkboxdis + offer.name + "<br/>";
			}
		});

		if(!$('stay_'+i).select('div.offer')[0].empty())
		{
			$('stay_'+i).select('div.offer')[0].innerHTML =  $('offerheadersimple').innerHTML + $('stay_'+i).select('div.offer')[0].innerHTML;
			if(globalOffers.length)
			{
				$('stay_'+i).select('div.offer')[0].innerHTML += "<hr style='margin-top:10px'/>";
			}
		}

		// Promotions
		if(globalOffers.length)
		{
			$('stay_'+i).select('div.offer')[0].innerHTML += $('offerheadercomplex').innerHTML;
		}
		offers[hash].each(function(offer)
		{
			if(offer.code != "")
			{
				var coffer = searchComplexOffers(offer.code);
				$('stay_'+i).select('div.offer')[0].innerHTML +=
												$('complex_offers_description').innerHTML
												.replace(/#stay#/g, i)
												.replace(/#code#/g, offer.code)
												.replace(/#name#/i, offer.name)
												.replace(/#price#/i, formatPrice(parseFloat(breakdown[i] - offer.discount)))
												.replace(/#discount#/i, offer.discount)
												.replace(/#description#/i, coffer.description);

			}

		});

	}else{
		$('stay_'+i).select('li.offer')[0].hide();
	}
}

// For complex offers
function updatePrice(el)
{
	// No noautooffers with a radio button behaviour
	var allnoautooffers = $$('input[name="noautooffers"]');
	allnoautooffers.each
	(
		function(cur)
		{
			if(cur.id != el.id)
			{
				cur.checked = cur.value == el.value ? el.checked : false;
			}
		}
	);

	// Update Selector
	var i = el.id.match(/(\d+)_(\d+)/)[1];
	if(el.checked)
	{
		var discount = parseFloat(el.readAttribute('rel'));
		var nhabs = updateSelect(i, discount);
		updateTotalPrice(discount, nhabs);
	}
	else
	{
		var currsel = getNRoomsSelected();
		$('stay_'+i).select('span.price')[0].innerHTML = selectsdefault[i].replace('selected="selected"', "").replace('value="'+currsel+'"', 'value="'+currsel+'" selected="selected"');
		updateTotalPrice(0, currsel);
	}
}

function getNRoomsSelected()
{
	var currsel = 1;
	if($('nhabsametype'))
	{
		var optionsel = $('nhabsametype').select('option').find(function(ele){return !!ele.selected});
		currsel = optionsel.value;
	}

	return currsel;
}

function updateSelect(stay, value)
{
	var currsel = getNRoomsSelected();

	var selectprices = '<div id="divnhabsametype"><select style="display:none" name="nhabsametype" id="nhabsametype" onchange="updateTotalPrice('+value+', this.value)">';
	for(n=1; n<2;n++){var val = (breakdown[stay] - value)*n;selectprices += '<option '+(currsel==n ? 'selected="selected"' : '')+' value="'+n+'">'+n+'hab. '+formatPrice(val)+'</option>'}
	selectprices += '</select></div>';
	//$('stay_'+stay).select('span.price')[0].innerHTML = selectprices;

	if(value == 0)
	{
		$('stay_'+stay).select('span.price')[0].innerHTML = '<div id="divnhabsametype">'+formatPrice(breakdown[stay])+'</div>';
	}
	else
	{
		var classp = value > 0 ? 'preciotachado preciobig' : 'preciotachado';
		$('stay_'+stay).select('span.price')[0].innerHTML = '<div class="'+classp+'">'+formatPrice(breakdown[stay])+'</div>';
	}

	return currsel;
}

function reasonNotAvail(i, hash)
{
	if(availcode[hash] > 0)
	{
		$('stay_'+i).select('div.reasonnotavail span')[0].update();
		$('stay_'+i).select('li.reasonnotavail')[0].show();

		var reason = "";
		switch(availcode[hash])
		{
			case 10:
				reason =  str_error_release;
			break;
			case 11:
				reason =  str_error_estancia_minima;
			break;
			case 12:
				reason =  str_error_disponibilidad;
			break;
			case 13://NotPax
			break;
			case 14://NotRoom
			break;
		}

		$('stay_'+i).select('div.reasonnotavail span')[0].title = availcode[hash];
		$('stay_'+i).select('div.reasonnotavail span')[0].innerHTML = reason;

		var sel = $('stay_'+i).down('select').select('option').find(function(ele){return !!ele.selected});
		var boards = $('boards').select('option').find(function(ele){return !!ele.selected});
		getCalendar(sel.title, boards.value, availcode[hash], $('stay_'+i).select('div.calendar')[0]);

	}else{
		$('stay_'+i).select('li.reasonnotavail')[0].hide();
	}

	var onrr = $('roomsavail').select("ul[class~='attention']");
	onrr.length > 0 && hotel_onrequest == "no" ? $('nextstep').hide() : $('nextstep').show();
}

function updateBoards(boards)
{
	if (!boards) return;

	$('boards').options.length = 0;
	boards.each(function(b)
	{
		$('boards').options.add(new Option(b.name, b.code));
	});
}

function sortPrice(r1, r2)
{
	return r1.pricevalue - r2.pricevalue;
}

var globalRooms;
var globalOffers = Array();
function updateRoomsPerBoard()
{
	if (!globalRooms) return;

	var cont = 0;
	var setfirst = false;
	var oneavail = false;
	$('roomsavail').update();

	var sel = $$('#boards option').find(function(ele){return !!ele.selected});

	if(sel){
		var board = sel.value;
	}
	else{
		return oneavail;
	}

	globalRooms.each(function(room, index)
	{

		var id = room.id;
		var party = room.party;
		var ages = room.ages;
		var roomtypes = room.rooms;

		var roomtpl = $('template_room').cloneNode(true);
		roomtpl.id = "stay_" + id;
		roomtpl.style.display = "block";
		$('roomsavail').insert(roomtpl);

		var textroom = globalRooms.length == 1 ? "Hab. / Room" : "Hab./Room #"+id + " :";
		$('roomsavail').select("ul#"+roomtpl.id + " div.texto_habitacion span")[0].update(textroom);

		// Rooms
		var selectE = $('roomsavail').select("ul#"+roomtpl.id + " div.texto_habitacion select")[0];

		// Check if we can found a room associated with the selected board
		var roomandboardfound = false;
		if(roomtypes.size() > 0)
		{
			roomtypes = roomtypes.sort(sortPrice);
			roomtypes.each(function(r, index)
			{
				if(r && board == r.board)
				{
					var op = new Option(r.name, r.id);
					op.title = r.roomcode;
					if(r.onrequest == 'true')
					{
						op.style.color = "#CC0000";
					}

					selectE.options.add(op);

					prices["rcandidates_"+id+"_"+r.id] = r.pricevalue;
					pricesno["rcandidates_"+id+"_"+r.id] = r.pricenovalue;
					offers["rcandidates_"+id+"_"+r.id] = r.offers;
					onrequest["rcandidates_"+id+"_"+r.id] = r.onrequest;
					availcode["rcandidates_"+id+"_"+r.id] = parseInt(r.availcode,10);

					roomandboardfound = true;
				}
			});
		}

		if(roomandboardfound)
		{
			oneavail = true;

			selectE.id = "rcandidates_"+id;
			selectE.name = "room["+cont+"]";

			$('roomsavail').select("ul#"+roomtpl.id + " div.col-3 span")[0].update(party.adults);
			var inputAd = document.createElement('input');
			inputAd.type = "hidden"; inputAd.name = "adults_r[]"; inputAd.value = party.adults;
			$('roomsavail').select("ul#"+roomtpl.id + " div.col-3 span")[0].insert(inputAd);

			$('roomsavail').select("ul#"+roomtpl.id + " div.col-4 span")[0].update(party.children);
			var inputCh = document.createElement('input');
			inputCh.type = "hidden"; inputCh.name = "children_r[]"; inputCh.value = party.children;
			$('roomsavail').select("ul#"+roomtpl.id + " div.col-3 span")[0].insert(inputCh);

			$('roomsavail').select("ul#"+roomtpl.id + " div.col-5 span")[0].update(party.infants);
			var inputBa = document.createElement('input');
			inputBa.type = "hidden"; inputBa.name = "babies_r[]"; inputBa.value = party.infants;
			$('roomsavail').select("ul#"+roomtpl.id + " div.col-3 span")[0].insert(inputBa);

			// Ages
			ages.children.each(function(c)	{
				var inputChA = document.createElement('input');
				inputChA.type = "hidden";
				inputChA.name = "ninos_edades_r[]";
				inputChA.value = c;
				$('roomsavail').select("ul#"+roomtpl.id)[0].insert(inputChA);
			});

			ages.babies.each(function(b){
				var inputBaA = document.createElement('input');
				inputBaA.type = "hidden";
				inputBaA.name = "bebes_edades_r[]";
				inputBaA.value = b;
				$('roomsavail').select("ul#"+roomtpl.id)[0].insert(inputBaA);
			});

			$('stay_' + id).writeAttribute('class', cont == 0 ? "habitacion impar first" : (cont%2 == 1 ? ("habitacion par") : ("habitacion impar")));

			cont++;
		}
		else // Room not available
		{
			$('roomsavail').select("ul#"+roomtpl.id + " li").invoke("hide");
			$$("ul#"+roomtpl.id)[0].hide();
			var notAvailTpl = new Template($('template_room_not_available').innerHTML);
			$('roomsavail').select("ul#"+roomtpl.id)[0].insert(notAvailTpl.evaluate({id: id}));
			//$('rooms_not_available_txt').show();
			selectE.name = "notavail[]";
		}
	});

	showPricesAndOffers();

	return oneavail;
}

function updateRoomsAvailability()
{
	$('otherhotels', 'errores').invoke('update');
	$('legend', 'rooms_not_available_txt').invoke('hide');

	if(updateRoomsPerBoard())
	{
		$('disponibilidad', 'legend').invoke('show');
		$('loading').hide();
	}
	else
	{
		$('disponibilidad', 'nextstep').invoke('hide');
		$('loading', 'nodisponibilidad', 'rooms_not_available_txt').invoke('show');

		updateOtherHotels();
	}

	$('disponibilidad').setOpacity(1);
	$('nodisponibilidad').setOpacity(1);
}

function checkAvailability()
{

	if (!$F('arrival').isDate() || !$F('departure').isDate() || processingAjax)
	{
		return;
	}

	var pars = $('booking').serialize();

	processingAjax = true;

	new Ajax.Request
	(
		'/' + hotel_id + '/' + url_availability,
		{
			parameters : $('booking').serialize(),
			onSuccess : function(transport)
			{
				processingAjax = false;
				var data = transport.responseJSON;
				$('hash').value = data.hash;

				updateBoards(data.boards);
				globalRooms = data.stays;
				globalOffers = data.offers;
				updateRoomsAvailability();
			}
		}
	);
}

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;
				$('loading').hide();
				$('otherhotels').update(transport.responseText);
			}
		}
	);

}

function getCalendar(roomcode, boardcode, errortype, calendar)
{
	processingAjax = true;
	$('loading').show();
	$(calendar).update();

	new Ajax.Request
	(
		'/' + hotel_id + '/' + url_calendar,
		{
			parameters :
			{
				roomcode  : roomcode,
				boardcode  : boardcode,
				errortype  : errortype,
				hotelcode  : $F('code'),
				arrival   : $F('arrival'),
				departure : $F('departure')
			},
			onSuccess : function(transport)
			{
				processingAjax = false;
				$('loading').hide();
				$(calendar).update(transport.responseText);
			}
		}
	);

}

function optionsChanged()
{
	$('disponibilidad').hide();
	$('nextstep').hide();
	$('rooms_not_available_txt').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 = newnights > 0 ? newnights : "--";
}

function checkRoomsSelected()
{
	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;
};


/* INIT */
document.observe('dom:loaded', function()
{
	//Validar el formulario booking
	$('booking').onsubmit = checkRoomsSelected;

	displayRooms($('quantity'));

	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()
{
	if(checkRoomsSelected())
	{
		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();

		infoBox.close('room-info');

		if(manyNights())
		{
			$('nights').value = manyNights();
			checkAvailability();
		}
		else
		{
			$('loading').hide();
			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))
	}
}
