/* lightbox*/
(function($){$.fn.lightBox=function(settings){settings=jQuery.extend({overlayBgColor:'#000',overlayOpacity:0.8,fixedNavigation:false,imageLoading:urlHTTPS+'/imagenes/lightbox-ico-loading.gif',imageBtnPrev:urlHTTPS+'/imagenes/lightbox-btn-prev.gif',imageBtnNext:urlHTTPS+'/imagenes/lightbox-btn-next.gif',imageBtnClose:urlHTTPS+'/imagenes/lightbox-btn-close.gif',imageBlank:urlHTTPS+'/imagenes/lightbox-blank.gif',containerBorderSize:10,containerResizeSpeed:400,txtImage:'Image',txtOf:'of',keyToClose:'c',keyToPrev:'p',keyToNext:'n',imageArray:[],activeImage:0},settings);var jQueryMatchedObj=this;function _initialize(){_start(this,jQueryMatchedObj);return false;}
function _start(objClicked,jQueryMatchedObj){$('embed, object, select').css({'visibility':'hidden'});_set_interface();settings.imageArray.length=0;settings.activeImage=0;if(jQueryMatchedObj.length==1){settings.imageArray.push(new Array(objClicked.getAttribute('href'),objClicked.getAttribute('title')));}else{for(var i=0;i<jQueryMatchedObj.length;i++){settings.imageArray.push(new Array(jQueryMatchedObj[i].getAttribute('href'),jQueryMatchedObj[i].getAttribute('title')));}}
while(settings.imageArray[settings.activeImage][0]!=objClicked.getAttribute('href')){settings.activeImage++;}
_set_image_to_view();}
function _set_interface(){$('body').append('<div id="jquery-overlay"></div><div id="jquery-lightbox"><div id="lightbox-container-image-box"><div id="lightbox-container-image"><img id="lightbox-image"><div style="" id="lightbox-nav"><a href="#" id="lightbox-nav-btnPrev"></a><a href="#" id="lightbox-nav-btnNext"></a></div><div id="lightbox-loading"><a href="#" id="lightbox-loading-link"><img src="'+settings.imageLoading+'"></a></div></div></div><div id="lightbox-container-image-data-box"><div id="lightbox-container-image-data"><div id="lightbox-image-details"><span id="lightbox-image-details-caption"></span><span id="lightbox-image-details-currentNumber"></span></div><div id="lightbox-secNav"><a href="#" id="lightbox-secNav-btnClose"><img src="'+settings.imageBtnClose+'"></a></div></div></div></div>');var arrPageSizes=___getPageSize();$('#jquery-overlay').css({backgroundColor:settings.overlayBgColor,opacity:settings.overlayOpacity,width:arrPageSizes[0],height:arrPageSizes[1]}).fadeIn();var arrPageScroll=___getPageScroll();$('#jquery-lightbox').css({top:arrPageScroll[1]+(arrPageSizes[3]/10),left:arrPageScroll[0]}).show();$('#jquery-overlay,#jquery-lightbox').click(function(){_finish();});$('#lightbox-loading-link,#lightbox-secNav-btnClose').click(function(){_finish();return false;});$(window).resize(function(){var arrPageSizes=___getPageSize();$('#jquery-overlay').css({width:arrPageSizes[0],height:arrPageSizes[1]});var arrPageScroll=___getPageScroll();$('#jquery-lightbox').css({top:arrPageScroll[1]+(arrPageSizes[3]/10),left:arrPageScroll[0]});});}
function _set_image_to_view(){$('#lightbox-loading').show();if(settings.fixedNavigation){$('#lightbox-image,#lightbox-container-image-data-box,#lightbox-image-details-currentNumber').hide();}else{$('#lightbox-image,#lightbox-nav,#lightbox-nav-btnPrev,#lightbox-nav-btnNext,#lightbox-container-image-data-box,#lightbox-image-details-currentNumber').hide();}
var objImagePreloader=new Image();objImagePreloader.onload=function(){$('#lightbox-image').attr('src',settings.imageArray[settings.activeImage][0]);_resize_container_image_box(objImagePreloader.width,objImagePreloader.height);objImagePreloader.onload=function(){};};objImagePreloader.src=settings.imageArray[settings.activeImage][0];};function _resize_container_image_box(intImageWidth,intImageHeight){var intCurrentWidth=$('#lightbox-container-image-box').width();var intCurrentHeight=$('#lightbox-container-image-box').height();var intWidth=(intImageWidth+(settings.containerBorderSize*2));var intHeight=(intImageHeight+(settings.containerBorderSize*2));var intDiffW=intCurrentWidth-intWidth;var intDiffH=intCurrentHeight-intHeight;$('#lightbox-container-image-box').animate({width:intWidth,height:intHeight},settings.containerResizeSpeed,function(){_show_image();});if((intDiffW==0)&&(intDiffH==0)){if($.browser.msie){___pause(250);}else{___pause(100);}}
$('#lightbox-container-image-data-box').css({width:intImageWidth});$('#lightbox-nav-btnPrev,#lightbox-nav-btnNext').css({height:intImageHeight+(settings.containerBorderSize*2)});};function _show_image(){$('#lightbox-loading').hide();$('#lightbox-image').fadeIn(function(){_show_image_data();_set_navigation();});_preload_neighbor_images();};function _show_image_data(){$('#lightbox-container-image-data-box').slideDown('fast');$('#lightbox-image-details-caption').hide();if(settings.imageArray[settings.activeImage][1]){$('#lightbox-image-details-caption').html(settings.imageArray[settings.activeImage][1]).show();}
if(settings.imageArray.length>1){$('#lightbox-image-details-currentNumber').html(settings.txtImage+' '+(settings.activeImage+1)+' '+settings.txtOf+' '+settings.imageArray.length).show();}}
function _set_navigation(){$('#lightbox-nav').show();$('#lightbox-nav-btnPrev,#lightbox-nav-btnNext').css({'background':'transparent url('+settings.imageBlank+') no-repeat'});if(settings.activeImage!=0){if(settings.fixedNavigation){$('#lightbox-nav-btnPrev').css({'background':'url('+settings.imageBtnPrev+') left 15% no-repeat'}).unbind().bind('click',function(){settings.activeImage=settings.activeImage-1;_set_image_to_view();return false;});}else{$('#lightbox-nav-btnPrev').unbind().hover(function(){$(this).css({'background':'url('+settings.imageBtnPrev+') left 15% no-repeat'});},function(){$(this).css({'background':'transparent url('+settings.imageBlank+') no-repeat'});}).show().bind('click',function(){settings.activeImage=settings.activeImage-1;_set_image_to_view();return false;});}}
if(settings.activeImage!=(settings.imageArray.length-1)){if(settings.fixedNavigation){$('#lightbox-nav-btnNext').css({'background':'url('+settings.imageBtnNext+') right 15% no-repeat'}).unbind().bind('click',function(){settings.activeImage=settings.activeImage+1;_set_image_to_view();return false;});}else{$('#lightbox-nav-btnNext').unbind().hover(function(){$(this).css({'background':'url('+settings.imageBtnNext+') right 15% no-repeat'});},function(){$(this).css({'background':'transparent url('+settings.imageBlank+') no-repeat'});}).show().bind('click',function(){settings.activeImage=settings.activeImage+1;_set_image_to_view();return false;});}}
_enable_keyboard_navigation();}
function _enable_keyboard_navigation(){$(document).keydown(function(objEvent){_keyboard_action(objEvent);});}
function _disable_keyboard_navigation(){$(document).unbind();}
function _keyboard_action(objEvent){if(objEvent==null){keycode=event.keyCode;escapeKey=27;}else{keycode=objEvent.keyCode;escapeKey=objEvent.DOM_VK_ESCAPE;}
key=String.fromCharCode(keycode).toLowerCase();if((key==settings.keyToClose)||(key=='x')||(keycode==escapeKey)){_finish();}
if((key==settings.keyToPrev)||(keycode==37)){if(settings.activeImage!=0){settings.activeImage=settings.activeImage-1;_set_image_to_view();_disable_keyboard_navigation();}}
if((key==settings.keyToNext)||(keycode==39)){if(settings.activeImage!=(settings.imageArray.length-1)){settings.activeImage=settings.activeImage+1;_set_image_to_view();_disable_keyboard_navigation();}}}
function _preload_neighbor_images(){if((settings.imageArray.length-1)>settings.activeImage){objNext=new Image();objNext.src=settings.imageArray[settings.activeImage+1][0];}
if(settings.activeImage>0){objPrev=new Image();objPrev.src=settings.imageArray[settings.activeImage-1][0];}}
function _finish(){$('#jquery-lightbox').remove();$('#jquery-overlay').fadeOut(function(){$('#jquery-overlay').remove();});$('embed, object, select').css({'visibility':'visible'});}
function ___getPageSize(){var xScroll,yScroll;if(window.innerHeight&&window.scrollMaxY){xScroll=window.innerWidth+window.scrollMaxX;yScroll=window.innerHeight+window.scrollMaxY;}else if(document.body.scrollHeight>document.body.offsetHeight){xScroll=document.body.scrollWidth;yScroll=document.body.scrollHeight;}else{xScroll=document.body.offsetWidth;yScroll=document.body.offsetHeight;}
var windowWidth,windowHeight;if(self.innerHeight){if(document.documentElement.clientWidth){windowWidth=document.documentElement.clientWidth;}else{windowWidth=self.innerWidth;}
windowHeight=self.innerHeight;}else if(document.documentElement&&document.documentElement.clientHeight){windowWidth=document.documentElement.clientWidth;windowHeight=document.documentElement.clientHeight;}else if(document.body){windowWidth=document.body.clientWidth;windowHeight=document.body.clientHeight;}
if(yScroll<windowHeight){pageHeight=windowHeight;}else{pageHeight=yScroll;}
if(xScroll<windowWidth){pageWidth=xScroll;}else{pageWidth=windowWidth;}
arrayPageSize=new Array(pageWidth,pageHeight,windowWidth,windowHeight);return arrayPageSize;};function ___getPageScroll(){var xScroll,yScroll;if(self.pageYOffset){yScroll=self.pageYOffset;xScroll=self.pageXOffset;}else if(document.documentElement&&document.documentElement.scrollTop){yScroll=document.documentElement.scrollTop;xScroll=document.documentElement.scrollLeft;}else if(document.body){yScroll=document.body.scrollTop;xScroll=document.body.scrollLeft;}
arrayPageScroll=new Array(xScroll,yScroll);return arrayPageScroll;};function ___pause(ms){var date=new Date();curDate=null;do{var curDate=new Date();}
while(curDate-date<ms);};return this.unbind('click').click(_initialize);};})(jQuery);

