$(function () {
	var nowTemp = new Date();
	var now = new moment(new Date(nowTemp.getFullYear(), nowTemp.getMonth(), nowTemp.getDate(), 0, 0, 0, 0));

	$('#txtCity, #txtHotel').on('click', function () {
		$(this).select();
	});

	$("#txtCity").on("focusout", function () {
		$("#txtHotel").val("");
		if ($("#City").val().length == 0 || $("#txtCity").val().length == 0) {
			$('#expandHotelInput').slideUp();
		}
	});

	$("#txtCity").autocomplete({
		minLength: 3,
		source: function (request, response) {
			$.getJSON('/Lookup/Regions', {
				term: request.term
			}, response);
		},
		focus: function (event, ui) {
			$("#txtCity").val(ui.item.Label);
			return false;
		},
		select: function (event, ui) {
			$("#txtCity").val(ui.item.Label);
			$("#City").val(ui.item.Value);
			$('#expandHotelInput').slideDown();
			if ($('#txtCity').hasClass("input-validation-error")) {
				$('#txtCity').removeClass("input-validation-error");
			}

			return false;
		}
	}).data("ui-autocomplete")._renderItem = function (ul, item) {
		return $("<li>")
		.append("<a>" + item.Label + "</a>")
		.appendTo(ul);
	};

	$("#txtHotel").autocomplete({
		minLength: 3,
		source: function (request, response) {
			$.getJSON('/Lookup/Hotels', {
				term: request.term,
				region: $('#City').val()
			}, response);
		},
		focus: function (event, ui) {
			$("#txtHotel").val($.trim(ui.item.Label));
			return false;
		},
		select: function (event, ui) {
			$("#txtHotel").val($.trim(ui.item.Label));
			$("#Hotel").val($.trim(ui.item.Value));

			return false;
		}
	}).data("ui-autocomplete")._renderItem = function (ul, item) {
		return $("<li>")
		.append("<a>" + item.Label + "</a>")
		.appendTo(ul);
	};

	setTimeout(function () { $('#txtHotel').focus(); }, 10);

	$("#cmdSubmitSearch").on("click", function () {
		var submitForm = true;
		var $required = $(this).closest('fieldset').find('[required]');
		var days = calculateDays($("#CheckIn").val(), $("#CheckOut").val())
		var alertMessage = new Array();

		$required.each(function () {
			var field = $(this);
			var fieldId = field.attr("id");
			var fieldValue = field.val();
			var fieldMessage = field.attr("label");

			if (fieldValue.length == 0) {
				alertMessage.push("Please enter " + fieldMessage);
				field.addClass("input-validation-error");

				if (fieldId != "CheckIn" && fieldId != "CheckOut") {
					field.focus();
				}

				if (fieldId == "City") {
					$("#txtCity").focus();
					$("#txtCity").addClass("input-validation-error");
				}
			} else {
				if (fieldId == "City") {
					field = $("#txtCity");
				}

				if (field.hasClass("input-validation-error")) {
					field.removeClass("input-validation-error");
				}
			}
		});

		if ($("#City").val().length == 0) {
			if ($("#txtCity").val().length == 0) {
				alertMessage.push("Please enter a city.");
				$("#txtCity").focus();
				$("#txtCity").addClass("input-validation-error");
			} else if ($("#txtCity").val().length < 3) {
				alertMessage.push("Please enter at least the first 3 letters of the city name.");
				$("#txtCity").focus();
				$("#txtCity").addClass("input-validation-error");
			}
		}

		if (new Date($("#CheckIn").val()) < now.toDate()) {
			alertMessage.push("Check in date cannot be in the past.");
			$("#CheckIn").focus();
			$("#CheckIn").addClass("input-validation-error");
		}

		if (new Date($("#CheckIn").val()) - new Date($("#CheckOut").val()) >= 0) {
			alertMessage.push("Check out date must be after check in date.");
			$("#CheckOut").focus();
			$("#CheckOut").addClass("input-validation-error");
		}

		if (days >= 28) {
			alertMessage.push("Maximum length of stay is 28 days.");
			$("#CheckOut").focus();
			$("#CheckOut").addClass("input-validation-error");
		}

		if ($("#ChildrenList").children().length > 0) {
			$("#ChildrenList").children("select").each(function () {
				if ($(this).val().length == 0) {
					alertMessage.push("Please enter all child ages");
					$(this).focus();
					$(this).addClass("input-validation-error");
				}
			});
		}

		//CLEAR CITY VALUE IF DELETED THE CITY NAME FROM INPUT.
		if (($("#txtCity").val().length == 0)) {
			$("#City").val("");
		}

		//CLEAR HOTEL VALUE IF DELETED THE HOTEL NAME FROM INPUT.
		if (($("#txtHotel").length == 0)) {
			$("#Hotel").val("");
		}
		
		if ($(".ui-helper-hidden-accessible").html() == "No search results.") {
			$("#City").val("");
		}

		if (alertMessage.length == 0) {
			if ($('#txtHotel').val() =="")
			{
				$('#Hotel').val("")
			}
			$("#frmMain").submit();
		} else {
			$("#frmMain").find(".validation-summary-valid").removeClass("validation-summary-valid").addClass("validation-summary-errors");
			$(".validation-summary-errors").remove();
			$("#ulSearchFields").prepend('<div class="validation-summary-errors" data-valmsg-summary="true"><ul><li></li></ul></div>');

			$(alertMessage).each(function (index) {
				$(".validation-summary-errors ul").append("<li>" + (alertMessage[index]).toString() + "</li>");
			});

			$(".validation-summary-errors").show();
		}
	});
});

