var today = new Date();
var items = "";
var selectingNights = false;
var calYear = 0;
var calMonth = 0;
var selectedNight = 0;
var availFailed = false;
var checkin;
var checkout;

function updateCalendar(year, month) {
	calYear = year;
	calMonth = month;
	$.getJSON("property-info.php", {
		"month": year+"-"+month
		}, function(json) {
			items = json.items;
			drawCalendar(items);
			$("#monthYearSelect option[value='"+year+"-"+month+"']").attr("selected", "selected");
			$("#calendarCells .day, #calendarCells .sold").hover(function(e) {
				cellHover($(this), e);
			}, function() {
				if (!selectingNights) {
					$("#hoverInfo").hide();
				}
			});
	});
}

function drawCalendar(items) {
	$("#calendarCells").empty();
	var monthStartPosition = new Date(calYear, calMonth - 1, 1).getDay();
	insertBlankCells(monthStartPosition);
	var minp = 99999;
	var maxp = 0;
	for (var key in items) {
		// indexOf was prototyped in for IE, so it appears in the for loop.
		if (key != "indexOf") {
			var day = items[key];
			var date = new Date(calYear, calMonth - 1, day.day);
			var todayNoTime = new Date(today.getFullYear(), today.getMonth(), today.getDate());
			if (date < todayNoTime) {
				$("#calendarCells").append("<li class='past'><span class='date'>"+day.day+"</span></li>");
			} else {
				var className = "";
				/*
				if (day.sh != null && day.sh.indexOf($("#holidaySelect").val()) != -1 )
					className = " sh";
				if (day.ph != null && day.ph.indexOf($("#holidaySelect").val()) != -1 )
					className = " ph";
				*/
				if (checkin != null && checkout != null && (((date - checkin) /1000/60/60/24) >= 0 && (((date - checkout) /1000/60/60/24) <= 0))) {
					className = className + " selected";
					if (day.minp < minp) minp = day.minp;
					if (day.maxp > maxp) maxp = day.maxp;
				}
				if (day.avail)
					if (0 && parseInt(day.minp) > 0) {
						$("#calendarCells").append("<li class='day"+className+"'><div class='corner'>&nbsp;</div><span class='date'>"+day.day+"</span>$"+day.minp+"</li>");
					} else {
						$("#calendarCells").append("<li class='day"+className+"'><div class='corner'>&nbsp;</div><span class='date'>"+day.day+"</span></li>");
					}
				else
					$("#calendarCells").append("<li class='day na'><span class='date'>"+day.day+"</span></li>");
			}
		}
	}
	if (checkin != null && checkout != null) {
		$("#CheckInDate").html( prettyDate(checkin) + "&nbsp;<span id='clearLink'><a href='javascript:void(0);'>clear</a></span>" );
		var displayCheckout = new Date(checkout.getFullYear(), checkout.getMonth(), checkout.getDate() + 1);
		$("#CheckOutDate").html(prettyDate(displayCheckout));
		$("#pricingSummary").addClass('altered');
		if (checkin.getMonth() == (calMonth - 1) && checkin.getFullYear() == calYear) {
			if (minp == maxp) {
				if (minp == 0) {
					$("#Pricing").html("Pricing Unavailable");
				} else {
					$("#Pricing").html((((checkout - checkin) /1000/60/60/24) + 1) + " night stay from $" + minp + " /night*");
				}
			} else {
				$("#Pricing").html((((checkout - checkin) /1000/60/60/24) + 1) + " night stay $" + minp + " - $" + maxp + " /night*");
			}
			if (items[parseInt(checkin.getDate())] != null && items[parseInt(checkin.getDate())].minn > ((checkout - checkin) /1000/60/60/24) + 1) {
				$("#Pricing").html("You must book at least "+ items[checkin.getDate()].minn +" nights.");
			}
		}

		$("#res_dayin").val(checkin.getDate());
		$("#res_monthin").val(checkin.getFullYear() + "-" + (checkin.getMonth() + 1));
		$("#res_nights").val((((checkout - checkin) /1000/60/60/24) + 1));
		//$("#DayIn option[value='"+checkin.getDate()+"']").attr('selected', 'selected');
		//$("#MonthIn option[value='"+checkin.getFullYear()+"-"+(checkin.getMonth() + 1)+"']").attr('selected', 'selected');
		//$("#Nights option[value='"+(((checkout - checkin) /1000/60/60/24) + 1)+"']").attr('selected', 'selected');
	}
	var numberRows = Math.ceil((items.length + monthStartPosition) / 7)
	insertBlankCells(numberRows * 7 - (items.length + monthStartPosition));
	$("#propertyCalendar").height((numberRows * 29) + 65);
}

function insertBlankCells(number) {
	for (var i = 0; i < number; i++) {
		$("#calendarCells").append("<li class='filler'>&nbsp;</li>");
	}
}

