$(document).ready(function(){	
	// When the user changes the select box prepare a trigger
	$("#course_titles").change(function(){ 
		// Trim the URL to send the AJAX request
		var trimmedURL = this.value.replace("/courses/course", "");		
		// Send the request for the XML
		$.ajax({
		    url: '/index.php/ajax/register'+trimmedURL,
		    type: 'GET',
		    dataType: 'xml',
		    timeout: 1000,
		    error: function(){
		        alert('Error loading XML document');
		    },
			success: function(xml) {
			    // Set Course Reference
				$(xml).find('courseref').each(function(){
			        var courseRef = $(this).text();
					$("#course_ref").attr({ 
					          value: courseRef
					        });
			    });
				$("#course_dates").replaceWith('<select id="course_dates" name="course_dates"></select>');
			    $(xml).find('date').each(function(){
					// Check if no courses are available
					var text = $(this).text();
					if (text=="No dates available") {
						$("#course_dates").replaceWith('<input id="course_dates" name="course_dates" class="text" value="Sorry, no dates available" />');
						return;
					}
					// Dates are available so show them
					$("#course_dates").prepend('<option value="' + $(this).text() + '">'+ $(this).text() + '</option>');
	
					//alert(text);

			    }); 
			}
		});
	});

});

