if (!this.YAHOO) {YAHOO = {};}
if (!this.YAHOO.ybb) {YAHOO.ybb = {};}

YAHOO.Fp.utf8_decode = function(sUTFText) {  
	
/* Utility function to decode UTF8 encoded text */	
	
        var string = "";  
        var i = 0;  
        var c = c1 = c2 = 0;  
        while ( i < sUTFText.length ) {  
            c = sUTFText.charCodeAt(i);  
            if (c < 128) {  
                string += String.fromCharCode(c);  
                i++;  
            }  
            else if((c > 191) && (c < 224)) {  
                c2 = sUTFText.charCodeAt(i+1);  
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));  
                i += 2;  
            }  
            else {  
                c2 = sUTFText.charCodeAt(i+1);  
                c3 = sUTFText.charCodeAt(i+2);  
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));  
                i += 3;  
            }  
        }  
        return string;  
    }

YAHOO.Fp.getNormalisationRules = function() {

/*
This obscure looking function returns Neil Crosby's original array of Normalisation rules.
It's needed to avoid having to enter foreign characters into Rosetta which would be devoured by it.
- marcov
*/
	
var aNormalisationData = [
		['A', ['A', '%c3%80', '%c3%81', '%c3%82', '%c3%83']],
		['AE', ['%c3%86', '%c3%84', 'AE']],
		['C', ['%c3%87', 'C']],
		['E', ['E', '%c3%88', '%c3%89', '%c3%8a', '%c3%8b']],
		['I', ['I', '%c3%8c', '%c3%8d', '%c3%8e', '%c3%8f']],
		['D', ['D', '%c3%90']],
		['N', ['%c3%91', 'N']],
		['O', ['%c3%92', '%c3%93', '%c3%94', '%c3%95', 'O']],
		['OE', ['%c3%96', '%c3%98', 'OE']],
		['U', ['U', '%c3%99', '%c3%9a', '%c3%9b']],
		['UE', ['%c3%9c', 'UE']],
		['Y', ['Y', '%c3%9d']],
		['TH', ['TH', '%c3%9e']],
		['ss', ['%c3%9f', 'ss']],
		[' ', [" |'|\\\-"]]
		];
var oNormalisationRules = Array();
for(i=0;i<aNormalisationData.length;i++) {
   sJoined = aNormalisationData[i][1].join('|');
   oNormalisationRules.push(Array(aNormalisationData[i][0], YAHOO.Fp.utf8_decode(unescape(sJoined)))); 
   }

return oNormalisationRules;
}

