$(document).ready(function(){

$.widget( "custom.catcomplete", $.ui.autocomplete, {
		_renderMenu: function( ul, items ) {
			var self = this,
				currentCategory = "";
			$.each( items, function( index, item ) {
				if ( item.category != currentCategory ) {
					ul.append( "<li class='ui-autocomplete-category'>-- " + item.category + " --</li>" );
					currentCategory = item.category;
				}
				self._renderItem( ul, item );
			});
		}
});

$('#sitesearch-button').css("display", "none");
$('#sitesearch-anchor').css("display", "inline");


 var termTemplate = "<span class='ui-autocomplete-term'>%s</span>";


/* overload the renderitem prototype */
$.ui.autocomplete.prototype._renderItem = function (ul, item) {

            if (!item.url){
                item.url = "/PageRender/decVanilla/sitesearch.htm?sitesearch_search=" + item.label;
            }

            item.label = item.label.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + $.ui.autocomplete.escapeRegex(this.term) + ")(?![^<>]*>)(?![^&;]+;)", "gi"), "<strong>$1</strong>");
            var icon = '';

if (item.type){
         
// work out the image path from the type
switch (item.type){
   
    case "CustomDataType19":
       imagePath = "srnews16.png";
       break;


    case "PDF":
    case "MSWord":
        imagePath = "srdoc16.png";
        break;

    case "CustomDataType4":
        imagePath = "srcal16.png";
        break;

    case "CustomDataType9":
        imagePath = "srperson16.png";
        break;

    
      case "CustomDataType18":
        imagePath = "srmouse16.png";
        break;


    default: 
       imagePath = "sreye16.png";
       break;
}


   icon = "<img src='Direct/" + imagePath + "' />";
	         
} else {
   icon = "";
}	      
            

            return $("<li></li>")
                    .data("item.autocomplete", item)
                    .append("<a>" + icon + item.label + "</a>")
                    .appendTo(ul);
        };



$( "#mainsearch" ).catcomplete({
	delay: 0,
	source: "/SiteSearch?adhocsearchtypes=CustomDataType18||DecoratedContent",
	select: function (event, ui) {
		$(event.target).val(ui.item.value);
		window.location = ui.item.url;
		return false;
	}
	});



		


// Now regexp replace any occurrences of the term in site search
if ($('#mainsearch').val()){
    var term = $('#mainsearch').val();
    $('#sitesearch1 .m').each(function(){
    
    $(this).html($(this).html().replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + $.ui.autocomplete.escapeRegex(term) + ")(?![^<>]*>)(?![^&;]+;)", "gi"), "<strong>$1</strong>"));

    });

}



});