function cellHover(el, ev) {
	if (!selectingNights) {
		// Get the date of the item selected, and generate the holiday lists.
		var index = $("span", el).html() - 1;
		var selectedDate = new Date(calYear, calMonth - 1, index + 1);
		/*
		var publicHoliday = (items[index].ph != null && items[index].ph.indexOf($("#holidaySelect").val()) != -1) ? "Public Holiday<br />" : "";
		var schoolHoliday = (items[index].sh != null && items[index].sh.indexOf($("#holidaySelect").val()) != -1) ? "School Holiday<br />" : "";
		*/
		// Display information in div, and move to mouse location.
		$("#hoverInfo").html("<strong>"+prettyDate(selectedDate)+"</strong><div id='information'><div>");
		if (!items[index].avail) {
			$("#hoverInfo #information").append("<div>Not Available</div>");
		} else {
			//$("#hoverInfo #information").append("<div>"+publicHoliday+schoolHoliday+"</div>");
			if (items[index].minn > 1) {$("#hoverInfo #information").append("<span style='color: red;'>min "+items[index].minn+" night stay.</span>");}
			if (items[index].minp > 0) {
				if (items[index].minp != items[index].maxp) {
					//$("#hoverInfo #information").append("<div>From $"+items[index].minp+" - $"+items[index].maxp+" per night*.</div>");
				} else {
					//$("#hoverInfo #information").append("<div>From $"+items[index].minp+" per night*.</div>");
				}
			}
		}
		$("#hoverInfo").append("<span class='arrow-bottom'> </span>");
		var pos = el.position();
		$("#hoverInfo").css("top", pos.top - $("#hoverInfo").height() - 8).css("left", pos.left - ($("#hoverInfo").width() / 2) - 2).show();
		$("#hoverInfo").bgiframe({width: $("#hoverInfo").width(), height: $("#hoverInfo").height()});
	}
}

function getAvail(selectedDate, searchingMonth, searchingYear, availItems, el) {
	// Get next months avail list.
	searchingMonth++;
	if (searchingMonth > 12) {searchingMonth = 0; searchingYear++;}
	$.getJSON("property-info.php", {
		"month": searchingYear+"-"+(searchingMonth + 1)
	}, function(json) {
		availItems = availItems.concat(json.items);
		// As long as the last list contained items and we still haven't got enough to test out to
		// max night stay, keep getting more. Otherwise, build the dialog with what we have.
		if (json.items.length > 0 && (availItems.length - selectedDate.getDate()) < items[selectedDate.getDate() - 1].maxn) {
			getAvail(selectedDate, searchingMonth, searchingYear, availItems, el);
		} else {
			buildStayLengthDialog(selectedDate, availItems, el);
		}
	});
}

function buildStayLengthDialog(selectedDate, availItems, el) {
	// Process the item list until we run out of items, we get to the max night stay, or find an unavailable date.
	$("#hoverInfo").hide();
	$("#clickInfo").show();
	$("#clickInfo #stayDate").html(prettyDate(checkin));
	$("#calDays").empty().append("<option>Select</option>");
	for (var i = (items[selectedDate.getDate() - 1].minn - 1); i <= items[selectedDate.getDate() - 1].maxn; i++) {
		var nightToCheck = (selectedDate.getDate() + i) - 1;
		if (nightToCheck < availItems.length) {
			if (availItems[nightToCheck].avail)
				$("#clickInfo #calDays").append("<option value='"+(i + 1)+"'>"+(i + 1)+" nights</option>");
			else
				break;
		}
	}
	$("#clickInfo #minStay").html("min " + items[selectedDate.getDate() - 1].minn + " night stay.");
	// Complete building the dialog.
	$("#minDays").remove();
	if ($("#clickInfo #calDays").children().size() < 2) {
		$("#clickInfo #calDays").after("<span id='minDays'>Minimum number of nights cannot be met.</span>").hide();
		$("#Pricing").html("You must book at least " + items[selectedDate.getDate() - 1].minn + " nights");
	} else {
		$("#clickInfo #calDays").show();
	}
	var pos = el.position();
	$("#clickInfo").css("top", pos.top - $("#clickInfo").height() - 8).css("left", pos.left - ($("#clickInfo").width()) + 48);
	$("#clickInfo").bgiframe({width: $("#clickInfo").width(), height: $("#clickInfo").height()});
}

function closeBalloon() {
	$("#clickInfo").hide();
	selectingNights = false;
}

function closeLink() {
	$(".day").removeClass("selected");
	closeBalloon();
}

