var srchtextid = "cosrchstr";
var srchformname = "conamesearch";
var srchresultsdivid = "results";
var srchnresults = 0;
var srchselectid = 0;
var srchsavesrchstr;

domReady(function(){    // execute the following upon completion of loading the DOM tree
    // store currently selected li node element in search results html fragment
    var curPos;
    
// create the results area
   var div = document.createElement("div");
   div.id = srchresultsdivid;
   div.className='srchsuggest';
   div.innerHTML = "<ul></ul>";
// SDC: add additional attributes to fix suggestion list position on page without moving existing content   
   div.style.position='absolute';  // enough by itself in firefox, overwrites "search" button in ie
   div.style.top = eval(curTop(id(srchtextid)) + id(srchtextid).offsetHeight) + "px";
   div.style.left = curLeft(id(srchtextid)) + "px";
// and add it in after the input box
   id(srchtextid).parentNode.appendChild(div);

   var keyevent = function(e) {
      keynum=e.keyCode;   // this works in firefox, chrome, safari-windows, and ie - e.which, this.keyCode don't work

// Get all search result items, represented as LI elements (with subtrees) in the html results
      var li = id(srchresultsdivid).getElementsByTagName("li");

// currently selected li entry in results html fragment is the (only) one with class=cur assigned
// get position in list of currently selected li tag - using index allows for cross-browser compatibility
      var lipos = -1;
      for ( var i = 0; i < li.length; i++ ) {
          if (hasClass(li[i], "cur"))
             lipos = i;
      }

      var newlipos;
// avoid error in case results list is empty of li elements
      if (li.length) {
           // assign class attribute indicating currently selected item in search results
         addClass( curPos, "cur" );
        
         if ( e.keyCode == 9 || e.keyCode == 13 ) { // If the [TAB] or [Enter] keys are pressed
            chooseSearchResult (curPos);  // set search text using label part of selected result element structure

            if (e.preventDefault)  // suppress normal action of key if supported by browser
               e.preventDefault();

            return false;
         } else if ( e.keyCode == 38 ) {  // If the up arrow key is presssed
            // change currently selected result item to previous one in the results list - 
            // if the current selection is first one, select the last one in the list
// sdc: cross-browser fix            return updatePos( curPos.previousSibling || li[ li.length - 1 ] );
                   if (lipos > 0)
                      newlipos = lipos - 1;
                   else 
                      newlipos = li.length - 1;

                   return updatePos( li[newlipos] );
                }
                else if ( e.keyCode == 40 ) {  // If the down arrow key is pressed
            // change currently selected result item to next one in the results list - 
            // if the current selection is the last one, select the first one in the list
// sdc: cross-browser fix             return updatePos( curPos.nextSibling || li[0] );
                        if (lipos < li.length - 1)
                           newlipos = lipos + 1;
                        else 
                           newlipos = 0;

                        return updatePos( li[newlipos] );
                     }

      }  // end if (li.length)

    // if search text has changed except for leading or trailing whitespace, 
    // clear current selected id (so it will not be removed from suggest list)
      var newsrchstr = strtrim(id(srchtextid).value + String.fromCharCode(keynum));
      if (newsrchstr.toLowerCase() != srchsavesrchstr) {
         srchselectid = 0;
      }

   }; // end assignment to variable keyevent of anonymous function definition

   var el = id(srchtextid);
   if (el.addEventListener) 
      el.addEventListener("keydown", keyevent, false);
   else
      el.attachEvent("onkeydown", keyevent);

    // Initialize the delayed input checks on our input
   delayedInput({
        // We're attaching to the input text field
      elem: id(srchtextid),         // sdc: change original q to to
        
        // Start searching only if input contains specified minimum number of characters
      chars: 3,

        // When the text field loses focus, close the results popup
//        focus: true,
      focus: false,      // avoid IE problem of not getting onclick event 
        
        // Handle when the result popup should be opened up
      open: function(q,open){
            // Get the last word out of the comma-separated list of words
            var w = strtrim( q.substr( q.lastIndexOf(',')+1, q.length ) );

            // Make sure that we're dealing with a word, at least
            if ( w ) {
                // clear any currently selected element in results list
               curPos = null;
                
                // Get the UL that holds all the results
               var results = id(srchresultsdivid).lastChild;
                
                // And empty it out
               results.innerHTML = "";
                
                // Do a request for new data
               ajax({
                    // Do a simple GET request to the CGI script which
                    // returns an HTML block of LI elements
                    type: "GET",
                    url: "xmlco_name_search.php?s=" + w,  // script to return search results as html 
                    // Watch for when the HTML comes back
                    onSuccess: function(html){
                       results.innerHTML = html; // insert items returned by search in results UL
                        // Go through LI items in html fragment returned by search
                       var li = results.getElementsByTagName( "li" );
// sdc: share number of result entries from currently defined search string using global var
                       srchnresults = li.length;
                       for ( var i = 0; i < li.length; i++ ) {
                            // If the current search selection ID matches this LI's id attribute, remove the LI
                          if ( li[i].id == srchselectid ) {
                             results.removeChild( li[i--] );
                          }
                          else {   // Otherwise, bind some events to the LI
                               // Whenever the user mouses over the LI,
                               // set it to be the currently hilighted one
                             li[i].onmouseover = function(){
                                                    updatePos(this);
                                                 };
                               // When the  is clicked
                             li[i].onclick = function(){
                                             // put current search results entry label in search text input
                                                 chooseSearchResult (this);
                                              // And focus back on the search text input again
                                                id(srchtextid).focus();
                                                id(srchtextid).value=id(srchtextid).value;  // force cursor to end of text

                                             };
                          }
                       }

                            // Go through the li elements in the search results html fragment
                       li = results.getElementsByTagName( "li" );
   
                        // If the displayed results list contains no items, the search input
                        // text either matches a single selected item (which is removed from
                        // the search list) or the search finds no matches
                       if ( li.length == 0 )
                          hide( id(srchresultsdivid) );  // if results list is empty hide it, otherwise
                       else {                            // display list with first element selected 
                           // Add 'odd' classes to alternate LI elements in search results subtree
                           // to give them a striping with suitable styling
                          for ( var i = 1; i < li.length; i += 2 )
                             addClass( li[i], "odd" );
                           // Set the first LI item in the search results list as the currently selected one
                          updatePos( li[0] );
                            // And then show the results
                          show( id(srchresultsdivid) );
                       }
                    }  // end function definition for ajax onsuccess argument
                });   // end ajax function call
            }  // end if (w)
        },  // end function definition defining delayedinput open argument
        // When the popup needs to be closed
        close: function(){
            // Hide the result set
            hide( id(srchresultsdivid) );
        }
    });  // end delayedinput function call
    


    // Set highlight to currently selected search result item by adding cur class to li in results html subtree
   function updatePos( elem ) {
      // Update the position to the currently selected element
      curPos = elem;
      // Get all the search results li elements
      var li = id(srchresultsdivid).getElementsByTagName("li");
      // Remove the 'cur' class from the currently selected one (by removing it from all)
      for ( var i = 0; i < li.length; i++ )
         removeClass( li[i], "cur" );
        
        // And add the 'cur' class to the current LI element based on the passed argument
      addClass( curPos, "cur" );
        
      return false;
   }

// Define search input text based on label included in element structure of passed search result item
   function chooseSearchResult( elem ) {
      srchselectid = elem.id;  // record id of selected item from search results

      var i;
      for (i=0; i < elem.childNodes.length; ++i)
      {
         if (elem.childNodes[i].className) {
            if (elem.childNodes[i].className == "hideconame") {
               id(srchtextid).value = strtrim(elem.childNodes[i].innerHTML);  // save string from element subtree
               srchsavesrchstr = strtrim(id(srchtextid).value.toLowerCase());
               break;
            }
         }
      }

        // Remove the selected li element from results html subtree
      elem.parentNode.removeChild( elem );
        
        // And hide the results list - if the selected item's text occurs in other items, the list will be un-hidden on refresh
      hide( id(srchresultsdivid) );
   }

});  // end domReady function call, which has form: domReady(function(){...});