//SHOWS ALL PLACEHOLDERS FOR IE < 8
$(function () {
	$('input, textarea').placeholder();
});

function calculateDays(checkInDate, checkOutDate) {
	var checkInDate_ms = new Date(checkInDate).getTime();
	var checkOutDate_ms = new Date(checkOutDate).getTime();
	//Get 1 day in milliseconds
	var one_day = 1000 * 60 * 60 * 24;
	// Calculate the difference in milliseconds
	var difference_ms = checkOutDate_ms - checkInDate_ms;
	// Convert back to days and return
	return Math.round(difference_ms / one_day);
}

function renderChildren() {
	for (i = 0; i < $("#Children").val() ; i++) {
		$("#ChildrenList").append(" \
					<select data-val=\"true\" data-val-number=\"The field Nullable`1 must be a number.\" id=\"ChildAges_" + i + "_\" name=\"ChildAges[" + i + "]\"> \
						<option selected=\"selected\"></option> \
						<option value=\"0\">0</option> \
						<option value=\"1\">1</option> \
						<option value=\"2\">2</option> \
						<option value=\"3\">3</option> \
						<option value=\"4\">4</option> \
						<option value=\"5\">5</option> \
						<option value=\"6\">6</option> \
						<option value=\"7\">7</option> \
						<option value=\"8\">8</option> \
						<option value=\"9\">9</option> \
						<option value=\"10\">10</option> \
						<option value=\"11\">11</option> \
						<option value=\"12\">12</option> \
						<option value=\"13\">13</option> \
						<option value=\"14\">14</option> \
						<option value=\"15\">15</option> \
						<option value=\"16\">16</option> \
						<option value=\"17\">17</option> \
					</select>"
	   );
	}
}

function toggleHotelInput() {
	if ($('#liHotelRow').css("display") == "none") {
		//SWAP ICON TO NEGATIVE
		$('#hotelIcon').removeClass("expandIcon").addClass("collapseIcon");
	} else {
		//SWAP ICON TO POSITIVE
		$('#hotelIcon').removeClass("collapseIcon").addClass("expandIcon");
	}

	$('#liHotelRow').slideToggle();
}