YAHOO.Fp.AutoSuggest = function() {
   return {

        oACDS: null,
        lastResponse: null,

        oNormalisationRules:YAHOO.Fp.getNormalisationRules(),

        setDataSource: function(oAutocomplete, toggle) {
          if(toggle == 'on') {
	          oAutocomplete.dataSource = YAHOO.Fp.oACDS;
            }
          else {
	//alert('dummy DS set');
	          oAutocomplete.dataSource = YAHOO.Fp.oDummyACDS;
            }
        },

        resetAutoComplete: function() {
	//alert('resetAutoComplete called');
	if(document.getElementById('ysearchcontainer')) {
			document.getElementById('ysearchcontainer').innerHTML = '';
		}
            YAHOO.util.Event.removeListener("vsearchtabs", "click");
			YAHOO.util.Event.removeListener('disablesayt', 'click');
			YAHOO.util.Event.removeListener('enablesayt', 'click');				
			},

		createAutoComplete: function() {
	//alert('createAutoComplete called');	    
		    YAHOO.Fp.AutoSuggest.resetAutoComplete();
          var elSearchBox = document.getElementById('p');
            	YAHOO.Fp.oACDS = new YAHOO.widget.DS_XHR("proxy.php", ["gossip.results","key"]);
            	YAHOO.Fp.oACDS.scriptQueryParam = "query";
            	YAHOO.Fp.oACDS.scriptQueryAppend = "dbid=default&nresults=10&output=json";
            	YAHOO.Fp.oACDS.queryDelay = 0; 
                YAHOO.Fp.oDummyACDS = new YAHOO.widget.DS_JSArray([]); 
          // if we already have a container, ditch it

          if(document.getElementById('ysearchcontainer')) {
	     document.getElementById('searchbox').removeChild(document.getElementById('ysearchcontainer'));
          }

             var elSearchContainer = document.createElement('div');
             elSearchContainer.id = 'ysearchcontainer'; 
             elSearchBox.parentNode.appendChild(elSearchContainer);
             YAHOO.util.Event.addListener(elSearchBox, "keypress", YAHOO.Fp.AutoSuggest.keyPressed);
                document.getElementById('ysearchcontainer').style.display = 'block';



	        YAHOO.Fp.oAutoComp = new YAHOO.widget.AutoComplete("p","ysearchcontainer", YAHOO.Fp.oACDS);
              if(YAHOO.cookie.get('autocomplete') == 'off') {
                   YAHOO.Fp.AutoSuggest.setDataSource(YAHOO.Fp.oAutoComp, 'off');
              }
              else {
                   YAHOO.Fp.AutoSuggest.setDataSource(YAHOO.Fp.oAutoComp, 'on');
                   document.getElementById('enablesayt').style.display = 'none';
                   document.getElementById('p').setAttribute('autocomplete', 'off');
              }
          YAHOO.Fp.oAutoComp.animVert = false; 
          YAHOO.Fp.oAutoComp.allowBrowserAutocomplete = false; 
          YAHOO.Fp.oAutoComp.itemSelectEvent.subscribe(YAHOO.Fp.AutoSuggest.myOnItemSelect);

          YAHOO.Fp.oAutoComp.setFooter("<p><a id='disablesayt' href='/'><!!>Turn search suggestions off</!!></a></p>");

          YAHOO.util.Event.addListener('disablesayt', 'click', YAHOO.Fp.AutoSuggest.doConfigChange, YAHOO.Fp.oAutoComp);
          YAHOO.util.Event.addListener('enablesayt', 'click', YAHOO.Fp.AutoSuggest.doConfigChange, YAHOO.Fp.oAutoComp);
          YAHOO.util.Event.addListener("vsearchtabs", "click", YAHOO.Fp.AutoSuggest.clickTabs, YAHOO.Fp.oAutoComp);	
          YAHOO.Fp.oAutoComp.textboxFocusEvent.subscribe(function() {
            this.sendQuery(elSearchBox.value);
          }, YAHOO.Fp.oAutoComp, true);
          YAHOO.Fp.oAutoComp.autoHighlight = false;
		},
		
        clickTabs: function (e, obj) {
////alert('clicked a tab');
        // Switches the DS on or off depending on which searchtab was clicked

        if(document.getElementById('vsearchtabs').getElementsByTagName('LI')[0].className.match('on'))  {
	//alert('first clicked '+document.getElementById('vsearchtabs').getElementsByTagName('LI')[0].className);
	if(YAHOO.cookie.get('autocomplete') != 'off') {
		  	YAHOO.Fp.AutoSuggest.createAutoComplete();	
          	YAHOO.Fp.AutoSuggest.setDataSource(YAHOO.Fp.oAutoComp, 'on');
			}
          }
        else {
	//alert('other clicked ' + document.getElementById('vsearchtabs').getElementsByTagName('LI')[0].className);
          YAHOO.Fp.AutoSuggest.setDataSource(obj, 'off');
          }
        },

        init: function() {
	//alert('init ran');
          // overwriting the real _onTextboxKeyDown so that ENTER does not stop the event
          YAHOO.widget.AutoComplete.prototype._onTextboxKeyDown = function(v,oSelf) {
              var nKeyCode = v.keyCode;
              
              switch (nKeyCode) {
                  case 9: // tab
                      if(oSelf.delimChar && (oSelf._nKeyCode != nKeyCode)) {
                          if(oSelf._bContainerOpen) {
                              YAHOO.util.Event.stopEvent(v);
                          }
                      }
                      // select an item or clear out
                      if(oSelf._oCurItem) {
                          oSelf._selectItem(oSelf._oCurItem);
                      }
                      else {
                          oSelf._toggleContainer(false);
                      }
                      break;
                  case 13: // enter
                      if(oSelf._nKeyCode != nKeyCode) {
                          if(oSelf._bContainerOpen) {
                              //YAHOO.util.Event.stopEvent(v);
                          }
                      }
                      if(oSelf._oCurItem) {
                          oSelf._selectItem(oSelf._oCurItem);
                      }
                      else {
                          oSelf._toggleContainer(false);
                      }
                      break;
                  case 27: // esc
                      oSelf._toggleContainer(false);
                      return;
                  case 39: // right
                      oSelf._jumpSelection();
                      break;
                  case 38: // up
                      YAHOO.util.Event.stopEvent(v);
                      oSelf._moveSelection(nKeyCode);
                      break;
                  case 40: // down
                      YAHOO.util.Event.stopEvent(v);
                      oSelf._moveSelection(nKeyCode);
                      break;
                  default:
                      break;
              }
          };

          YAHOO.Fp.AutoSuggest.createAutoComplete();

          YAHOO.Fp.oAutoComp.formatResult = function(aResultItem, sQuery) {
             var sKey = aResultItem[0]; // the entire result key
             
             // split the key on any | characters and use the first segment
             var aKey = sKey.split('|');
             sKey = aKey[0];
             
             // now normalise the query and result
             var normalisedQuery  = YAHOO.Fp.AutoSuggest.normalise(sQuery.toUpperCase());
             var normalisedResult = YAHOO.Fp.AutoSuggest.normalise(sKey.toUpperCase());

             // now, look for the normalised query in the normalised result
             // but still use the ORIGINAL result for display
             var sQueryHighlighted = sKey;
             var iQueryPos = normalisedResult.indexOf(normalisedQuery);
             if ( -1 != iQueryPos ) {
               var iHighlightLength = normalisedQuery.length + ( sKey.length - normalisedResult.length )
               sQueryHighlighted = sKey.substring(0, iQueryPos)
                                 + '<strong>'
                                 + sKey.substring(iQueryPos, iQueryPos + iHighlightLength)
                                 + '</strong>'
                                 + sKey.substring(iQueryPos + iHighlightLength);
             }

             return sQueryHighlighted;
          };
        },
        
        keyPressed: function(e, obj) {
          if ( 13 == e.keyCode) {
            YAHOO.Fp.AutoSuggest.doFormSubmit();
          }
        },
        
        myOnItemSelect: function(sType, aArgs) {
          // add an extra "sugg" field to the form
          // because of IE, we need to duplicate one of the existing hidden fields
          var elSugg = null;
          var elsFr = document.getElementsByName("fr");
          if ( elsFr.length > 0 ) {
            elSugg = elsFr[0].cloneNode(true);
            elSugg.name = 'sugg';
            elSugg.value = '1';
          }
          
          // finally, submit
          YAHOO.Fp.AutoSuggest.doFormSubmit( elSugg);
        },
        
        doFormSubmit: function( elSugg ) {
          // find the form that we're in and submit it
          var elSearchBox = document.getElementById('p');
          var elParent = elSearchBox.parentNode;
          while ( null !== elParent ) {
            if ( 'form' == elParent.tagName.toLowerCase()) {
              if ( elSugg ) {
                elParent.appendChild(elSugg);
              }

              elParent.submit();
              return;
            }
            elParent = elParent.parentNode;
          }
        },
        
        normalise: function(sInput) {
          var rules = YAHOO.Fp.AutoSuggest.oNormalisationRules;
          for ( var i=rules.length - 1; i >= 0; i--) {
            var sIn = rules[i][1];
            var sOut = rules[i][0];
            var regEx = new RegExp(sIn, 'g');
            
            sInput = sInput.replace(regEx, sOut);
          }
          
          return sInput;
        },
        
        setAutoCompleteCookie: function(sToggle)  {
           YAHOO.cookie.set('autocomplete', sToggle);
        },

        doConfigChange: function(e, obj) {
	//alert('doConfigChange called');
          /* toggles config on or off */
          YAHOO.util.Event.stopEvent(e);
          var sToggle = YAHOO.cookie.get('autocomplete');
          if(sToggle != 'off') {
            // set cookie
            YAHOO.Fp.AutoSuggest.setAutoCompleteCookie('off');
            // if we're here then we want to stop suggestions from being given to the user.
            // first, we stop them on this page load
            // by giving the autocomplete module something empty to chew on
            YAHOO.Fp.AutoSuggest.setDataSource(YAHOO.Fp.oAutoComp, 'off');
            // now remove the current dropdown from the screen
            document.getElementById('enablesayt').style.display = 'block';
          } else {
            YAHOO.Fp.AutoSuggest.setAutoCompleteCookie('on'); 
            YAHOO.Fp.AutoSuggest.setDataSource(YAHOO.Fp.oAutoComp, 'on');
            document.getElementById('enablesayt').style.display = 'none';
            YAHOO.Fp.themes.toggle();
			YAHOO.Fp.AutoSuggest.createAutoComplete();
          }       
          document.getElementById('p').focus();    
        }
    };
} ();
YAHOO.util.Event.onContentReady("p", YAHOO.Fp.AutoSuggest.init);