/*Fin lightbox*/
$(document).ready(function(){	 
	
	// EMPIEZA Calendario
		$('.dateSelect_m').attr('readonly', 'readonly');
		$('.dateSelect_m').attachDatepicker({
			firstDay: 1,
			buttonText: msgButtonText,
			buttonImage: urlHTTPS+'/imagenes/btn_calendar.gif',
			buttonImageOnly: true,
			showOn: 'both',
			beforeShow: customRange_reserva,
			onSelect: setFechaFinReserva
		});


		// Customize two date pickers to work as a date range 
		function customRange_reserva(input)
		{
			var fechaI;
			var fechaF;
			var picker;

			if(input.id == 'fecha_inicio')
			{
				fechaI = new Date();
				fechaF = new Date();
				fechaF.setFullYear(fechaF.getFullYear()+1);
				fechaF.setTime(fechaF.getTime() - (1000*60*60*24));
				picker = $('#fecha_fin').getDatepickerDate();
				if(picker && picker < fechaF)
				fechaF = picker;
			}
			else
			{
				fechaI = new Date();
				picker = $('#fecha_inicio').getDatepickerDate();			
				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 setFechaFinReserva(input) {
				
				var pickerI;
				var pickerF;
				
				if($(this).attr("id") == 'fecha_inicio')
				{
					pickerI = $('#fecha_inicio').getDatepickerDate();
					pickerF = $('#fecha_fin').getDatepickerDate();

					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').val(dia+'/'+(mes)+'/'+pickerI.getFullYear());
					}
				}
			} 
			
		// TERMINA Calendario

		$('#modificar_fechas').click(function(){
			if($('#modificar_fechas_div').is(':hidden'))
				$('#modificar_fechas_div').slideDown();
			else
				$('#modificar_fechas_div').slideUp();

			return false;
		});

		$('#cambiar_fecha').click(function(){		
			$('#frm_cambiar_fecha').submit();
			return false;
		});
		
	$("select[name^=cantHabitaciones_], select[name^=pension_]").change(function(){
		
		reg = ($(this).attr('name')).split("_");
		if(reg)
		{
			if(reg[0] == "pension")
			{
				if(! ($("select[name=cantHabitaciones_"+(reg[1])+"_"+(reg[2])+"_"+(reg[3])+"]").val() > 0))
				{
					$("select[name=cantHabitaciones_"+(reg[1])+"_"+(reg[2])+"_"+(reg[3])+"]").val("1");
				}
			}
		}
		
		calcularPrecios(reg[1], reg[2], reg[3]);
	});
	
	$("a[name='continuar']").click(function(){
		//Precio total > 0 reservo algo
		if($("input[name='precio_total']").val() > 0)
		{
			$("#form_continuar").attr("action",urlHTTPS+"/index.php?modul=booking&action=paso2");
			$("#form_continuar").submit();
			return false;
		}
		else
		{
			alert(msgDebeSelHab);
			return false;
		}
	});
	
	$("a[name='search']").click(function(){

		$("#form_search").submit();
		return false;
	});
	
	$("a[name='continuar2']").click(function(){
		$("select[name^='id_servicio_']").each(function(){
			if($(this).attr("disabled"))
			{
				$(this).attr("disabled", false);
			}
		});
		$("#form_continuar").submit();
		return false;
	});
	
	//Paso 2
	$('select[name^=id_servicio_]').change(function(){
		/*
			Evento del selector de  cantidad de un servicio
			Existe id_servicio_dia por eso diferencia con match
			Hay ciertas restricciones que cambian o no el selector de dias
			Se calcula el total del servicio
			Se actualizael total (sumar parciales)
		*/
		var reg = /id_servicio_(\d+)/;
		reg = $(this).attr('name').match(reg);
		if(reg)
		{
			var idS = parseInt(reg[1]);
			/*
			var dias = new Array();
			jQuery.each(tarifas['desc'], function(key, value){
				dias.push(parseInt(key));
			});
			*/

			if((!$('select[name="id_servicio_'+idS+'"]').attr("disabled"))
					&& (!$('select[name="id_servicio_dia_'+idS+'"]').attr("disabled")))
			{
				if($(this).val() == 0)
				{
					$('select[name="id_servicio_dia_'+idS+'"] option:eq(0)').attr("selected","selected");
				}
				else
				{
					if($('select[name="id_servicio_dia_'+idS+'"]').val() == 0)
					{
						$('select[name="id_servicio_dia_'+idS+'"] option:eq(1)').attr("selected","selected");
					}
				}
			}
			
			calcularPrecioServicios(vIdAlojamiento);
			//var total = parseFloat(tarifas['serv'][idS]['tarifa']) * parseInt($(this).val())  * parseInt($('select[name="id_servicio_dia_'+idS+'"]').val());
			
			//$('span[name=precio_servicio_'+idS+']').html(total.toFixed(2));
			
		}
	});
	
	$('select[name^=id_servicio_dia_]').change(function()
	{
		/*
			Evento del selector de días de servicio
			Segun el caso debe actualizar selector de cantidad (en gral si esta en 0)
			Hace llamado a selector de cantidad para actualizar totales.
		*/
		idS = ($(this).attr("name")).split("_");
		idS = idS[3];
			
		if(!$('select[name="id_servicio_'+idS+'"]').attr("disabled"))
		{
			
			if($(this).val() == 0)
			{
				
					$('select[name="id_servicio_'+idS+'"] option:eq(0)').attr("selected","selected");
			}
			else
			{
				if($('select[name="id_servicio_'+idS+'"]').val() == 0)
				{
					$('select[name="id_servicio_'+idS+'"] option:eq(1)').attr("selected","selected");
				}
			}
		}
		$('select[name="id_servicio_'+idS+'"]').change();
	});
	
	jQuery.validator.addMethod("caducidadTarjetaValida", function(value, element) { 
		if('AE' == $('#cardtype').val())
		{
			VNT = VCT = true;
		}
		else
		{
			VNT = validarNroTarjeta();
			VCT = validarCaducidad();
		}						
		if(!VCT)
		{
			return false;
		}
		else
		{
			return true;
		}
	}, msgFechaCaducidadNoValida);
	
	jQuery.validator.addMethod("nroTarjetaValida", function(value, element) { 
		if('AE' == $('#cardtype').val())
		{
			VNT = VCT = true;
		}
		else
		{
			VNT = validarNroTarjeta();
			VCT = validarCaducidad();
		}						
		
		if (!VNT)
		{
			return false;
		}
		else
		{
			return true;
		}
		
	}, msgNroTarjetaNoValido);
	
	$('#frm_reserva').validate({
		rules: {	
			nombre:"required",
			telefono:"required",							
			email: {
				required: true,
				email: true
			},
			email2: {
				required: true,
				email: true,
				equalTo: "[name='email']"
			},
			cardnumber:{ number:true, required:true},
			cardnumber:"nroTarjetaValida",
			expcard_anio:"caducidadTarjetaValida",
			cvc:"required"
		}
	});
	
	
	$("#finalizar").click(function(){	
	
		if($("#terminos").is(':checked'))
		{
			$('#frm_reserva').submit();
		}
		else
		{
			alert(msgDebeAceptarCondiciones);
		}
		return false;
	});
	
	$("#volver_paso3").click(function(){	
		history.go(-1);
		return false;
	});
	
	$('#pop_cond_reservas').easydrag();
	
	$('#close_pop_cond_reservas').click(function()
	{
		$("#pop_cond_reservas").hide();
		return false;
	});	
	
	$("a[name='ver_cvc']").click(function()
	{
		
		$("#pop_cond_reservas").css("left",parseInt($(window).scrollLeft() + ($(window).width()/2)) - 350);
		$("#pop_cond_reservas").css("top", parseInt($(window).scrollTop() + ($(window).height()/2) - 280));
		
		$.ajax({
		   type: "POST",
		   url: urlHTTPS+"/index.php",
		   data: "modul=contenido&action=getContenidoPopUp&id=18",
		   success: function(msg){
				$("div.pop_cond_reservas_Txt").html(msg);
				$("#titulo_popup").html(""+msgTitleCvc);
				$("#pop_cond_reservas").show();
		   }
		 });
	 
		// /index.php?modul=contenido&action=popup&id=19
		
		
		return false;
	});
	
});

// idA: id Alojamiento
// idH: id Habitacion
function calcularPrecios(idA, idH, idDis)
{
	var tarifas;
	/*
	FORMATO DEL ARREGLO
	tarifasIdAlojamiento = 
	{"habi":
	{"70": //id_habitacion
		{"80"://id_distribucion                                           dia   tarifa
			{"adultos":"3","ninios":"0","disponibilidad":"10","tarifas":{"172":"75","173":"75","174":"75","175":"75","176":"75","177":"75"}},
		"82":
			{"adultos":"4","ninios":"0","disponibilidad":"10","tarifas":{"172":"79","173":"79","174":"79","175":"79","176":"79","177":"79"}},
		"258":
			{"adultos":"2","ninios":"0","disponibilidad":"10","tarifas":{"172":"71","173":"71","174":"71","175":"71","176":"71","177":"71"}}
	},
	
	"desc":
	{"172":
		{"id":"0","tipo":"0","desc":"0"},
	"173":{"id":"0","tipo":"0","desc":"0"},
	"174":{"id":"31","tipo":"3","desc":"10.00"},
	
	"pens":{
		"57":{"inc":"0","tipo":"0","nombre":"Solo alojamiento","tarifa":"0.00","tarifa_adultos":"0.00","tarifa_menores":"0.00"},
		"18":{"inc":"0","tipo":"0","nombre":"Desayuno","tarifa":"0.00","tarifa_adultos":"0.00","tarifa_menores":"0.00"},
	*/
	eval("tarifas = tarifas"+idA+";");

    tarifas['desc']; 
	tarifas['pens']; 
	tarifas['habi']; 

	var pension = $('select[name=pension_'+idA+'_'+idH+'_'+idDis+']');
	if(pension.length && pension.length == 1)
	{
		pension = parseInt(pension.val());
	}
	else
	{
		pension = null;
	}
	
	var cantHab = $('select[name=cantHabitaciones_'+idA+'_'+idH+'_'+idDis+']');
	if(cantHab.length && cantHab.length == 1)
	{
		cantHab = parseInt(cantHab.val());
	}
	else
	{
		cantHab = null;
	}
		
	if(cantHab != null)
	{
		var total = 0;
		var totalSinDesc = 0;

		if(cantHab > 0)
		{
			var masEconomico = 0;

			jQuery.each(tarifas['desc'], function(key, value){
				key = parseInt(key);
				var subTotal = 0;
				var pensionHoy = 0;
				if(pension != null && parseInt(tarifas['pens'][pension]['inc']) == 1)
				{
					adultos = parseFloat(tarifas['habi'][idH][idDis]["adultos"]) * cantHab;
					ninios = parseFloat(tarifas['habi'][idH][idDis]["ninios"]) * cantHab;
					var pensionHoy = parseFloat(tarifas['pens'][pension]['tarifa_adultos']) * adultos + parseFloat(tarifas['pens'][pension]['tarifa_menores']) * ninios;
					
				}
				
				//switch(tarifas['desc'][key]['tipo'])
				switch(parseInt(value['tipo']))
				{
					case 1: // Descuento en el precio final
						subTotal = parseFloat(tarifas['habi'][idH][idDis]["tarifas"][key]) * cantHab;
						subTotal = subTotal + pensionHoy;
						subTotal = subTotal * ( (100 - parseFloat(value['desc'])) / 100 );
						break;
					case 2: // Y descuento en el precio final sin servicios.
						subTotal = parseFloat(tarifas['habi'][idH][idDis]["tarifas"][key]) * cantHab;
						subTotal = subTotal * ( (100 - parseFloat(value['desc'])) / 100 );
						subTotal = subTotal + pensionHoy;
						break;
					case 3: // Descuento en el último día.
						if(tarifas['desc'][key+1] == undefined || tarifas['desc'][key+1]['id'] != value['id'])
						{
							subTotal = parseFloat(tarifas['habi'][idH][idDis]["tarifas"][key]) * cantHab;
							subTotal = subTotal + pensionHoy;
							subTotal = subTotal * ( (100 - parseFloat(value['desc'])) / 100 );
						}
						else
						{
							subTotal = parseFloat(tarifas['habi'][idH][idDis]["tarifas"][key]) * cantHab;
							subTotal = subTotal + pensionHoy;
						}
						break;
					case 4: // Descuento en el día más economico.
						if(tarifas['desc'][key-1] == undefined
						|| !masEconomico
						|| costoDelDia(idA, idH, key, cantHab) <= costoDelDia(idA, idH, masEconomico, cantHab))
							masEconomico = key;

						subTotal = parseFloat(tarifas['habi'][idH][idDis]["tarifas"][key]) * cantHab;
						subTotal = subTotal + pensionHoy;

						if(tarifas['desc'][key+1] == undefined || tarifas['desc'][key+1]['id'] != value['id'])
						{
							if(masEconomico == key)
								subTotal = subTotal * ( (100 - parseFloat(value['desc'])) / 100 );
							else
							{
								var aux = costoDelDia(idA, idH, masEconomico, cantHab);
								total = total - aux;
								aux = aux * ( (100 - parseFloat(tarifas['desc'][masEconomico]['desc'])) / 100 );
								total = total + aux;
							}
							masEconomico = 0;
						}
						break;
					case 5: // Servicios adicionales.
						subTotal = parseFloat(tarifas['habi'][idH][idDis]["tarifas"][key]) * cantHab;
						if(pension != null && jQuery.inArray(pension, value['desc']) == -1)
							subTotal = subTotal + pensionHoy;
						break;
					default:
						subTotal = parseFloat(tarifas['habi'][idH][idDis]["tarifas"][key]) * cantHab;
						subTotal = subTotal + pensionHoy;
						break;
				}
				total = total + subTotal;
				totalSinDesc = totalSinDesc + (parseFloat(tarifas['habi'][idH][idDis]["tarifas"][key]) * cantHab) + pensionHoy;
			});
		}
		total = parseFloat(total);
		//pTH = $('#tarifa_habitacion_'+idA+'_'+idH+'_'+idDis).html(total.toFixed(2));
		
		$('input[name=tarifa_habitacion_'+idA+'_'+idH+'_'+idDis+']').val(total.toFixed(2));
		$('#tarifa_habitacion_'+idA+'_'+idH+'_'+idDis+'').html((total/noches).toFixed(2));
		/*
		if($(pTH).find('span.old').length)
			$(pTH).find('span.old').html((totalSinDesc.toFixed(2)) + " &euro;");
*/
		total = 0;
		$('input[name^=tarifa_habitacion_'+idA+'_]').each(function(){
																   
			total = total + parseFloat($(this).val());
		});

		total = total.toFixed(2);
		
		$("#precio_total").html(total);
		$("input[name='precio_total']").val(total);
		
	}
}

function calcularPrecioServicios(idA)
{
	total_servicio = 0;
	$('input[name^=tarifa_servicio_'+idA+'_]').each(function(){
		id_servicio = ($(this).attr("name")).split("_");	
		id_servicio = id_servicio[3];
		total_servicio = total_servicio + (parseFloat($(this).val()) * $('#id_servicio_'+id_servicio).val() * $('#id_servicio_dia_'+id_servicio).val());
	});
	$('#total_servicios').html(total_servicio.toFixed(2));
	$('#total').html((parseFloat($('#total_servicios').html()) + parseFloat($('#total_habitaciones').html())).toFixed(2));
}

function costoDelDia(idA, idH, dia, cantH)
{
	var tarifas;
	eval("tarifas = tarifas"+idA+";");

	var retorno = 0;

	var pension = $('select[name=pension_'+idA+'_'+idH+']');
	if(pension.length && pension.length == 1)
		pension = parseInt(pension.val());
	else
		pension = null;

	var pensionHoy = parseFloat('0.00');
	if(pension != null && !tarifas['pens'][pension]['inc'])
		pensionHoy = parseFloat(tarifas['pens'][pension]['tarifa']);

	retorno = parseFloat(tarifas['habi'][idH][dia]) * cantH;
	retorno = retorno + pensionHoy;
	
	return parseFloat(retorno);
}

// Customize two date pickers to work as a date range 
function customRange(input)
{
	var fechaI = null;
	var fechaF = null;

	if(input.id == 'fecha_inicio_reserva')
	{
		if($('#rango').attr('checked'))
			fechaF = $('#fecha_fin_reserva').getDatepickerDate();
	}
	else
		fechaI = $('#fecha_inicio_reserva').getDatepickerDate();

	return {minDate: (fechaI), maxDate: (fechaF)};
}

function validarNroTarjeta(){

	type = $("#cardtype").val();	
	
	ccnum = $('#cardnumber').val();
	
	if (type == "VS") {
      // Visa: length 16, prefix 4, dashes optional.
      var re = /^4\d{3}-?\d{4}-?\d{4}-?\d{4}$/;
   } else if (type == "MC") {
      // Mastercard: length 16, prefix 51-55, dashes optional.
      var re = /^5[1-5]\d{2}-?\d{4}-?\d{4}-?\d{4}$/;
   } else if (type == "AE") {
      // American Express: length 15, prefix 34 or 37.
      var re = /^3[4,7]\d{2}-?\d{6}-?\d{5}$/;
   } 
   
   //if (re.test(ccnum)) return true;
   if (!re.test(ccnum)) return false;
 
   // Remove all dashes for the checksum checks to eliminate negative numbers
   ccnum = ccnum.split("-").join("");
   // Checksum ("Mod 10")
   // Add even digits in even length strings or odd digits in odd length strings.
   var checksum = 0;
   for (var i=(2-(ccnum.length % 2)); i<=ccnum.length; i+=2) {
      checksum += parseInt(ccnum.charAt(i-1));
   }
   // Analyze odd digits in even length strings or even digits in odd length strings.
   for (var i=(ccnum.length % 2) + 1; i<ccnum.length; i+=2) {
      var digit = parseInt(ccnum.charAt(i-1)) * 2;
      if (digit < 10) { checksum += digit; } else { checksum += (digit-9); }
   }
  			
	//document.getElementById("nro_tarjeta").value = nro_tarjeta;	

 	if ((checksum % 10) == 0)  
		return true;
	else 
		return false;
}

function validarCaducidad()
{
	mes_ = $('#expcard_mes').val();
	anio_ = $('#expcard_anio').val();

	fecha = new Date;

	mesAct = fecha.getMonth()+1;
	anioAct = fecha.getFullYear();
	
	if((anio_ < anioAct) || ((anio_ == anioAct) && (mes_ <= mesAct)))
		return false;
	else
		return true;	
}

(function(D){var A="Lite-1.0";D.fn.cycle=function(E){return this.each(function(){E=E||{};if(this.cycleTimeout){clearTimeout(this.cycleTimeout)}this.cycleTimeout=0;this.cyclePause=0;var I=D(this);var J=E.slideExpr?D(E.slideExpr,this):I.children();var G=J.get();if(G.length<2){if(window.console&&window.console.log){window.console.log("terminating; too few slides: "+G.length)}return }var H=D.extend({},D.fn.cycle.defaults,E||{},D.metadata?I.metadata():D.meta?I.data():{});H.before=H.before?[H.before]:[];H.after=H.after?[H.after]:[];H.after.unshift(function(){H.busy=0});var F=this.className;H.width=parseInt((F.match(/w:(\d+)/)||[])[1])||H.width;H.height=parseInt((F.match(/h:(\d+)/)||[])[1])||H.height;H.timeout=parseInt((F.match(/t:(\d+)/)||[])[1])||H.timeout;if(I.css("position")=="static"){I.css("position","relative")}if(H.width){I.width(H.width)}if(H.height&&H.height!="auto"){I.height(H.height)}var K=0;J.css({position:"absolute",top:0,left:0}).hide().each(function(M){D(this).css("z-index",G.length-M)});D(G[K]).css("opacity",1).show();if(D.browser.msie){G[K].style.removeAttribute("filter")}if(H.fit&&H.width){J.width(H.width)}if(H.fit&&H.height&&H.height!="auto"){J.height(H.height)}if(H.pause){I.hover(function(){this.cyclePause=1},function(){this.cyclePause=0})}D.fn.cycle.transitions.fade(I,J,H);J.each(function(){var M=D(this);this.cycleH=(H.fit&&H.height)?H.height:M.height();this.cycleW=(H.fit&&H.width)?H.width:M.width()});J.not(":eq("+K+")").css({opacity:0});if(H.cssFirst){D(J[K]).css(H.cssFirst)}if(H.timeout){if(H.speed.constructor==String){H.speed={slow:600,fast:200}[H.speed]||400}if(!H.sync){H.speed=H.speed/2}while((H.timeout-H.speed)<250){H.timeout+=H.speed}}H.speedIn=H.speed;H.speedOut=H.speed;H.slideCount=G.length;H.currSlide=K;H.nextSlide=1;var L=J[K];if(H.before.length){H.before[0].apply(L,[L,L,H,true])}if(H.after.length>1){H.after[1].apply(L,[L,L,H,true])}if(H.click&&!H.next){H.next=H.click}if(H.next){D(H.next).bind("click",function(){return C(G,H,H.rev?-1:1)})}if(H.prev){D(H.prev).bind("click",function(){return C(G,H,H.rev?1:-1)})}if(H.timeout){this.cycleTimeout=setTimeout(function(){B(G,H,0,!H.rev)},H.timeout+(H.delay||0))}})};function B(J,E,I,K){if(E.busy){return }var H=J[0].parentNode,M=J[E.currSlide],L=J[E.nextSlide];if(H.cycleTimeout===0&&!I){return }if(I||!H.cyclePause){if(E.before.length){D.each(E.before,function(N,O){O.apply(L,[M,L,E,K])})}var F=function(){if(D.browser.msie){this.style.removeAttribute("filter")}D.each(E.after,function(N,O){O.apply(L,[M,L,E,K])})};if(E.nextSlide!=E.currSlide){E.busy=1;D.fn.cycle.custom(M,L,E,F)}var G=(E.nextSlide+1)==J.length;E.nextSlide=G?0:E.nextSlide+1;E.currSlide=G?J.length-1:E.nextSlide-1}if(E.timeout){H.cycleTimeout=setTimeout(function(){B(J,E,0,!E.rev)},E.timeout)}}function C(E,F,I){var H=E[0].parentNode,G=H.cycleTimeout;if(G){clearTimeout(G);H.cycleTimeout=0}F.nextSlide=F.currSlide+I;if(F.nextSlide<0){F.nextSlide=E.length-1}else{if(F.nextSlide>=E.length){F.nextSlide=0}}B(E,F,1,I>=0);return false}D.fn.cycle.custom=function(K,H,I,E){var J=D(K),G=D(H);G.css({opacity:0});var F=function(){G.animate({opacity:1},I.speedIn,I.easeIn,E)};J.animate({opacity:0},I.speedOut,I.easeOut,function(){J.css({display:"none"});if(!I.sync){F()}});if(I.sync){F()}};D.fn.cycle.transitions={fade:function(F,G,E){G.not(":eq(0)").css("opacity",0);E.before.push(function(){D(this).show()})}};D.fn.cycle.ver=function(){return A};D.fn.cycle.defaults={timeout:4000,speed:1000,next:null,prev:null,before:null,after:null,height:"auto",sync:1,fit:0,pause:0,delay:0,slideExpr:null}})(jQuery)