/**
Project Name: Search Term AutoComplete
Author: Juwei
Description:  AJAX control for search term autocomplete project. This JS file do
the following assignments.
	1. Initiate dataSource for term search. The DataSource is from YUI, 
	it defined search url, data structure, data fields to return
	2. Initiate AutoComplete Object which is YUI AutoComplete standard.
	3. Add event to control item Select behavior. Any selection will trigger a search.<b> 
	4. Among the query configuration, we control the return number of records,
	data caching, maximum of terms shown in dropdown, minimum of chracters typed to
	trigger autoComplate, etc 
Notes: (1) To test in localhost, uncomment termsearchUrl
	(2) We temporarily turn off data caching, each typing will trigger Endeca search. 
	This is to avoid space in instance is eaten up by Term Search Returns. It is not
	surprised that your local machine get sluggish if turned ON caching.<b> 
	(3) "Term", "Rank", the two data field names are defined in TermQueryManager
	(4) Term Search is good for FLAT data format that YUI provided. FLAT format requires 
	the term must be shown as the first word in dropdown list, it is not working with
	our default matching pattern. So we chose JSON.<b>
	(5) search form must be in the name frmHeaderSearch or as existing search box 
	......more....See documents or commentd in TermQueryController, TermQueryManager	
	Please add notes here if any change is made in the file. 
*/
 
YAHOO.example.ACJson = new function(){
/*****************************************
DataSource Object
This section define DataSource for query
******************************************/

var termsearchUrl=    "/termsearch/termquery.html";
 // termsearchUrl ="http://" + window.location.host + "/termsearch/termquery.html";
  this.oACDS_Term= new YAHOO.widget.DS_XHR(termsearchUrl, ["ResultSet.Result","Term","Rank"]); 
 // Match results that *contain* the query string as well as results that start with query str
 this.oACDS_Term.queryMatchContains = true;
 // Disable the cache 
 this.oACDS_Term.maxCacheEntries = 0;
 // Match case sensitivity 
 this.oACDS_Term.queryMatchCase = false; 
 // Match results of query strings that are *subsets* of the current query string 
 this.oACDS_Term.queryMatchSubset = false;	 
 // define return data type/format, hash
 this.oACDS_Term.responseType = YAHOO.widget.DS_XHR.TYPE_JSON;
 // param sent to controller, term
 this.oACDS_Term.scriptQueryParam = "query";
 // control return output, controller imporse control on return number as well
 //termDataSource.scriptQueryAppend = "output=json&results=1000"; // Needed for YWS
 this.oACDS_Term.responseStripAfter = "<!-";
 // incase ENDECA has delay
 this.oACDS_Term.connTimeout = 3000;
 
 /************************************************
 AutoComplete Object
 This section define AutoComplete query and dropdown format 
 *************************************************/
 // "search" is input field div id
 //"searchContrinner is to show dropdown list
 this.oAutoCompTerm = new YAHOO.widget.AutoComplete("search","searchContainer", this.oACDS_Term); 
 	 this.oAutoCompTerm.maxResultsDisplayed = 10;
 	 // defined characters typed in order to trigger autoComplete
 	 this.oAutoCompTerm.minQueryLength = 3;
 	 this.oAutoCompTerm.typeAhead = true;
 	 // some browser has default autoComplete opened
 	 this.oAutoCompTerm.allowBrowserAutocomplete = false;
 	 // control dropdown list shown or not after you selected or in case of no matching
 	 this.oAutoCompTerm.alwaysShowContainer = false; 
 	 this.oAutoCompTerm.useIFrame = true; 
 	 this.oAutoCompTerm.useShadow = true; 
 	 // leave it for user to highlight with cursor or mouse
 	 this.oAutoCompTerm.autoHighlight = false; 
 	 // time delay before trigger Endeca query, we like it be quick
 	 this.oAutoCompTerm.queryDelay = 0;
 	 // Be aware, format function operate a row, not whole return data set	  
 	 this.oAutoCompTerm.formatResult = function(oResultItem, sQuery) {
 	    var inp=document.frmHeaderSearch.term.value;
 	    if (inp != "") {
 	       inp = inp.toLowerCase();
 	    }
 	    var inpArr = new Array();
 	    inpArr = inp.split(" ");
 	    var res=oResultItem[0];
 	    for (var ip = 0; ip < inpArr.length; ip++) { 	    
 	  	   if (inpArr[ip].length > 0) {
	 	  	   if (inpArr[ip] != "b"){ 	 	  	     
		 	     var re = new RegExp(inpArr[ip],"g"); 
		 	     if (res.match(re))  
		 	        res = res.replace(re,"<b>" + inpArr[ip] + "</b>");
		        } else {
		        var re = new RegExp(" b","g"); 
		 	     if (res.match(re))  
		 	        res = res.replace(re,"<b> b</b>");                    
                }		      
 	       }
	 	}
   		//return "<div id='termid'>" + res + " (" + oResultItem[1]   + ")</div>";
   		return "<div id='termid'>" +res + "</div>"; 
   		//return "<div id='termid'>" +oResultItem[0] + "</div>";
 	 };
 	 this.oAutoCompTerm.doBeforeExpandContainer = function(oTextbox, oContainer, sQuery, aResults) { 
	        var pos = YAHOO.util.Dom.getXY(oTextbox); 
	        pos[1] += YAHOO.util.Dom.get(oTextbox).offsetHeight + 2; 
	        YAHOO.util.Dom.setXY(oContainer,pos); 
	        return true; 
	  }; 
	 
	    // Stub for form validation 
	  this.validateForm = function() { 
	        // Validation code goes here 
	        return true; 
	  }; 
/*************************************************
Event Section
This section define item select action
After select an item, we submit search form.
**************************************************/ 
 	 var itemSelectHandler = function(sType, aArgs) {
	//YAHOO.log(sType);
	var oMyAcInstance = aArgs[0];
	var elListItem = aArgs[1];
	var aData = aArgs[2];
	// format name must be as below(current anywhere in main57) 
	document.frmHeaderSearch.term.value=aData[0];
	document.frmHeaderSearch.submit();	 
	}; 	 
 	 this.oAutoCompTerm.itemSelectEvent.subscribe(itemSelectHandler);
	
/***************************************************
Other Section
****************************************************/
};	
 