$(document).ready(function(){
	function refreshSearchForm() {
		$.post(baseUrl + "/ajax/searchrefresh/",
			{state: $("#columnState").val()}, 
			function(xml) {
				refreshSubjects(xml);
				refreshTrainers(xml);
			}
		);
	}

	function refreshSubjects(xml) {
		var selected = $("#columnSelectedSubject").val();
		var options = '<option value="0">Select a Subject</option>';

		$("strand",xml).each(function(id) {
				strand = $("strand",xml).get(id);
				if( $(strand).attr('value') )
				{
					options += '<option value="strand_' + $(strand).attr('value') + '" style="background-color:#f0f1f1">' +  $(strand).attr('label') + '</option>';
				}
			$("kla",strand).each(function(id) {
				kla = $("kla",strand).get(id);
				options += '<option value="kla_' + $(kla).attr('kla_id') + '">' +  $(kla).attr('label') + '</option>';
				
				$("subject",kla).each(function(sid) {
					subject = $("subject",kla).get(sid);
					options += '<option value="subject_' + $(subject).attr('subject_id') + '">---' +  $(subject).text() + '</option>';
				});
			});
		});


		$("#columnSubjects").html(options);
		$("#columnSubjects [value='" + selected + "']").attr('selected', 'selected');
	}

	function refreshTrainers(xml) {
		var selected = $("#columnSelectedTrainer").val();
		var options = '<option value="0">Select a Trainer</option>';
		$("trainer",xml).each(function(id) {
			trainer = $("trainer",xml).get(id);
			options += '<option value="' + $(trainer).attr('trainer_id') + '">' + $(trainer).text() + '</option>';
		});
		$("#columnTrainers").html(options);
		$("#columnTrainers [value='" + selected + "']").attr('selected', 'selected');
	}
	
	$("#columnSubmit").click(function(){
	   $("#columnForm").submit();
	});
	
	$("#columnState").change(function(){
		refreshSearchForm();	
	});

	$("#columnKeywords").click(function(){
		$("#columnKeywords").val('');
	});
	
	refreshSearchForm();
});
