

search_string_for_sort = "";



function getData(v){

	
	var com = document.getElementById("com").checked;

	var sTitle, sId, sType, sCode;

	var re = new RegExp("\\b" + v,"i");

	var matchingCourses = [];

		
	var matched_com = false;

	//  matchingCourses(id: is set to the array index from the complete JSON data array or -1 for the headings,

	//  matchingCourses(value: is the course description,

	//  matchingCourses(url: is the url of the course,

	//  matchingCourses(info: used by jqueryAutocomplete.js to set the class name of the course when displaying the course in the SAYT list)




	for(var i=0;i<course_data.length;i++)

	{

		sTitle = course_data[i].title;

		sType = course_data[i].type;

		sCode = course_data[i].code;

		sId = course_data[i].id;

		

		if(sTitle.match(re))

		{

			if (sType == "C") {

				PushCourse(matchingCourses, sTitle, sType, sId, sCode);

				matched_com = true;

			} 		

		}

	}

	

	if (matched_com) {

		matchingCourses.push({id:-1,value:"Community",url:"http://www.abcol.ac.uk/community/courses.cfm",info:"com",group:1});

	}
		

	search_string_for_sort = v.toLowerCase();

	matchingCourses.sort(CompareByTitlePreferingSearchString);

	return matchingCourses;

}



function PushCourse(matchingCourses, sTitle, sType, sId, sCode){

	if (sType == "C") {

		matchingCourses.push(

			{

				id:sId,

				value:sTitle,

				url:"http://www.abcol.ac.uk/community/course-detail.cfm?course_id_arg="+sId,

				info:"com",

				group:1				

			}

		);

	
	} 

}




function CompareByTitlePreferingSearchString(a, b) {

	if (a.group < b.group){

		return -1;	

	}else if (a.group > b.group){

		return +1;

	}else if (a.id == -1 && b.id != -1){

		return -1;

	}else if (a.id != -1 && b.id == -1){

		return +1;

	}

	var value_a = a.value.toLowerCase();

	var value_b = b.value.toLowerCase();

	var a_at_start = (value_a.indexOf(search_string_for_sort) == 0);

	var b_at_start = (value_b.indexOf(search_string_for_sort) == 0);

	if (a_at_start && !b_at_start) {

		return -1;

	} else if (b_at_start && ! a_at_start) {

		return +1;

	} else if (value_a < value_b) {

		return -1;

	} else if (value_a > value_b) {

		return +1;

	} else {

		return 0;

	}

}


$(document).ready(function() {	
	$('#theSearch').autocomplete({
		get:getData,
		multi:false,
		delay:0,
		height:180,
		noresults:"No courses match your search criteria, go to our <span class=\"nowrap\"><a id=\"atoz\" href=\"/courses/index.cfm\">main course section</a> for more options.</span>"
	});
});
