
/*

	transit time calculator javascript functions
	
	dependencies: 
		jQuery
		global.js > ParseErrorMsg()
		global.js > ScrollToElm()
	
*/

jQuery(function($) {
	var ajax_req = null; 
	var calculator = $("#TransitTimeCalculator");
	if (calculator.length) {
		
		// reset the form onload; clears remnants from clicking the browser's "back" button
		calculator.get(0).reset();
		
		// parse error message; adds click event handlers
		ParseErrorMsg();
		
		$("#ClearBtn").click(function(evt) {
			// abort active ajax_req
			if (ajax_req) ajax_req.abort();
			// prevent form from submitting
			evt.preventDefault();
			// clear button focus
			$(this).blur();
			// reset the form
			ClearForm(calculator);
			// reset the origin and destination city fields
			$("#OriginCityFld").css("opacity", 0.5).attr("disabled", "disabled").get(0).selectedIndex = -1;
			$("label.OriginCity").addClass("Disabled");
			$("#DestinationCityFld").css("opacity", 0.5).attr("disabled", "disabled").get(0).selectedIndex = -1;
			$("label.DestinationCity").addClass("Disabled");
			// error message clean-up
			ClearErrors();
			// scroll to top of form
			ScrollToElm("#TransitTimeCalculator");
		});
		
		$(".DividerCol").show();
		$(".StateCountryCol").show();
		
		var defaultShipmentDate = new Date();
		var shipmentDate = jQuery.trim($("#ShipmentDateFld").val());
		var results = shipmentDate.match(/^(\d{1,2})\/(\d{1,2})\/(\d{2,4})$/);
		if (results && (results.length == 4)) {
			var m = Number(results[1]) - 1;	// zero offset
			var d = Number(results[2]);
			var y = Number(results[3]);
			defaultShipmentDate.setFullYear(y, m, d);
		}
		
		$("#ShipmentDateFld").datepicker({
			beforeShowDay: $.datepicker.noWeekends,
			minDate: 0,
			maxDate: 90,
			defaultDate: defaultShipmentDate,
			showAnim: "fadeIn",
			duration: "fast",
			beforeShow: function() {
				// scroll to shipment date field
				ScrollToElm("#ShipmentDateFld");
			}
		});
		
		// hide all loader animations
		$(".LoaderImg").hide();
	
		// disable the city picklists and make their corresponding label semi-transparent
		if ($("#OriginStateFld").val() == "") {
			$("#OriginCityFld").css("opacity", 0.5).attr("disabled", "disabled").get(0).length = 0;
			$("label.OriginCity").addClass("Disabled");
		}
		if ($("#DestinationStateFld").val() == "") {
			$("#DestinationCityFld").css("opacity", 0.5).attr("disabled", "disabled").get(0).length = 0;
			$("label.DestinationCity").addClass("Disabled");
		}
		
		// setup origin zip field onchange event handler
		$("#OriginZipFld").change(function() {
			$("#OriginStateFld").val("");
			$("#OriginCityFld").css("opacity", 0.5).attr("disabled", "disabled").get(0).length = 0;
			$("label.OriginCity").addClass("Disabled");
		});
		
		// setup destination zip field onchange event handler
		$("#DestinationZipFld").change(function() {
			$("#DestinationStateFld").val("");
			$("#DestinationCityFld").css("opacity", 0.5).attr("disabled", "disabled").get(0).length = 0;
			$("label.DestinationCity").addClass("Disabled");
		});
		
		// setup origin state field onchange event handler
		$("#OriginStateFld").change(function() {
			// clear the zip code
			$("#OriginZipFld").val("");
			
			// get the select state
			var originState = $(this).val();
			
			if (originState) {
				// make the label opaque
				$("label.OriginCity").removeClass("Disabled");
				// make the picklist opaque, disabled, and clear selection
				$("#OriginCityFld").css("opacity", 1).attr("disabled", "disabled").get(0).length = 0;
				// show the loader animation
				$("#OriginCityLoader").show();
				// refresh the city picklist
				ajax_req = $.ajax({ 
					url: "/calculators/transit_time.cgi",
					type: "post",
					dataType: "html",
					data: {
						Action: "Get Cities",
						location: "origin",
						state: originState
					},
					success: function(data) {
						// hide the loader animation
						$("#OriginCityLoader").hide();
						// setup the city picklist
						$("#OriginCityFld").replaceWith(data);
						$("#OriginCityFld").change(function() {
							// clear the zip code
							$("#OriginZipFld").val("");
						});	
						$("#OriginCityFld").focus();
					},
					error: function(data) {
					}
				});
			}
			else {
				// make the label semi-transparent
				$("label.OriginCity").addClass("Disabled");
				// make the picklist semi-transparent, disabled, and clear selection
				$("#OriginCityFld").css("opacity", 0.5).attr("disabled", "disabled").get(0).length = 0;
			}
		});
		
		// setup destination state field onchange event handler
		$("#DestinationStateFld").change(function() {
			// clear the zip code
			$("#DestinationZipFld").val("");
			
			// get the select state
			var destinationState = $(this).val();
			
			if (destinationState) {
				// make the label opaque
				$("label.DestinationCity").removeClass("Disabled");
				// make the picklist opaque, disabled, and clear selection
				$("#DestinationCityFld").css("opacity", 1).attr("disabled", "disabled").get(0).length = 0;
				// show the loader animation
				$("#DestinationCityLoader").show();
				// refresh the city picklist
				$.post("/calculators/transit_time.cgi",
					{
						Action: "Get Cities",
						location: "destination",
						state: destinationState
					},
					function(data) {
						// hide the loader animation
						$("#DestinationCityLoader").hide();
						// setup the city picklist
						$("#DestinationCityFld").replaceWith(data);
						$("#DestinationCityFld").change(function() {
							// clear the zip code
							$("#DestinationZipFld").val("");
						});
						$("#DestinationCityFld").get(0).focus();
					},
					"html");
			}
			else {
				// make the label semi-transparent
				$("label.DestinationCity").addClass("Disabled");
				// make the picklist semi-transparent, disabled, and clear selection
				$("#DestinationCityFld").css("opacity", 0.5).attr("disabled", "disabled").get(0).length = 0;
			}
		});
		
		calculator.submit(function(evt) {
			var errorMsg = "";
	
			var errorPrefix = '<span class="ErrorPrefix">Error: </span>';
			
			var originZip = jQuery.trim($("#OriginZipFld").val());
			var originState = jQuery.trim($("#OriginStateFld").val());
			var originCity = jQuery.trim($("#OriginCityFld").val());
			var destinationZip = jQuery.trim($("#DestinationZipFld").val());
			var destinationState = jQuery.trim($("#DestinationStateFld").val());
			var destinationCity = jQuery.trim($("#DestinationCityFld").val());
			var shipmentDate = jQuery.trim($("#ShipmentDateFld").val());
			
			// error message clean-up
			ClearErrors();
			
			if (originZip == "" && (originState == "" || originCity == "")) {
				$(".OriginHeading").addClass("Error").find(".HeadingNo").after(errorPrefix);
				errorMsg += '<li><a href="#OriginZipFld">Enter an origin</a>: Please enter a zip code or select an city/state.</li>\n';
			}
			else if (originZip != "") {
				if (!/^\d{5}$/.test(originZip)) {
					$("label.OriginZip").addClass("Error").prepend(errorPrefix);
					errorMsg += '<li><a href="#OriginZipFld">Zip Code</a>: The origin zip code must be a 5-digit number.</li>\n';
				}
			}
			
			if (destinationZip == "" && (destinationState == "" || destinationCity == "")) {
				$(".DestinationHeading").addClass("Error").find(".HeadingNo").after(errorPrefix);
				errorMsg += '<li><a href="#DestinationZipFld">Enter a destination</a>: Please enter a zip code or select an city/state.</li>\n';
			}
			else if (destinationZip != "") {
				if (!/^\d{5}$/.test(destinationZip)) {
					$("label.DestinationZip").addClass("Error").prepend(errorPrefix);
					errorMsg += '<li><a href="#DestinationZipFld">Zip Code</a>: The destination zip code must be a 5-digit number.</li>\n';
				}
			}
			
			if (shipmentDate == "") {
				$(".ShipmentDateHeading").addClass("Error").find(".HeadingNo").after(errorPrefix);
				errorMsg += '<li><a href="#ShipmentDateFld">Enter a shipment day</a>: Please enter a shipment day.</li>\n';	
			}
			else {
				shipmentDate.replace("-","/");
				var results = shipmentDate.match(/^(\d{1,2})\/(\d{1,2})\/(\d{2,4})$/);
				if (results && (results.length == 4)) {
					var m = Number(results[1]) - 1;	// zero offset
					var d = Number(results[2]);
					var y = Number(results[3]);
					if (y < 100) y += 2000;	// force 2-digit values to 4
					var shipmentDate = new Date();
					shipmentDate.setFullYear(y, m, d);
					var minDate = new Date();
					var maxDate = new Date();
					maxDate.setDate(maxDate.getDate() + 90);
					var dayOfWeek = shipmentDate.getDay() + 1;
					if (shipmentDate < minDate) {
						$("label.ShipmentDate").addClass("Error").prepend(errorPrefix);
						errorMsg += '<li><a href="#ShipmentDateFld">Shipment day</a>: Shipment day cannot be earlier than today.</li>\n';
					}
					else if (shipmentDate > maxDate) {
						$("label.ShipmentDate").addClass("Error").prepend(errorPrefix);
						errorMsg += '<li><a href="#ShipmentDateFld">Shipment day</a>: Shipment day cannot be greater than 90 days from today.</li>\n';
					}
					else if (dayOfWeek == 1 || dayOfWeek == 7) {
						$("label.ShipmentDate").addClass("Error").prepend(errorPrefix);
						errorMsg += '<li><a href="#ShipmentDateFld">Shipment day</a>: Shipment day must be a weekday (e.g. Monday-Friday).</li>\n';
					}
				}
				else {
					$("label.ShipmentDate").addClass("Error").prepend(errorPrefix);
					errorMsg += '<li><a href="#ShipmentDateFld">Shipment day</a>: Shipment day is invalid. Please enter the shipment day as MM/DD/YYYY.</li>\n';
				}
			}
			
			if (errorMsg != "") {
				// prevent the form from submitting
				evt.preventDefault();
				// insert error message
				errorMsg = '<h2 class="Error">Please check the following fields for missing or invalid input:</h2>\n' +
					'<ul class="ErrorMsg">' + errorMsg + '</ul>\n';
				$("#ErrorMsg").append(errorMsg);
				// parse error message; adds click event handlers
				ParseErrorMsg();
				// scroll to top of form
				ScrollToElm("#TransitTimeCalculator");
			}
		});
	}
});