var oDS = new YAHOO.util.XHRDataSource("/pubs/nameSearch_ajax.aspx");
oDS.responseType = YAHOO.util.XHRDataSource.TYPE_TEXT;
oDS.responseSchema = {
	recordDelim: "\n",
	fieldDelim: "\t"
};
oDS.maxCacheEntries = 50;
var myAutoComp = new YAHOO.widget.AutoComplete("pName","myContainer", oDS); 
myAutoComp.autoHighlight = false;
myAutoComp.suppressInputUpdate = true;
myAutoComp.maxResultsDisplayed = 25;
myAutoComp.minQueryLength = 3;

myAutoComp.setHeader("<a onclick=\"hideSuggest();return false;\" id=\"closeSuggest\" title=\"Close suggestions\"><img src=\"/img/icons/close.gif\" alt=\"\" /></a>");

var itemSelectHandler = function(sType, aArgs) {
	if (aArgs[2] && aArgs[2][1]){
		window.location = "/pubs/view/" + aArgs[2][1];
	}
};

myAutoComp.itemSelectEvent.subscribe(itemSelectHandler);

var sQueryLower;

myAutoComp.doBeforeLoadData = function(sQuery , oResponse , oPayload) {
	sQueryLower = sQuery.toLowerCase();
	return true;
}

myAutoComp.generateRequest = function (sQuery) {
    var result = "?query=" + sQuery;
    if (document.getElementById('ckToLetOnly').checked) {
        result += "&tl=1";
    }
    return result;
}

myAutoComp.formatResult = function(oResultData, sQuery, sResultMatch) {
	var mtch = sResultMatch.toLowerCase();
	var pubNameMatchIndex = mtch.indexOf(sQuery);

	var tmp = HighlightMatch(sResultMatch, sQuery, pubNameMatchIndex);

	var aMarkup = ["<div class=\"myCustomResult\">", 
	tmp,
	"</div>"]; 
	return (aMarkup.join("")); 
};

//document.getElementById('pName').focus();

function HighlightMatch(full, snippet, matchindex) {
    return full.substring(0, matchindex) + "<span class=\"mtch\">" + full.substr(matchindex, snippet.length) + "</span>" + full.substring(matchindex + snippet.length);
}

function hideSuggest() {
    if (myAutoComp) {
        myAutoComp.collapseContainer();
    }
}