var arrivalDate = false;
var departureDate = false;
var nights = 0;
var dateblocked = false;
var offers = false;

jQuery(document).ready( function() {
	/* IE placeholder attribute fix */
	if (!Modernizr.input.placeholder) {
		jQuery('[placeholder]').focus(function() {
		  var input = jQuery(this);
		  if (input.val() == input.attr('placeholder')) {
		    input.val('');
		    input.removeClass('placeholder');
		  }
		}).blur(function() {
		  var input = jQuery(this);
		  if (input.val() == '' || input.val() == input.attr('placeholder')) {
		    input.addClass('placeholder');
		    input.val(input.attr('placeholder'));
		  }
		}).blur();
		
		jQuery('[placeholder]').parents('form').submit(function() {
		  jQuery(this).find('[placeholder]').each(function() {
		    var input = jQuery(this);
		    if (input.val() == input.attr('placeholder')) {
		      input.val('');
		    }
		  })
		});
	}
	/* End IE fix */
	
	jQuery("#arrival").blur( function() {
		//jQuery("#departure").datepicker("show");
	});
	
	var dates = jQuery( "#arrival, #departure" ).datepicker({
		dateFormat: "d M, yy",
		defaultDate: null,
		gotoCurrent: true,
		minDate: new Date(),
		numberOfMonths: 3,
		showButtonPanel: true,
		stepMonths: 2,
		onClose: function( selectedDate, obj ) {				
			if(obj.id == "arrival") {
				var altField = "#arrivalDate";
				arrivalDate = jQuery(this).datepicker("getDate") ? jQuery(this).datepicker("getDate") : false;
				jQuery("#departure").qtip("show");
				//jQuery("#departure").datepicker("show");
			} else {
				var altField = "#departureDate";
				departureDate = jQuery(this).datepicker("getDate") ? jQuery(this).datepicker("getDate") : false;

			}
			
			var year = obj.selectedYear;
			var month = "" + (obj.selectedMonth + 1); month = month.length == 1 ? "0" + month : month;
			var day = "" + obj.selectedDay; day = day.length == 1 ? "0" + day : day;
			var date = year + "-" + month + "-" + day;
			jQuery(altField).attr("value", date);
			
			if(arrivalDate != false && departureDate != false) {
				var days = Math.floor((departureDate.getTime() - arrivalDate.getTime()) / 86400000);
				jQuery("#nights span").each( function() {
					if(jQuery(this).hasClass("nights")) {
						jQuery(this).html((days > 1 ? "nights" : "night"));
					} else {
						jQuery(this).html(days);
					}
				});
				jQuery("#nights").css("display", "block");
				nights = days;
			
				jQuery.ajax({
				  url: "page.includes/rates-list-new.inc.php",
				  data: { "bnb_id": bnbId, 
				  		"arrival": jQuery("#arrivalDate").attr("value"), 
				  		"departure": jQuery("#departureDate").attr("value"),
				  		"nights": jQuery("#nights span").html(),
				  		"showflags": true,
				  		"offers": offers },
				  context: document.body,
				  success: function(data){
				  	jQuery('select.numrooms').removeAttr('disabled');
						jQuery('span.disabled').css('display', 'none');
						jQuery('#ratesTable').html(data);
				    rateEvents();
						jQuery("#roomscaption").qtip("show");
				  },
				  type: "POST"
				});
			}
			dateblocked = false;
		},
		beforeShow: function(input, inst) {
			if(jQuery(input).attr("id") == "arrival") {
				jQuery("#arrival, #departure, #arrivalDate, #departureDate").val("");
				jQuery("#selecteddates").each( function() { this.reset(); });
				jQuery(this).datepicker('option', { maxDate: null });
			} else {
				//jQuery(this).datepicker('option', { minDate: "+1D" });
			}
		},
		beforeShowDay: function(date) {
		  var m = (date.getMonth() < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1);
		  var d = (date.getDate() < 10 ? "0" + date.getDate() : date.getDate());
		  var y = date.getFullYear();
		  var today = new Date();
		  var currentdate = new Date(today.getFullYear(), today.getMonth(), today.getDate(), 0, 0, 0);
		  for (i = 0; i < disabledDays.length; i++) {
		  	if(this.id == "arrival" || (this.id == "departure" && date > jQuery("#arrival").datepicker("getDate"))) {
			    if(jQuery.inArray(y + '-' + m + '-' + (this.id == "departure" && date.getDate() != 1 ? (date.getDate() - 1 < 10 ? "0" + (date.getDate() - 1) : d) : d), disabledDays) != -1) {
			    	dateblocked = true;
			      return [false, 'blocked', 'This date is not available'];
			    } else if(currentdate > date || (this.id == "departure" && dateblocked && date >= jQuery("#arrival").datepicker("getDate"))) {
			    	return [false, 'x', 'x'];
			    } 
			  }
		  }
		  dateblocked = false;
		  return [true];
		},
		onSelect: function( selectedDate ) {
			if(this.id == "arrival") {
				var option = "minDate";
				var instance = jQuery( this ).data( "datepicker" );
				
				var selected = jQuery( this ).datepicker("getDate");
				var date = new Date(selected.getFullYear(), selected.getMonth(), selected.getDate() + 1, 0, 0, 0);
				dates.not( this ).datepicker( "option", option, date );
			}
		}
	});
	
	rateEvents();
	
	jQuery("#arrival").qtip("show");
});