function prettyDate(d) {
	var d_names = new Array("Sun", "Mon", "Tue",
		"Wed", "Thu", "Fri", "Sat");

	var m_names = new Array("January", "February", "March",
		"April", "May", "June", "July", "August", "September",
		"October", "November", "December");

	var curr_day = d.getDay();
	var curr_date = d.getDate();
	var curr_month = d.getMonth();
	var curr_year = d.getFullYear();

	return(d_names[curr_day] + " " + curr_date + " " + m_names[curr_month] + " " + curr_year);
}

// ---- JQuery Event Bindings Follow ----
$(document).ready(function() {
	$("#make-enquiry").click(function() {
		$("#Seriousness").attr("value", "General");
		$("#EnqTabs").show();
		$("#ResTabs").hide();
		$("#SendButton").html("Send Enquiry<span></span>");
	});
	$("#make-reservation").click(function() {
		$("#Seriousness").attr("value", "Reservation");
		$("#EnqTabs").hide();
		$("#ResTabs").show();
		$("#SendButton").html("Send Reservation<span></span>");
	});

	$("#calDays").change(function() {
		// Once the user has selected the number of nights to stay, display the checkout date, and
		// update the inline booking form with the number of nights to stay.
		var daysToStay = parseInt( $("#calDays").val() );
		checkout = new Date(calYear, (calMonth - 1), selectedNight + (daysToStay - 1));
		var displayCheckout = new Date(checkout.getFullYear(), checkout.getMonth(), checkout.getDate() + 1);
		$("#CheckOutDate").html(prettyDate(displayCheckout));
		var minp = items[selectedNight - 1].minp;
		var maxp = items[selectedNight - 1].maxp;
		for (var i = 0; i < daysToStay - 1 && (selectedNight + i) > items.length; i++) {
			var currentNight = items[selectedNight + i];
			if (currentNight.minp < minp) minp = currentNight.minp;
			if (currentNight.maxp > maxp) maxp = currentNight.maxp;
		}
		if (minp == maxp) {
			if (minp == 0) {
				$("#Pricing").html("Pricing Unavailable");
			} else {
				$("#Pricing").html(daysToStay + " night stay from $" + minp + " /night*");
			}
		} else {
			$("#Pricing").html(daysToStay + " night stay $" + minp + " - $" + maxp + " /night*");
		}
		$("#res_nights").val(daysToStay);
		//$("#Nights option[value='"+daysToStay+"']").attr('selected', 'selected');
		$(".day").each(function() {
			var currentDate = parseInt($("span", $(this)).html());
			if (currentDate >= selectedNight && currentDate < (selectedNight + daysToStay)) {
				$(this).addClass("selected");
			} else {
				$(this).removeClass("selected");
			}
		});
		$("#pricingSummary").addClass('altered');
		closeBalloon();
	});

	$("#prevCalLink a").click(function(){
		// Retreat the Calendar one month, but not prior to the current month.
		var thisMonth = new Date( today.getFullYear(), today.getMonth(), 1 );
		var testDate = new Date( calYear, (calMonth - 2), 1 );
		if ( testDate >= thisMonth ) {
			updateCalendar( testDate.getFullYear(), (testDate.getMonth() + 1) );
		}
	});

	$("#nextCalLink a").click(function(){
		// Advance the Calendar to the next month.
		var testDate = new Date( calYear, (calMonth - 1), 1 );
		testDate.setMonth( (testDate.getMonth() + 1) );
		updateCalendar( testDate.getFullYear(), (testDate.getMonth() + 1) );
	});

	$("#calendarCells .day:not(.na)").live("click", function() {
		closeBalloon();
		selectingNights = true;
		$("#pricingSummary").removeClass('altered');
		$("#CheckInDate").html("Click on date above.");
		$("#CheckOutDate").html("&mdash;");
		$("#Pricing").html("&mdash;");
		$(".day").removeClass("selected");
		// Change to the on click colours.
		$(this).addClass("selected");
		// Build date object for selected date.
		var selectedDate = new Date( calYear, calMonth - 1, parseInt($("span", $(this)).html()) );
		checkin = new Date( calYear, calMonth - 1, parseInt($("span", $(this)).html()) );
		selectedNight = selectedDate.getDate();
		$("#CheckInDate").html( prettyDate(selectedDate) + "&nbsp;<span id='clearLink'><a href='javascript:void(0);'>clear</a></span>" );
		// Update the inline booking forms Check in dates.
		$("#res_dayin").val(selectedDate.getDate());
		$("#res_monthin").val(selectedDate.getFullYear() + "-" + (selectedDate.getMonth() + 1));
		//$("#DayIn option[value='"+selectedDate.getDate()+"']").attr('selected', 'selected');
		//$("#MonthIn option[value='"+selectedDate.getFullYear()+"-"+(selectedDate.getMonth() + 1)+"']").attr('selected', 'selected');
		// Using the current item set, get as many months as required to check avail out to the max night stay
		// and build the dialog box.
		getAvail(selectedDate, selectedDate.getMonth(), selectedDate.getFullYear(), items, $(this));
	});

	$("#monthYearSelect, #MonthIn").change(function() {
	//$("#monthYearSelect, #MonthIn").change(function() {
		// Change to the month selected from the drop down.
		var date = $(this).val().split("-");
		updateCalendar(date[0], date[1]);
	});

	$("#holidaySelect").change(function() {
		// Changed the holiday location, update view.
		updateCalendar(calYear, calMonth);
	});

	$("#reservation-form form").submit(function() {
		$("#SubmitNote span").html("");
		if (availFailed) {$("#SubmitNote span").append("<p>The property is not available for the selected dates - see calendar!</p>");}
		if ($("#FirstName").val() == "") {$("#SubmitNote span").append("<p>You must enter a first name.</p>");}
		if ($("#LastName").val() == "") {$("#SubmitNote span").append("<p>You must enter a last name.</p>");}
		if ($("#Email").val() == "" || ($("#Email").val().indexOf(",") > 0 || $("#Email").val().indexOf("@") < 0)) {$("#SubmitNote span").append("<p>You must enter a valid email address.</p>");}
		if ($("#ConfirmEmail").val() != $("#Email").val()) {$("#SubmitNote span").append("<p>The confirmation email address you entered, doesn't match your email address.</p>");}
		if ($("#Phone1").val() == "") {$("#SubmitNote span").append("<p>You must enter a phone number.</p>");}
		if ($("#Postcode").val() == "") {$("#SubmitNote span").append("<p>You must enter a postcode.</p>");}
		if (!$("#Agree").is(":checked")) {$("#SubmitNote span").append("<p>You must agree to the Stayz Terms and Conditions.</p>");}
		if ($("#Captcha").val() == "") {$("#SubmitNote span").append("<p>You must enter the security code exactly as shown in the picture.</p>");}
		if ($("#SubmitNote span").html() != "") {
			$("#SubmitNote").show();
			return false;
		} else {
			return true;
		}
	});
	$("#clearLink a").live("click", function() {
		$("#CheckInDate").html("Click on date above.");
		$("#CheckOutDate").html("&mdash;");
		$("#Pricing").html("&mdash;");
		$(".day").removeClass("selected");
		$("#pricingSummary").removeClass('altered');
		checkin = null;
		checkout = null;
	});
});

