$(document).ready(function() {
	$("#searchboxform").bind("keyup", function(evt) {updateCourseList(evt);});
	$("#searchboxform").bind("change", function(evt) {doUpdateCourseList();});
	try {
		$(".sortable").tablesorter();
	} catch (err) {}
	$(".ajax-loader").hide();
});

function updateCourseList(e) {
	if (window.updateSearchTimeout) clearTimeout(window.updateSearchTimeout);
	if (e.keyCode == 13) {
		doUpdateCourseList();
	} else {
		window.updateSearchTimeout = setTimeout(doUpdateCourseList, 2000);
	}
	
}

function doUpdateCourseList(){
	var keyword = $("#searchbox input[name=keyword]").val();
	var action;
	var type = $('#searchboxform input[name=searchFormType]:checked').val();
	if (type == 'user') {
		action = "usersearch";
		if (keyword.length < 3) 
			return;
		showHeader('Users');
	}
	else {
		action = "index";
		showHeader('Courses');
	}
	showAjaxLoader(true);
	
	$.ajax({
		url: action,
		type: "GET",
		data: {
			ajax: true,
			keyword: keyword,
			status: $("#searchboxform select[name=status]").val(),
			time: new Date().getTime()
		},
		success: function(resp) {
			$("#results-table").html(resp);
			showAjaxLoader(false);
			$(".sortable").tablesorter();
			if (typeof addFeaturesToCourseList == "function") addFeaturesToCourseList();
			
		}
	});
	
}
function showHeader(header) {
	$("#courseHeader").html(header);
}

function showAjaxLoader(show) {
	if (show) {
		$(".ajax-loader").show();
	} else {
		$(".ajax-loader").hide();
	}
}