$(function () {
	var coursetype = $('#course_type');
	var course = $('#course');
	var mnth = $('#course_month');
    var location = $('#course_location');

	function populateSelect(target, source, data, msg) {
		target.empty();
				
		$.ajax({
			url: source,
			data: data,
	        type: 'post',
			dataType: 'json',
			success: function (j) {
				var options = [], i = 0, o = null;
	                   
				if (j.length) {
					o = document.createElement("OPTION");
					o.value = "";
					o.text = "Please select";
					target.get(0).options[0] = o;
				
					for (i = 0; i < j.length; i++) {
						// required to get around IE bug (http://support.microsoft.com/?scid=kb%3Ben-us%3B276228)
						o = document.createElement("OPTION");
						o.value = j[i]['id'];
						o.text = j[i]['label'];
						target.get(0).options[i+1] = o;
			        }

					if (j.length > 1) {
						// show the child select
						target.closest("div").show();
					}
					else {
						// hand control back to browser for a moment
						setTimeout(function () {
						    target.find('option:nth-child(2)').attr('selected', 'selected').parent('select').trigger('change');
						}, 0);							
					}
				}
				else {
					$('#course_finder_content').html('<p><br />' + msg + '</p>');
				}

			}
		});
	}

	coursetype.change(function() {
		// hide stuff
		course.closest("div").hide();
		mnth.closest("div").hide();
		location.closest("div").hide();
		course.closest("div").hide();
		$('#course_finder_content').empty();
		// load data
		populateSelect(course, '/app/modules/vettrak/finder/data.cfm', { ajax: true, lookup: "course",  course_type: coursetype.val()}, 'No courses currently available');
	});
	
	course.change(function() {
		// hide stuff
		mnth.closest("div").hide();
		location.closest("div").hide();
		course.closest("div").hide();
		$('#course_finder_content').html("");
		// load data
		populateSelect(mnth, '/app/modules/vettrak/finder/data.cfm', { ajax: true, lookup: "month", course_type: coursetype.val(), course: course.val()}, 'No course dates available for that course');
	});

	mnth.change(function() {
		// hide stuff
		location.closest("div").hide();
		$('#course_finder_content').html("");
		// load data
		populateSelect(location, '/app/modules/vettrak/finder/data.cfm', { ajax: true, lookup: "location", course_type: coursetype.val(), course: course.val(), course_month: mnth.val()}, 'No locations available for that month');
	});

	
	location.change(function() {
		$('#course_finder_content').html("<br /><p>Loading...</p>");
		$.get('/app/modules/vettrak/finder/content.cfm?lookup=dates&key='+$('#sessionKey').val()+'&course='+course.val()+'&course_month='+mnth.val()+'&course_location='+location.val(), function(data) {
		  $('#course_finder_content').html(data);
		});
	});

});
