var cache = {};

function setupAutocomplete() {
	var terms = new Array();
	var search;
	var urlPath = window.location.protocol;
	if (urlPath === "http:") {
	  search = urlPath + "//" + window.location.host + "/searchresults?search="
	  urlPath += "//" + window.location.host + "/API/autosearch.aspx";
	}
	else {
	  urlPath = "";
	  urlPath += "http:" + window.location.host + "/API/autosearch.aspx";
	};
	$(".searchTiff").autocomplete({
	  delay: 1,
	  minLength: 3,
	  source: function (request, response) {
		  if (cache.term == request.term && cache.content) {
			  response(cache.content);
			  return;
		  }
		  if (new RegExp(cache.term).test(request.term) && cache.content && cache.content.length < 13) {
			  response($.ui.autocomplete.filter(cache.content, request.term));
			  return;
		  }
		  var term = request.term,
			  element = this.element;

		  $.ajax({
			  type: "GET",
			  contentType: "application/json; charset=utf-8",
			  url: urlPath,
			  data: { "mytext": request.term, "pathname": "/filmsandschedules/tiffbelllightbox/2011", "apikey": "seckey4tiff2011" },
			  dataType: "text",
			  success: function (data) {
				  cache.term = request.term;
				  cache.content = data.split(",");
				  var terms = data.split(",");
				  response(terms);
			  },
			  error: function (jqXHR, textStatus, errorThrown) {
				  if (textStatus !== null) {

				  }
			  }
		  });
	  },
	  select: function (event, ui) {
		  var goto = ui.item.value;
		  if (goto != "") {
			window.location.href = encodeURI(search + goto);
		}
	  }
	});
}
$.ui.autocomplete.prototype._renderItem = function (ul, item) {
	ul.removeAttr("style");
	  var term = this.term.split(' ').join('|');
	  var re = new RegExp("(" + term + ")", "gi");
	  var t = item.label.replace(re, '<span class="highlight">$1</span>');
	  return $("<li></li>")
	.data("item.autocomplete", item)
	.append("<a>" + t + "</a>")
	.appendTo(ul);
};      
