$(document).ready(function() {
	// Load the event options when the event selection box is changed
	$("#eventInput").change(function() {
		var eid = $(this).val();
		// Copy the event into the honeypot1
		$("#honeypot1").val(eid);
		if (eid == "") {
			// No event selected, hide form
			$("#regEditDiv").hide();
		} else {
			// Set passthrough
			// Fetch the event options and display form
			var data = {
					eid: eid
				};
			$("#eventoptionsdiv").load("registereventoptions-ajax.php", data, function() {
					$("#studentInput").change(function() {
						$(".prices").each(function() {
							var value;
							if ($("#studentInput:checked").length == 1) {
								value = Number($(this).html()) - Number($(this).parent().next().html());
							} else {
								value = Number($(this).html()) + Number($(this).parent().next().html());
							}
							$(this).html(value);
						});
						$(".eventOption").change();
					});
					$("#memberInput").change(function() {
						$(".prices").each(function() {
							var value;
							if ($("#memberInput:checked").length == 1) {
								value = Number($(this).html()) - Number($(this).parent().next().next().html());
							} else {
								value = Number($(this).html()) + Number($(this).parent().next().next().html());
							}
							$(this).html(value);
						});
						$(".eventOption").change();
					});
					$(".eventOption").change(function() {
						var total = 0;
						$(".eventOption:checked").each(function() {
							total = total + parseInt($(this).parent().next().children(".prices").html());
						});
						$("#totalCost").html("$" + total);
					});
					$("#regEditDiv").show();
				});
			$.post("registereventhousing-ajax.php", data, function(result) {
					$("#housingdiv").css("display", result.display);
				}, "json");
		}
	});
	
	$("#housingInputNone").change(function() {
		$(".housingRequest").hide();
		$(".housingOffer").hide();
	});
	$("#housingInputRequest").change(function() {
		$(".housingOffer").hide();
		$(".housingRequest").show();
	});
	$("#housingInputOffer").change(function() {
		$(".housingRequest").hide();
		$(".housingOffer").show();
	});
	
	$("#positionInputLead, #positionInputFollow").click(function () {
		UpdateDanceCaps();
		$(".eventOption").change();
	});
	function UpdateDanceCaps () {
		var position = $("#positionInputLead:checked, #positionInputFollow:checked").val();
		$(".eventOption:disabled").removeAttr("disabled");
		$(".eventFullFollow").toggleClass("eventFullFollow");
		$(".eventFullLead").toggleClass("eventFullLead");
		$(".cap"+position).each(function() {
			if ($(this).html() != "Open") {
				$(this).parent().toggleClass("eventFull"+position).children(":first").children(".eventOption").attr("disabled", "disabled").removeAttr("checked");
			}
		});
	}
	
	function updatePreview () {
		var errors = new Array();
		
		// Address block
		var address = "";
		if ($("#firstInput").val() != "" && $("#lastInput").val() != "") {
			address = address + $("#firstInput").val() + " " + $("#lastInput").val() + "<br />";
		} else {
			address = address + "<span class='error'>INVALID ENTRY</span><br />";
			errors.push("First and Last Name are required fields for registration.");
		}
		if ($("#streetInput").val() != "") {
			address = address + $("#streetInput").val() + "<br />";
		}
		if ($("#cityInput").val() != "" && $("#stateInput").val() != "") {
			address = address + $("#cityInput").val() + ", " + $("#stateInput").val();
		} else {
			address = address + "<span class='error'>INVALID ENTRY</span><br />";
			errors.push("City and State are required fields for registration.");
		}
		if ($("#zipInput").val() != "") {
			address = address + " " + $("#zipInput").val();
		}
		$("#addressPreview").html(address);
		
		// Email
		if ($("#emailInput").val() != "") {
			$("#emailPreview").html($("#emailInput").val());
		} else {
			$("#emailPreview").html("<span class='error'>INVALID ENTRY</span><br />");
			errors.push("Email is a required field for registration.  Please ensure a valid email address for proper registration.");
		}
		
		// Phone
		$("#phonePreview").html($("#phoneInput").val());
		
		// Dance position (Lead/Follow)
		if ($("#positionInputContainer input:checked").length == 1) {
			$("#positionPreview").html($("#positionInputContainer input:checked").val());
		} else {
			$("#positionPreview").html("<span class='error'>INVALID ENTRY</span><br />");
			errors.push("Lead/Follow is a required field for registration.  Please indicate your role such that we can help keep numbers balanced during the events.");
		}
		
		// Discount Status
		$("#memberPreview").html($("#memberInput:checked").length == 1 ? "Yes" : "No");
		$("#studentPreview").html($("#studentInput:checked").length == 1 ? "Yes" : "No");
		
		// Events
		var events = "";
		$("#danceInputList input:checked").each(function() {
			events = events + $(this).val() + "<br />";
		});
		if (events.length == 0) {
			events = "<span class='error'>NO EVENTS SELECTED</span>";
			errors.push("Please select at least one event option in order to create your registration.");
		}
		$("#eventsPreview").html(events);
		
		// Cost
		$("#totalcostPreview").html($("#totalCost").html());
		
		// Housing Start
		var request = $("#housingInputRequest:checked").length;
		var offer = $("#housingInputOffer:checked").length;
		if (request || offer) {
			// Nights
			var nights = new Array();
			$("#housingNightsContainer input:checked").each(function() {
				nights.push($(this).val());
			});
			if (nights.length == 0) {
				$("#nightsPreview").html("<span class='error'>NO NIGHTS SELECTED</span>");
				errors.push("Please select at least one night in the housing options.");
			} else {
				$("#nightsPreview").html(nights.toString().replace(/,/g, ", "));
			}
			
			// Smoking
			if ($("#smokingContainer input:checked").length == 1) {
				$("#smokingPreview").html($("#smokingContainer input:checked").val());
			} else {
				$("#smokingPreview").html("<span class='error'>INVALID ENTRY</span>");
				errors.push("Smoking preference is a required field for registration.");
			}
			
			// Pets
			var pets = new Array();
			$("#petsContainer input:checked").each(function() {
				pets.push($(this).val());
			});
			if (pets.length > 0) {
				$("#petsPreview").html(pets.toString().replace(/,/g, ", "));
			} else {
				$("#petsPreview").html("None");
			}
			
			// Late Nights
			if ($("#lateContainer input:checked").length == 1) {
				$("#latePreview").html($("#lateContainer input:checked").val());
			} else {
				$("#latePreview").html("<span class='error'>INVALID ENTRY</span>");
				errors.push("Late night preference is a required field for registration.");
			}
			
			// House With
			if (request) {
				$("#housewithPreview").html($("#housewithInput").val());
			}
			
			// Capacity
			if (offer) {
				var comfort = parseInt($("#comfortInput").val());
				var maximum = parseInt($("#maximumInput").val());
				// Valid number check
				if (comfort.toString() == "NaN" || maximum.toString() == "NaN") {
					$("#capacityPreview").html("<span class='error'>INVALID ENTRY</span>");
					errors.push("Comfortable and Maximum housing capacity fields are required.");
				// Is comfort less than or equal to max?
				} else if (comfort > maximum) {
					$("#capacityPreview").html("<span class='error'>" + comfort + " to " + maximum + " people</span>");
					errors.push("Error in housing capacity numbers.");
				} else {
					$("#capacityPreview").html(comfort + " to " + maximum + " people");
				}
			}
			
			// Additional Info
			$("#housinginfoPreview").html($("#housinginfoInput").val());
		}
		// Housing End
		
		// Handle Errors
		if (errors.length > 0) {
			// Disable submit button
			$("#submitButton").attr("disabled", "disabled");
			// Display error list
			$("#errorList").html("<li>" + errors.toString().replace(/,/g, "</li><li>") + "</li>").show();
		} else {
			// Enable submit button
			$("#submitButton").removeAttr("disabled");
			// Hide errors list (if previous errors had existed)
			$("#errorList").hide();
		}
	}
	
	$("#resetButton").click(function() {
		$("#memberInput:checked, #studentInput:checked").each(function() {
				$(".prices").each(function() {
						var value = Number($(this).html()) + Number($(this).parent().next().html());
						$(this).html(value);
					});
				$(".eventOption").change();
				UpdateDanceCaps();
			});
		return true;
	});
	$("#previewButton").click(function() {
		updatePreview();
		$("#regEditDiv").hide();
		$("#regSelectDiv").hide();
		$("#regConfirmDiv").hide();
		$("#regPreviewDiv").show();
	});
	$("#editButton, #editButtonTop").click(function() {
		$("#regPreviewDiv").hide();
		$("#regConfirmDiv").hide();
		$("#regEditDiv").show();
		$("#regSelectDiv").show();
	});
	$("#regForm").submit(function() {
		var formdata = $(this).serialize();
		$.post("registerpaymentform.php", formdata, function(result) {
				$("#regConfirmDiv").html(result);
		
				$("#returnToRegistration").click(function() {
						$("#regEditDiv").hide();
						$("#regPreviewDiv").hide();
						$("#regConfirmDiv").hide();
						$("#regSelectDiv").show();
						return false;
					});
			});
		$("input.eventOption:checked").each(function() {
				googlecart.addItem(googlecart.makeItem({
						'title': $("#eventInput option:selected").html() + " - " + $(this).next().html(),
						'price': $(this).parent().next().children(".prices").html() + ".00"
					}, {
						'name': "Registrant: " + $("#firstInput").val() + " " + $("#lastInput").val(),
						'member': "Member: " + ($("#memberInput:checked").length == 1 ? "Yes":"No"),
						'student': "Student: " + ($("#studentInput:checked").length == 1 ? "Yes":"No")
					}, 1)
				);
			});
		$("#eventInput").val("");
		$("#regEditDiv").hide();
		$("#regSelectDiv").hide();
		$("#regPreviewDiv").hide();
		$("#regConfirmDiv").show();
		return false;
	});
});