// functions defined outside of domReady call
//*******************************************
// function to transfer control based on data context when submit button pressed

function srchcontroltransfer(inputid) {
var vrdir = get_parentdir();
var co_srchform_id = srchformname;  // global var holds search form id, can override if necessary for page html

var retval = true;
var srchstr = id(inputid).value;

if (strtrim(srchstr) == "") {
   alert("You must enter a nonblank search string.");
   retval = false;
}
else {
        // 1 match returned in most recent results list and 0 items in 
        // currently displayed html indicates an explicitly selected 
        // item whose displayed label matches no other item found by the search
   if (srchnresults == 1 && id(srchresultsdivid).getElementsByTagName("li").length == 0) {
//      id(co_srchform_id).action = vrdir+'review.php';
//       gotourl = vrdir + "review.php?c=" + srchselectid;
           // 3-6-09 generate url in static form
      gotourl = "/reviews/" + srchselectid +"/" + srchsavesrchstr + "/";
      gotourl = gotourl.replace(/ /g, "-");
      gotourl = gotourl.replace(/'/g, "-");

      location.href = gotourl;
      retval = false;
   }
   else {
     // id(co_srchform_id).action = vrdir+"search/index.php";
     id(co_srchform_id).action = location.pathname;   // set form to reload current page in current directory
   }
}

return retval;
}

// following found online at http://snipplr.com/view/3561/addclass-removeclass-hasclass/
function hasClass(ele,cls) {
	return ele.className.match(new RegExp('(\\s|^)'+cls+'(\\s|$)'));
} 

function addClass(ele,cls) {
	if (!this.hasClass(ele,cls)) ele.className += " "+cls;
}

function removeClass(ele,cls) {
	if (hasClass(ele,cls)) {
    	var reg = new RegExp('(\\s|^)'+cls+'(\\s|$)');
	ele.className=ele.className.replace(reg,' ');	
        }
}


// from codeproject autocomplete article
/* Offset position from top of the screen */
function curTop(obj){
	toreturn = 0;
	while(obj){
		toreturn += obj.offsetTop;
		obj = obj.offsetParent;
	}
	return toreturn;
}
function curLeft(obj){
	toreturn = 0;
	while(obj){
		toreturn += obj.offsetLeft;
		obj = obj.offsetParent;
	}
	return toreturn;
}
/* ------ End of Offset function ------- */

function strtrim(s) {
   return s.replace(/^\s+/,"").replace(/\s+$/, "");
}

function get_parentdir()
{
   var fullpath = location.pathname;
   var currdir = fullpath.substr(0,fullpath.lastIndexOf("/"));
   var parentdir = currdir.substr(0,currdir.lastIndexOf("/")) + "/";

   return parentdir;
}