function showCalendar() {
	if(jQuery("#arrival").attr("value") == '') {
		jQuery("#arrival").qtip("show");
		jQuery("#arrival").focus();
	} else if(jQuery("#departure").attr("value") == '') {
		jQuery("#departure").qtip("show");
		jQuery("#departure").focus();
	}
}

var tooltipsetup = false;
function setupTip() {
	if(!tooltipsetup) {
		jQuery('#book').qtip({
				hide: {
						event: ''
					},
				position: {
						my: 'top right',
						at: 'bottom center'
					},
				show: {
						event: 'click',
						solo: true
					},
				style: {
			      classes: 'ui-tooltip-dark ui-tooltip-rounded ui-tooltip-shadow'
			   }
			});
		tooltipsetup = true;
	}
}

function rateEvents() {
	jQuery("span.disabled").click( function() {
		showCalendar();
	});
	
	jQuery("select.numrooms").change( function(event) {
		var offerId = jQuery(event.target).attr('dir');
		var rooms = jQuery(event.target).val();
		if(rooms != '-' && rooms > 0) {
			jQuery('#book').removeAttr('disabled');
			jQuery('#book').removeClass('disabled');
			jQuery("#roomscaption").qtip("hide");
			setupTip();
			jQuery('#book').qtip("show");
		}

		calculateTotal();
	});		
			
	jQuery("#book").click( function() {
		if(jQuery(this).hasClass("disabled")) {
			showCalendar();
		} else {
			jQuery("#bookingform").submit();
		}
	});
	
	jQuery(".offerInfo, #messageBar .tooltip").qtip({
		position: {
				my: 'top center',
				at: 'bottom center'
			},
		style: {
	      classes: 'ui-tooltip-blue ui-tooltip-darkblue ui-tooltip-rounded ui-tooltip-shadow'
	   }
	});
	
	jQuery(".helpstep").qtip({
		hide: {
				event: 'unfocus'
			},
		position: {
				my: 'bottom center',
				at: 'top center'
			},
		show: { 
				event: 'click focus',
				solo: true
			},
		style: {
	      classes: 'ui-tooltip-dark ui-tooltip-rounded ui-tooltip-shadow'
	   }
	});
	
	jQuery("#roomscaption").qtip({
		hide: {
				event: 'unfocus',
				target: jQuery("select.numrooms")
			},
		position: {
				my: 'bottom right',
				at: 'top center'
			},
		show: { 
				event: 'click focus',
				solo: true,
				target: jQuery("select.numrooms")
			},
		style: {
	      classes: 'ui-tooltip-dark ui-tooltip-rounded ui-tooltip-shadow'
	   }
	});
	
	currencyEvents();
}

function calculateTotal() {
	var total = 0;
	var staying = parseInt(jQuery("#nights span").html());
	
	jQuery("select.numrooms").each( function() {
		var offerId = jQuery(this).attr('dir');
		
		if(jQuery(this).val() != '-' && jQuery(this).val() > 0) {
			var rooms = parseInt(jQuery(this).val());
			var price = parseFloat(jQuery("td.offer" + offerId).attr("dir"));
			var pax = parseInt(jQuery("td.pax" + offerId).attr("dir"));
			var minNights = parseInt(jQuery("td.nights" + offerId).attr("dir"));
			
			var subtotal = price * rooms * (staying / minNights) * pax;
			jQuery("td.total" + offerId).html(selectedCurrency + floatFix(subtotal * multiplier, 2));  // multiplier = currency exchange rate
			jQuery("td.total" + offerId).attr('dir', floatFix(subtotal, 2));
			
			total = total + subtotal;
		} else {
			jQuery("td.total" + offerId).html('');
			jQuery("td.total" + offerId).attr('dir', 0);
		}
	});
	
	jQuery("#total span").html(selectedCurrency + " " + floatFix((total * multiplier), 2));  // multiplier = currency exchange rate
	jQuery("#total span").attr('dir', floatFix(total, 2));
	
	if(total == 0) {
			jQuery('#book').attr('disabled', 'disabled');
	}
}
