$(document).ready(function(){
		
			/*Detalle habitacion cadena*/
			$("a[id^='nombre_habitacion_']").click(function(){
				id = $(this).attr("id");
				id = id.split("_");
				id = id[2];
				if($("#detalle_habitacion_"+id).is(":hidden"))
				{
					$("#detalle_habitacion_"+id).css("display", "");
				}
				else
				{
					$("#detalle_habitacion_"+id).css("display", "none");
				}
				return false;
			});
	
			$('a.lightbox').lightBox();
			$('a.lightbox_hab').lightBox();
			
			$('tr[id^="detalle_habitacion_"]').each(function(){
					$("a[name='"+$(this).attr("id")+"']").lightBox();
			});
			
			$('div[name^="detalle_alojamiento_"]').each(function(){
					$("a[name='"+$(this).attr("name")+"']").lightBox();
			});
			
			tipboxPrecioHPorDia();
			tipboxDisponibilidades();
			
			$('select[name="por_pagina"]').change(function(){
				lugar = document.location;
				lugar = lugar.toString();
				lugar = lugar.replace(/&por_pagina\=[0-9]*/g, "");
				document.location = lugar + "&por_pagina="+$(this).val();
				return false;
			});

			$('select[name="orden_filtro"]').change(function(){
				lugar = document.location;
				lugar = lugar.toString(); 
				lugar = lugar.replace(/&orden_filtro\=[0-9]*/g, "");
				document.location = lugar + "&orden_filtro=" + $(this).val();
				return false;
			});
			
			// EMPIEZA Calendario
			$('.dateSelect_m').attr('readonly', 'readonly');
			$('.dateSelect_m').datepicker({
					numberOfMonths: 2,
					selectOtherMonths: true,
					buttonImage: urlHTTPS+'/imagenes/btn_calendar.gif',
					buttonImageOnly: true,
					showOn: 'both',
					beforeShow: customRange,
					onSelect: setFechaFin
				});
			
			function customRange(input)
				{
					var fechaI;
					var fechaF;
					var picker;
		
					if(input.id == 'fecha_inicio_reserva')
					{
						fechaI = new Date();
						/*fechaF = new Date();
						fechaF.setFullYear(fechaF.getFullYear()+1);
						fechaF.setTime(fechaF.getTime() - (1000*60*60*24));
						picker = $('#fecha_fin').datepicker( "getDate" );
						if(picker && picker < fechaF)
						fechaF = picker;*/
					}
					else
					{
						fechaI = new Date();
						picker = $('#fecha_inicio_reserva').datepicker( "getDate" );			
						if(picker && picker > fechaI)
						fechaI = picker;
						fechaF = new Date();
						fechaF.setFullYear(fechaF.getFullYear()+1);
						fechaF.setTime(fechaF.getTime() - (1000*60*60*24));
					}
					return {minDate: (fechaI), maxDate: (fechaF)};
				} 
				
				function setFechaFin(input) {
						
						var pickerI;
						var pickerF;
						
						if($(this).attr("id") == 'fecha_inicio_reserva')
						{
							pickerI = $('#fecha_inicio_reserva').datepicker( "getDate" );
							pickerF = $('#fecha_fin_reserva').datepicker( "getDate" );
		
							if(!pickerF || pickerI >= pickerF)
							{
								pickerI.setTime(pickerI.getTime() + (1000*60*60*24));
								dia = pickerI.getDate();
								if(dia < 10)
								{
									dia = '0'+dia;
								}
								mes = pickerI.getMonth()+1;
								if(mes < 10)
								{
									mes = '0'+mes;
								}
								$('#fecha_fin_reserva').val(dia+'/'+(mes)+'/'+pickerI.getFullYear());
							}
						}
					}  
				
				$("div[name^='online_booking_'] a").click(function(){
					ids = ((($(this).parent()).attr("name")).toString()).split("_");
					id_alojamiento = ids[2];
					
					if(!($("input[name='precio_total_"+id_alojamiento+"']").val() > 0))
					{
						alert(msgDebeSeleccionarHabitacion);
						return false;
					}
					else
					{
						$("form[id^='frm_reservas_"+id_alojamiento+"_']").submit();
						return false;
					}
					
				});
				
				$("select[name^='pension_']").change(function(){
					ids = (($(this).attr("name")).toString()).split("_");
					id_alojamiento = ids[1];
					id_habitacion = ids[2];
					id_distribucion = ids[3];
					if($("select[name='cantHabitaciones_"+ id_alojamiento+"_"+ id_habitacion+"_"+id_distribucion+"']").val() == 0)
					{
						$("select[name='cantHabitaciones_"+ id_alojamiento+"_"+ id_habitacion+"_"+id_distribucion+"']").val(1);
					}
					
					calcularPrecio(id_alojamiento, id_habitacion, id_distribucion);
				});
				
				$("select[name^='cantHabitaciones_']").change(function(){
					ids = (($(this).attr("name")).toString()).split("_");
					id_alojamiento = ids[1];
					id_habitacion = ids[2];
					id_distribucion = ids[3];
					calcularPrecio(id_alojamiento, id_habitacion, id_distribucion);
				});
				
				function calcularPrecio(id_alojamiento, id_habitacion, id_distribucion)
				{
					cantidad = $("select[name='cantHabitaciones_"+ id_alojamiento+"_"+ id_habitacion+"_"+id_distribucion+"']").val();
					preciosPensiones = $("select[name='pension_"+ id_alojamiento+"_"+ id_habitacion+"_"+id_distribucion+"']").val();
					if(preciosPensiones != null)
					{
						preciosPensiones = (preciosPensiones.toString()).split("_");
						precioPensionesAdultos = preciosPensiones[1];
						precioPensionesNinios = preciosPensiones[2];
					}
					else
					{
						precioPensionesAdultos = 0;
						precioPensionesNinios = 0;
					}
					valor = $("input[name='precioInicial_"+ id_alojamiento+"_"+ id_habitacion+"_"+id_distribucion+"']").val();
					valor = valor.replace(".","");
					valor = valor.replace(",",".");
					precioDistribucion = parseFloat(valor);
					adultos = $("input[name='adultos_"+ id_alojamiento+"_"+ id_habitacion+"_"+id_distribucion+"']").val();
					ninios = $("input[name='ninios_"+ id_alojamiento+"_"+ id_habitacion+"_"+id_distribucion+"']").val();
					
					total = cantidad * precioDistribucion + cantidad * (adultos * precioPensionesAdultos + ninios * precioPensionesNinios);
					$("div[name='pTotalD_"+ id_alojamiento+"_"+ id_habitacion+"_"+id_distribucion+"']").html('<span class="newprice">'+formato_numero(total,2)+' &euro;</span>');
					$("input[name='tarifa_habitacion_"+ id_alojamiento+"_"+ id_habitacion+"_"+id_distribucion+"']").val(total);
					
					calcularTotalesPrecio(id_alojamiento, id_habitacion);
				}
				
				function calcularTotalesPrecio(id_alojamiento, id_habitacion)
				{
					var total = 0;
					$("input[name^='tarifa_habitacion_"+ id_alojamiento+"']").each(function(){
						total += parseFloat($(this).val());
					});
					$("span[name='pTotal_"+ id_alojamiento+"']").html(formato_numero(total,2)+' &euro;');
					$("input[name='precio_total_"+ id_alojamiento+"']").val(total);
				}
			});
			
			
			/*
				 * jQuery Tooltip plugin 1.2
				 *
				 * http://bassistance.de/jquery-plugins/jquery-plugin-tooltip/
				 * http://docs.jquery.com/Plugins/Tooltip
				 *
				 * Copyright (c) 2006 - 2008 Jörn Zaefferer
				 *
				 * $Id: scripts.js,v 1.14 2010-07-12 14:50:57 sordone Exp $
				 * 
				 * Dual licensed under the MIT and GPL licenses:
				 *   http://www.opensource.org/licenses/mit-license.php
				 *   http://www.gnu.org/licenses/gpl.html
				 */
				 
				;(function($) {
					
						// the tooltip element
					var helper = {},
						// the current tooltipped element
						current,
						// the title of the current element, used for restoring
						title,
						// timeout id for delayed tooltips
						tID,
						// IE 5.5 or 6
						IE = $.browser.msie && /MSIE\s(5\.5|6\.)/.test(navigator.userAgent),
						// flag for mouse tracking
						track = false;
					
					$.tooltip = {
						blocked: false,
						defaults: {
							delay: 200,
							showURL: true,
							extraClass: "",
							top: 15,
							left: 15,
							id: "tooltip"
						},
						block: function() {
							$.tooltip.blocked = !$.tooltip.blocked;
						}
					};
					
					$.fn.extend({
						tooltip: function(settings) {
							settings = $.extend({}, $.tooltip.defaults, settings);
							createHelper(settings);
							return this.each(function() {
									$.data(this, "tooltip-settings", settings);
									// copy tooltip into its own expando and remove the title
									this.tooltipText = this.title;
									$(this).removeAttr("title");
									// also remove alt attribute to prevent default tooltip in IE
									this.alt = "";
								})
								.hover(save, hide)
								.click(hide);
						},
						fixPNG: IE ? function() {
							return this.each(function () {
								var image = $(this).css('backgroundImage');
								if (image.match(/^url\(["']?(.*\.png)["']?\)$/i)) {
									image = RegExp.$1;
									$(this).css({
										'backgroundImage': 'none',
										'filter': "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, sizingMethod=crop, src='" + image + "')"
									}).each(function () {
										var position = $(this).css('position');
										if (position != 'absolute' && position != 'relative')
											$(this).css('position', 'relative');
									});
								}
							});
						} : function() { return this; },
						unfixPNG: IE ? function() {
							return this.each(function () {
								$(this).css({'filter': '', backgroundImage: ''});
							});
						} : function() { return this; },
						hideWhenEmpty: function() {
							return this.each(function() {
								$(this)[ $(this).html() ? "show" : "hide" ]();
							});
						},
						url: function() {
							return this.attr('href') || this.attr('src');
						}
					});
					
					function createHelper(settings) {
						// there can be only one tooltip helper
						if( helper.parent )
							return;
						// create the helper, h3 for title, div for url
						helper.parent = $('<div id="' + settings.id + '"><h3></h3><div class="body"></div><div class="url"></div></div>')
							// add to document
							.appendTo(document.body)
							// hide it at first
							.hide();
							
						// apply bgiframe if available
						if ( $.fn.bgiframe )
							helper.parent.bgiframe();
						
						// save references to title and url elements
						helper.title = $('h3', helper.parent);
						helper.body = $('div.body', helper.parent);
						helper.url = $('div.url', helper.parent);
					}
					
					function settings(element) {
						return $.data(element, "tooltip-settings");
					}
					
					// main event handler to start showing tooltips
					function handle(event) {
						// show helper, either with timeout or on instant
						if( settings(this).delay )
							tID = setTimeout(show, settings(this).delay);
						else
							show();
						
						// if selected, update the helper position when the mouse moves
						track = !!settings(this).track;
						$(document.body).bind('mousemove', update);
							
						// update at least once
						update(event);
					}
					
					// save elements title before the tooltip is displayed
					function save() {
						// if this is the current source, or it has no title (occurs with click event), stop
						if ( $.tooltip.blocked || this == current || (!this.tooltipText && !settings(this).bodyHandler) )
							return;
				
						// save current
						current = this;
						title = this.tooltipText;
						
						if ( settings(this).bodyHandler ) {
							helper.title.hide();
							var bodyContent = settings(this).bodyHandler.call(this);
							if (bodyContent.nodeType || bodyContent.jquery) {
								helper.body.empty().append(bodyContent)
							} else {
								helper.body.html( bodyContent );
							}
							helper.body.show();
						} else if ( settings(this).showBody ) {
							var parts = title.split(settings(this).showBody);
							helper.title.html(parts.shift()).show();
							helper.body.empty();
							for(var i = 0, part; part = parts[i]; i++) {
								if(i > 0)
									helper.body.append("<br/>");
								helper.body.append(part);
							}
							helper.body.hideWhenEmpty();
						} else {
							helper.title.html(title).show();
							helper.body.hide();
						}
						
						// if element has href or src, add and show it, otherwise hide it
						if( settings(this).showURL && $(this).url() )
							helper.url.html( $(this).url().replace('http://', '') ).show();
						else 
							helper.url.hide();
						
						// add an optional class for this tip
						helper.parent.addClass(settings(this).extraClass);
				
						// fix PNG background for IE
						if (settings(this).fixPNG )
							helper.parent.fixPNG();
							
						handle.apply(this, arguments);
					}
					
					// delete timeout and show helper
					function show() {
						tID = null;
						helper.parent.show();
						update();
					}
					
					/**
					 * callback for mousemove
					 * updates the helper position
					 * removes itself when no current element
					 */
					function update(event)	{
						if($.tooltip.blocked)
							return;
						
						// stop updating when tracking is disabled and the tooltip is visible
						if ( !track && helper.parent.is(":visible")) {
							$(document.body).unbind('mousemove', update)
						}
						
						// if no current element is available, remove this listener
						if( current == null ) {
							$(document.body).unbind('mousemove', update);
							return;	
						}
						
						// remove position helper classes
						helper.parent.removeClass("viewport-right").removeClass("viewport-bottom");
						
						var left = helper.parent[0].offsetLeft;
						var top = helper.parent[0].offsetTop;
						if(event) {
							// position the helper 15 pixel to bottom right, starting from mouse position
							left = event.pageX + settings(current).left;
							top = event.pageY + settings(current).top;
							helper.parent.css({
								left: left + 'px',
								top: top + 'px'
							});
						}
						
						var v = viewport(),
							h = helper.parent[0];
						// check horizontal position
						if(v.x + v.cx < h.offsetLeft + h.offsetWidth) {
							left -= h.offsetWidth + 20 + settings(current).left;
							helper.parent.css({left: left + 'px'}).addClass("viewport-right");
						}
						// check vertical position
						if(v.y + v.cy < h.offsetTop + h.offsetHeight) {
							top -= h.offsetHeight + 20 + settings(current).top;
							helper.parent.css({top: top + 'px'}).addClass("viewport-bottom");
						}
					}
					
					function viewport() {
						return {
							x: $(window).scrollLeft(),
							y: $(window).scrollTop(),
							cx: $(window).width(),
							cy: $(window).height()
						};
					}
					
					// hide helper and restore added classes and the title
					function hide(event) {
						if($.tooltip.blocked)
							return;
						// clear timeout if possible
						if(tID)
							clearTimeout(tID);
						// no more current element
						current = null;
						
						helper.parent.hide().removeClass( settings(this).extraClass );
						
						if( settings(this).fixPNG )
							helper.parent.unfixPNG();
					}
					
					$.fn.Tooltip = $.fn.tooltip;
					
				})(jQuery);
				
				function tipboxPrecioUnaHPorDia(id_alojamiento, id_habitacion, id_distribucion)
				{
					/*Listado*/
					valor = ($('*[name="pTotalH_'+id_alojamiento+'_'+id_habitacion+'"]').find("span.newprice")).html();
					if(valor)
					{
						valor = valor.replace(".","");
						valor = valor.replace(",",".");
						valor = parseFloat(valor);
						$('*[name="pTotalH_'+id_alojamiento+'_'+id_habitacion+'"]').tipbox(formato_numero((valor/noches),2)+' € '+msgPrecioPromedioH, 1);
					}
					
					/*Detalle*/
					valor = ($('*[name="pTotalD_'+ id_alojamiento+'_'+id_habitacion+'_'+id_distribucion+'"]').find("span.newprice")).html();
					if(valor)
					{
						valor = valor.replace(".","");
						valor = valor.replace(",",".");
						valor = parseFloat(valor);
						$('*[name="pTotalD_'+ id_alojamiento+'_'+id_habitacion+'_'+id_distribucion+'"]').tipbox(formato_numero((valor/noches),2)+' € '+msgPrecioPromedioH, 1);
					}
				}

				function tipboxPrecioHPorDia()
				{
					/*Listado*/
					$("*[name^='pTotalH_']").each(function(){
									
						id = $(this).attr("name");
						id = id.split("_");
						id_alojamiento = parseInt(id[1]);
						id_habitacion = parseInt(id[2]);
						
						tipboxPrecioUnaHPorDia(id_alojamiento, id_habitacion, 0)
						
					});
					
					/*Detalle*/
					$("*[name^='pTotalD_']").each(function(){
									
						id = $(this).attr("name");
						id = id.split("_");
						id_alojamiento = parseInt(id[1]);
						id_habitacion = parseInt(id[2]);
						id_distribucion = parseInt(id[3]);
						
						tipboxPrecioUnaHPorDia(id_alojamiento, id_habitacion, id_distribucion)
						
					});
				}

				
				function tipboxDisponibilidad(id_alojamiento, id_habitacion, disponibilidad)
				{
					/*Listado*/
					valor = ($('*[name="pTotalH_'+id_alojamiento+'_'+id_habitacion+'"]').find("span.newprice")).html();

					if(valor)
					{
						valor = valor.replace(".","");
						valor = valor.replace(",",".");
						valor = parseFloat(valor);
						$('*[name="tbDisponibilidad_'+id_alojamiento+'_'+id_habitacion+'_'+disponibilidad+'"]').tipbox(msgDisponibilidad1+' '+disponibilidad+' '+msgDisponibilidad2+' '+formato_numero(valor,2)+' € '+msgDisponibilidad3, 1);
					}
					
					/*Detalle*/
					valor = ($('*[name^="pTotalD_'+ id_alojamiento+'_'+id_habitacion+'"]').find("span.newprice")).html();
					if(valor)
					{
						valor = valor.replace(".","");
						valor = valor.replace(",",".");
						valor = parseFloat(valor);
						$('*[name="tbDisponibilidad_'+ id_alojamiento+'_'+id_habitacion+'_'+disponibilidad+'"]').tipbox(msgDisponibilidad1+' '+disponibilidad+' '+msgDisponibilidad2+' '+formato_numero(valor,2)+' € '+msgDisponibilidad3, 1);
					}
				}
			
				function tipboxDisponibilidades()
				{
					/*Listado/Detalle*/
					$("*[name^='tbDisponibilidad_']").each(function(){
									
						id = $(this).attr("name");
						id = id.split("_");
						id_alojamiento = parseInt(id[1]);
						id_habitacion = parseInt(id[2]);
						disponibilidad = parseInt(id[3]);
						
						tipboxDisponibilidad(id_alojamiento, id_habitacion, disponibilidad)
						
					});
				}
				
			function formato_numero(pnumber,decimals){
				separadorDecimales = ",";
				separadorMiles = ".";
				
				pnumber = parseFloat(pnumber);
				pnumber = pnumber.toFixed(decimals);
			
				var snum = new String(pnumber);
				var sec = snum.split('.');
				var parteEntera = sec[0];
				var parteDecimal = sec[1];
				
				retorno = "";
				j = 1;
				for(i=(parteEntera.length - 1); i>= 0; i--)
				{
					retorno = parteEntera.charAt(i) + retorno;
					if(j == 3 && i > 0)
					{
						retorno = separadorMiles + retorno;
						j = 1;
					}
					else
					{
						j++;
					}
				}
				retorno = retorno + separadorDecimales + parteDecimal;
				return retorno;
			}