       
    var SEARCH_RESULT_PANEL_ID = "searchResult";
    var NO_SEARCH_RESULT = "Nothing Available";
    YAHOO.util.Event.addListener(document.getElementById('searchbox'), "focus", enterSearchBox);
    function enterSearchBox () {
        if (this.value == NO_SEARCH_RESULT) {
            this.value = "";
           YAHOO.util.Dom.setStyle(this, "color", "black");
        }
    }
    function hideSearchResult() {
      if (searchResultPanel) {searchResultPanel.hide();}
    }


    autoCompleteJSFunction = new function()  {
      var constantCompleteDataSource = new YAHOO.util.XHRDataSource("/webservices/concept/find");
      constantCompleteDataSource.responseType= YAHOO.util.XHRDataSource.TYPE_XML;
	    constantCompleteDataSource.useXPath = false;
      constantCompleteDataSource.responseSchema = {
        resultNode: "concept", 
        fields: ["matchedText", {key:"uri", locator:"@url"},"cycl", "comment"]
      };
	    //     var constantCompleteDataSource = 
	    //new YAHOO.widget.DS_XHR('/webservices/concept/find', 
	    //			['concept', 'preferredNl', relevantUriTag(), 'cycl', 'comment']);
	    constantCompleteDataSource.scriptQueryParam = 'uriType=' + getUriType() + '&max=75&includeMatchedText=true&isExactMatch=false&conceptDetails=typical&str';  
//      constantCompleteDataSource.responseType = YAHOO.widget.DS_XHR.TYPE_XML;
      this.oAutoComp = new YAHOO.widget.AutoComplete('searchbox', 'autocompleteContainer', constantCompleteDataSource);
      this.oAutoComp.resultTypeList = false;
	    this.oAutoComp.minQueryLength=3;
      this.oAutoComp.maxResultsDisplayed=200;
      this.oAutoComp.maxCacheEntries=0; 
      this.oAutoComp.autoHighlight=false;
      this.oAutoComp.itemSelectEvent.subscribe(searchSelectionHelper);
      this.oAutoComp.dataReturnEvent.subscribe(hideSearchResult);
      YAHOO.util.Dom.setX(document.getElementById("autocompleteContainer"), YAHOO.util.Dom.getX(document.getElementById("searchbox")));
      this.oAutoComp.formatResult = formatOpenCycAutocompleteResult;
    }

	function formatOpenCycAutocompleteResult (oResultData, sQuery, sResultMatch) { 
	var uri = oResultData;
        var sKey = sResultMatch; // the entire result key 
        var sKeyQuery = sKey.substr(0, sQuery.length); // the query itself 
        var sKeyRemainder = sKey.substr(sQuery.length); // the rest of the result 
        // some other piece of data defined by schema 
        var uri = oResultData.uri;
        var cycl = oResultData.cycl; 
        var comment = oResultData.comment;
        if (comment == "") comment = "<i>No description or comment available.</i>";
        var aMarkup = ["<div class='searchresult' onmouseover='showTooltip(this.nextSibling,true)' onmouseout='hideTooltip()'>", 
		       "<span class='match'>",
                       sKeyQuery,
                       "</span>",
		       sKeyRemainder, 
	      " <span class='cycl'>", 
	      cycl,
	      "</span>", 
	      "</div>",
              "<span class='owl_tooltip' id='hover_", uri , "'style='display: none;' >" ,
                "<div class='comment_header'>", cycl, "</div>" ,
                "<div class='comment_body'>", comment, "</div>" ,
              "</span>"
             ]; 
	     return (aMarkup.join("")); 
	}

    function searchSelectionHelper(sType, aArgs) {
      var oMyAcInstance = aArgs[0]; // your AutoComplete instance 
      var elListItem = aArgs[1]; //the <li> element selected in the suggestion
      var aData = aArgs[2]; //array of the data for the item as returned by the DataSource 
      document.getElementById('selectedText').innerHTML = aData.matchedText;
      document.getElementById('selectedUri').innerHTML = aData.uri;
      search();
    }
       
  function searchSuccessFunction (o) {
        var entries = o.responseXML.getElementsByTagName("concept");
        var searchString = o.argument.searchString;
        if (entries.length > 1) {

            var searchBox = document.getElementById("searchbox");
            var panelConfig = {"visible":true,
                               "width": "600px",
                               "height": "100%",
                               "close": true
                              };
            if (!document.getElementById(SEARCH_RESULT_PANEL_ID)) {
                var resultBox = document.createElement("div");
                document.body.appendChild(resultBox);
                resultBox.id=SEARCH_RESULT_PANEL_ID;
                searchResultPanel = new YAHOO.widget.Panel(SEARCH_RESULT_PANEL_ID, panelConfig);
                searchResultPanel.setFooter(" ");
                addResize(SEARCH_RESULT_PANEL_ID, searchResultPanel);
            }
            searchResultPanel.setHeader("OpenCyc: " + decodeURIComponent(searchString) + 
                             " <span style='font-weight:normal'>(" + entries.length + " concepts)</span>");
            searchResultPanel.setBody("");
            searchResultPanel.render();
            var region = YAHOO.util.Dom.getRegion(searchBox);
            searchResultPanel.cfg.setProperty("context", [searchBox, "tl", "bl"]);
//            searchResultPanel.cfg.setProperty("y", YAHOO.util.Dom.getRegion(searchBox).bottom + 10);
//            searchResultPanel.cfg.setProperty("x","10");
//	    console.log("got some results")
            for (var i = 0; i < entries.length; i++) {
                searchResultPanel.appendToBody(convertSearchResultXMLToHTMLElt(entries[i]));
            }
            searchResultPanel.show();
        } else if (entries.length == 1) {
	    var curUri = entries[0].getAttribute("uri");
          window.location = curUri;
        } else if (entries.length == 0) {
          document.getElementById("searchbox").value=NO_SEARCH_RESULT;
          YAHOO.util.Dom.setStyle(document.getElementById("searchbox"),
				"color", "red");
          if (searchResultPanel) {searchResultPanel.hide()}
        }
      }

  var explicitRequest = null;
  var searchResultPanel = null;
       
  function convertSearchResultXMLToHTMLElt(xmlElt) {
    var newElt = document.createElement("div");
    YAHOO.util.Dom.addClass(newElt, SEARCH_RESULT_PANEL_ID);
    var uri = xmlElt.getAttribute("uri");
    var aka= xmlElt.getElementsByTagName("nl")[0] ? xmlElt.getElementsByTagName("nl")[0].firstChild.nodeValue : "";
    var cycL= xmlElt.getElementsByTagName("cycl")[0].firstChild.nodeValue;
    var title = xmlElt.getElementsByTagName("preferredNl")[0].firstChild.nodeValue; 
    var commentElts =  xmlElt.getElementsByTagName("comment");
    var comment = null;
    if (commentElts && commentElts.length > 0 && commentElts[0].childNodes.length > 0) {
       comment= commentElts[0].firstChild.nodeValue;
    }
    if (cycL && cycL.indexOf("(") == 0) {cycL = null;}
    if ((title && title.toLowerCase() == aka.toLowerCase()) ||
        (comment && comment.toLowerCase() == title.toLowerCase())) {
          if (cycL && cycL.toLowerCase() != title.toLowerCase()) aka = cycL;
          else aka = null;
       }
    var resultHTML = "<a class='conceptNL' href='" + uri + "'>" + title;
    if (aka) {
      resultHTML += " <span class='searchAdditionalNames'>[" + aka + "]</span>";
    }
    resultHTML += "</a><br/>";
    var decodedComment = comment ? comment.replace(/&lt;/g, "<").replace(/&gt;/g, ">") : null;
    if (decodedComment) resultHTML += decodedComment + "<br>";
    resultHTML += "<a class='url' href='" + uri + "'>" + uri + "</a>";
    newElt.innerHTML = resultHTML;
    return newElt;
  }


  function addResize(sPanelId, oPanel) {
     var IE_QUIRKS = (YAHOO.env.ua.ie && document.compatMode == "BackCompat"); 
     var IE_SYNC = (YAHOO.env.ua.ie == 6 || (YAHOO.env.ua.ie == 7 && IE_QUIRKS)); 
     var PANEL_BODY_PADDING = (10*2) // 10px top/bottom padding applied to Panel body element. The top/bottom border width is 0 
     var resize = new YAHOO.util.Resize(sPanelId, { 
                                        handles: ['br'], 
           	           autoRatio: false, minWidth: 300,
                           minHeight: 100, status: true });
     resize.on('resize', function(args) { 
       var panelHeight = args.height; 
       var headerHeight = this.header.offsetHeight; // Content + Padding + Border 
       var footerHeight = this.footer.offsetHeight; // Content + Padding + Border 
       var bodyHeight = (panelHeight - headerHeight - footerHeight); 
       var bodyContentHeight = (IE_QUIRKS) ? bodyHeight : bodyHeight - PANEL_BODY_PADDING; 
       YAHOO.util.Dom.setStyle(this.body, 'height', bodyContentHeight + 'px'); 
       if (IE_SYNC) { 
	 this.sizeUnderlay(); 
	 this.syncIframe(); 
       } 
     }, 
     oPanel, true); 
  }


    function deExplicitSearch() {
      var searchString = document.getElementById('searchbox').value;
      searchString = escape(searchString.replace(/^\s+|\s+$/g, ''));
      if ("" != searchString) {
        var request = '/webservices/concept/find?max=75&isExactMatch=false&conceptDetails=typical&str=' 
          + searchString;// + '&isExact=true';
        /*/if (explicitRequest != null) {
          YAHOO.util.Connect.abort(cObj);
        }*/
      searchCallback = {success: searchSuccessFunction,
                        argument: {searchString: searchString}
                       };
        explicitRequest = YAHOO.util.Connect.asyncRequest('GET', request, searchCallback);
      } else {
        // consider doing something here
      }
    }
       
    function search() {
      var text = document.getElementById('selectedText').innerHTML;
      var uri = document.getElementById('selectedUri').innerHTML;
      var searchString = document.getElementById('searchbox').value;
      if ((uri != null) && (text == searchString)) {
        window.location = uri;
      } else {
        deExplicitSearch();
      }
    }

function getUriType() {
    var versionedRegExp;
    if (!versionedRegExp) {versionedRegExp = new RegExp("\\d\\d.concept");}
    if (window.location.href.indexOf("/concept/en") >0) {
	return "/readable";
    } else if (window.location.href.search(versionedRegExp) > 0) {
        return "versioned";
    } else {
        return "current";
    }
}
function relevantUriTag () {
    var versionedRegExp;
    if (!versionedRegExp) {versionedRegExp = new RegExp("\\d\\d.concept");}
    if (window.location.href.indexOf("/concept/en") >0) {
	return "/readableUri/@uri";
    } else if (window.location.href.search(versionedRegExp) > 0) {
        return "/versionedUri/@uri";
    } else {
        return "@uri";
    }
}

       