// ----- Check Booking Availablity -----

function checkAvailability() {
	var date = $("#res_monthin").val().split("-");
	//var date = $("#MonthIn").val().split("-");
	var checkInDate = new Date(date[0], date[1] - 1, $("#res_dayin").val());
	//var checkInDate = new Date(date[0], date[1] - 1, $("#DayIn").val());
	var checkInObj = items[checkInDate.getDate() - 1];
	// Update the nights drop down with vaild options.
	// If they have already chosen a stay length, perserve it.
	var numNights = parseInt($("#res_nights").val());
	//var numNights = parseInt($("#Nights").val());
//	$("#Nights").empty();
//	for (var i = parseInt(checkInObj.minn); i <= parseInt(checkInObj.maxn); i++) {
//		$("#Nights").append("<option value='"+i+"'>"+i+" nights</option>");
//	}
//	$("#Nights option[value='"+numNights+"']").attr("selected", "selected");
	// Actually check the Availablity.
	checkItems = items;
	getAvail2(checkInDate, checkInDate.getMonth(), checkInDate.getFullYear(), numNights, checkItems);
}

function getAvail2(checkInDate, searchMonth, searchYear, numNights, checkItems) {
	var checkingOffset = checkInDate.getDate();
	searchMonth++;
	if (searchMonth > 12) {searchMonth = 0; searchYear++;}
	$.getJSON("/ajax/propertyInfo.action", {
		"propertyId": propertyId,
		"month": searchYear+"-"+(searchMonth + 1)
	}, function(json) {
		checkItems = checkItems.concat(json.items);
		if (json.items.length != 0 && checkingOffset + numNights > checkItems.length) {
			// Get more Items
			getAvail2(checkInDate, searchMonth, searchYear, numNights, checkItems);
		} else {
			// Process List
			var available = true;
			for (var item = checkingOffset; item < numNights + checkingOffset; item++) {
				if (!checkItems[item - 1].avail) {
					available = false;
					break;
				}
			}
			if (!available) {
				$("#AvailabilityNote span").html("The property is not available for the selected dates - see calendar!");
				$("#AvailabilityNote").show();
				availFailed = true;
			} else if (numNights < checkItems[checkingOffset - 1].minn) {
				$("#AvailabilityNote span").html("You must book a minimum of " + checkItems[checkingOffset - 1].minn + " nights.");
				$("#AvailabilityNote").show();
				availFailed = true;
			} else {
				$("#AvailabilityNote span").html("");
				$("#AvailabilityNote").hide();
				availFailed = false;
			}
		}
	});
}
