function inArray(needle, haystack) {
    var length = haystack.length;
    for(var i = 0; i < length; i++) {
        if(haystack[i] == needle) return true;
    }
    return false;
}

$(function () {
	var target = "";
    var minlength = 5;
	var each_results = [];
	var all_results = [];
	var key_index = -1;
	var key_counter = 0;
	var value;
	var search_value;
    var search_tag;
    var search_results;
    var selected_course_id = 0;
    var search_box_value;
    var total_length = 0;
    var search_tags = ["autocomplete_site", "autocomplete_usa_zip", "autocomplete_canada_zip", "autocomplete_address", "autocomplete_course_name", "autocomplete_city", "autocomplete_state" ]
	var search_tags_header = ["Site Results", "US Zipcode Results", "Canada Zipcode Results", "Course Address Results", "Course Name Results", "City Results", "State Results"]
	
	$.each(search_tags, function(search_index, search_tag) {
    	each_results[search_index] = [];
 	});
 	
 	$("#search_box_button").click(function (eh) {
 		if (eh.keyCode != 13){
	 		value = $("#search_box").val();
	    	target = "/search/query/" + value;
	    	if (selected_course_id != 0)
	    		target = target + "&course_id=" + selected_course_id;
	    	window.location = "/process_search.php?search_string=" + value + "&course_id=" + selected_course_id;
    	}
 	});
 	
 	$(".header_search_form").focus(function (eh)	{
 		$("#search_box").val("");
 	});
 	
 	$("#search_box").blur(function (eh)	{
 		setTimeout(function(){
		    $("#autocomplete_results").slideUp(20);
	    	key_index = -1;
	    	$.each(search_tags, function(search_index, search_tag) {
		    	each_results[search_index] = [];
		    	$("#" + search_tag).html("");
		 	});
		 	$("#autocomplete_results").html("");
		 	search_results = [];
		 	$(".header_search_form").val("Search...");
	 	}, 250);
 	});
 	          	
    $("#search_box").keyup(function (eh) {
    	total_length = 0;
        value = $(this).val();
        search_value = value;
        key_counter = 0;
        
    	if (eh.keyCode == 38 && key_index != -1)	//up
    		key_index--;
		
		$("#autocomplete_results").children().children().each(function()	{
			if ($(this).attr("class") == 'autocomplete_item' && $(this).css("display") == 'block')
				total_length = total_length + 1;
		});
		
    	if (eh.keyCode == 40 && key_index < (total_length - 1))	{	//down
    		key_index++;
    	}

    	if (eh.keyCode == 13){	//enter
    		window.location = "/process_search.php?search_string=" + value + "&course_id=" + selected_course_id;
		}
        if (value.length >= minlength ) {
            $.ajax({
                type: "GET",
                url: "/autocomplete_search.php",
                data: {
                    'q' : value
                },
                dataType: "text",
                success: function(msg){
                    $.each(search_tags, function(search_index, search_tag) {
                    	
						if (msg.indexOf(search_tag) >= 0)	{
							$("#autocomplete_results").slideDown(1);
							
							search_results = msg.substring(msg.indexOf(search_tag) + search_tag.length);
							search_results = search_results.substring(0, search_results.indexOf("autocomplete_end"));
							search_results = search_results.split("\n")
	
							if (each_results[search_index].length == 0)	{
								$("#autocomplete_results").append("<div class='autocomplete_header' id='"+search_tag+"'><p>" + search_tags_header[search_index] + "</p></div>");
							}
							$.each(each_results[search_index], function(index, value) {
								if (!inArray(value, search_results))	{
									course_id = value.substring(0, value.indexOf(":"));
									$("#" + search_tag + "_" + course_id).slideUp(500);
									key_index = -1;
								}
							});
							$.each(search_results, function(index, value) {
								course_id = value.substring(0, value.indexOf(":"));
								
								if (key_counter == key_index){
									$("#" + search_tag + "_" + course_id).css({background:"#cccccc"});
									selected_course_id = course_id
								}
								else
									$("#" + search_tag + "_" + course_id).css({background:"#ffffff"});
									
								if (!inArray(value, each_results[search_index]))	{
									value = value.substring(value.indexOf(":") + 1);
									if ($.trim(value) != "")	{
										$("#" + search_tag).append("<div class='autocomplete_item' id='" + search_tag + "_" + course_id + "'><p>" + value + "</p></div>");
										$("#" + search_tag + "_" + course_id).css({display:"none"}).slideDown(500);
										$("#" + search_tag + "_" + course_id).click(function (e) {
											tmp_id = $(this).attr("id");
											tmp_id = tmp_id.split("_");
											tmp_id = tmp_id[tmp_id.length-1];
											window.location = "/process_search.php?search_string=" + search_value + "&course_id=" + tmp_id;
										});
									}
								}
								if ($.trim(value) != "")
									key_counter++;
							});
							each_results[search_index] = search_results;
						}
						else	{
							$("#" + search_tag).remove();
							each_results[search_index] = [];
						}
					});
                }
            });
        }
        else	{
        	$("#autocomplete_results").slideUp(200);
        	key_index = -1;
        	$.each(search_tags, function(search_index, search_tag) {
		    	each_results[search_index] = [];
		    	$("#" + search_tag).html("");
		 	});
		 	$("#autocomplete_results").html("");
		 	search_results = [];
        }
    });
});
