

search_string_for_sort = "";



function getData(v){

	
	var sTitle, sId, sType, sCode;

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

	var matchingCourses = [];

	var matched_pt = false;

	var matched_ft = false;

	var matched_flex = 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)



	

		pt = true;

		ft = true;

		flex = true;

	



	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))

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

		}

	}
	

	
		matchingCourses.push({id:-1,url:"http://www.abcol.ac.uk/courses/full-time/index.cfm",info:"ft",group:1});

	
		

	search_string_for_sort = v.toLowerCase();

	matchingCourses.sort(CompareByTitlePreferingSearchString);

	return matchingCourses;

}



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

	

		matchingCourses.push(

			{

				id:sId,

				value:sTitle,

				url:"/courses/detail.cfm?aset_course="+sId,

				info:"ft",

				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() {

	$('#courseSearch').autocomplete({

		get:getData,
		multi:false,
		delay:0,
		height:180,
		noresults:"No courses match your search criteria, try our <span class=\"nowrap\"><a id=\"atoz\" href=\"/courses/a-z.cfm\">A-Z</a> or <a id=\"atoz\" href=\"/courses/categories.cfm\">Course Categories</a>.</span>"

	});

});
