
function AutoComplete(bStr, oText, oDiv, nMaxSize)
{
//alert('In autocomplete.');
// initialize member variables
   this.oText = oText; // the text box
   this.oDiv = oDiv; // a hidden <div> for the popup auto-complete
   this.nMaxSize = nMaxSize;

// preprocess the texts for fast access
   db = new AutoCompleteDB();
//   var i, n = aStr.length;
//alert (n);
 //  for ( i = 0; i < n; i++ )
//   {
//alert(aStr[i]);
//      this.db.add(aStr[i]);
//   }

// attach handlers to the text-box
   oText.AutoComplete = this;
   oText.onkeyup = AutoComplete.prototype.onTextChange;
   oText.onblur = AutoComplete.prototype.onTextBlur;
} 

AutoComplete.prototype.onTextBlur = function()
{
   this.AutoComplete.onblur();
}

AutoComplete.prototype.onblur = function()
{
   this.oDiv.style.visibility = "hidden";
}

AutoComplete.prototype.onTextChange = function()
{
   this.AutoComplete.onchange();
}

AutoComplete.prototype.onchange = function()
{
   var txt = this.oText.value;

//   if (txt.length > 1)
//   {
      
      if (txt.length == 3)
      {
//         this.db = new AutoCompleteDB();
         reqstring = '/getCitySuggestions?partial=' + txt;
         new Ajax.Request(reqstring,
         {
            method:'get',
            requestHeaders: {Accept: 'application/json'},
            onSuccess: function(transport) 
            {
               json = transport.responseText.evalJSON(true);
               var newlist;
//jalert (json['cities'].length);
               for(var ndex=0;ndex<json['cities'].length;ndex++) 
               {
//alert(json['cities'][ndex]);
                  city = json['cities'][ndex];
//alert(city);
                  db.add(city);
//                  msg+= '\n' + city;
               }
//               alert(msg);
            }
         }
         );
      }
//   }
   if (txt.length > 2)
   {
// count the number of strings that match the text-box value.
      var nCount = db.getCount(txt);
//alert (nCount);
//alert (nMaxSize);

// if a suitable number then show the popup-div
      if ( (this.nMaxSize == -1 ) || ((nCount < this.nMaxSize) && (nCount > 0)) )
      {
// clear the popup div.
         while ( this.oDiv.hasChildNodes() )
            this.oDiv.removeChild(this.oDiv.firstChild);

// get all the matching strings from the AutoCompleteDB
         var aStr = new Array();
         db.getStrings(txt, "", aStr);

// add each string to the popup-div
         var i, n = aStr.length;
         for ( i = 0; i < n; i++ )
         {
            var oDiv = document.createElement('div');
            this.oDiv.appendChild(oDiv);
            oDiv.innerHTML = aStr[i];
            oDiv.onmousedown = AutoComplete.prototype.onDivMouseDown;
            oDiv.onmouseover = AutoComplete.prototype.onDivMouseOver;
            oDiv.onmouseout = AutoComplete.prototype.onDivMouseOut;
            oDiv.AutoComplete = this;
         }
         this.oDiv.style.visibility = "visible";
      }
      else // hide the popup-div
      {
         this.oDiv.innerHTML = "";
         this.oDiv.style.visibility = "hidden";
      }
   }
   else // hide the popup-div
   {
      this.oDiv.innerHTML = "";
      this.oDiv.style.visibility = "hidden";
   }
}

AutoComplete.prototype.onDivMouseDown = function()
{
   // set the text-box value to the word
   this.AutoComplete.oText.value = this.innerHTML;
}

AutoComplete.prototype.onDivMouseOver = function()
{
// assumes the existence of a CSS style called AutoCompleteHighlight
   this.className = "AutoCompleteHighlight";
}

AutoComplete.prototype.onDivMouseOut = function()
{
// assumes the existence of a CSS style called AutoCompleteBackground
   this.className = "AutoCompleteBackground";
} 

function AutoCompleteDB()
{
// set initial values.
   this.bEnd = false;
   this.nCount = 0;
   this.aStr = new Object;
}

AutoCompleteDB.prototype.add = function(str)
{
  // increment the count value.
   this.nCount++;
//alert(this.nCount);
//alert('adding the word ' + str);
   // if at the end of the string, flag this node as an end point.
   if ( str == "" )
      this.bEnd = true;
   else
   {
   // otherwise, pull the first letter off the string
      var letter = str.substring(0,1);
      var rest = str.substring(1,str.length);
//alert(letter + '  ' + rest);

   // and either create a child node for it or reuse an old one.
      if ( !this.aStr[letter] ) 
      {
//alert('adding new');
         this.aStr[letter] = new AutoCompleteDB();
      }
      this.aStr[letter].add(rest);
   }
}

AutoCompleteDB.prototype.getCount = function(str, bExact)
{
// if end of search string, return number
//alert ('str ' + str);
//alert (this.bEnd);
//alert (this.nExact);
//alert (this.nCount);
   if ( str == "" )
//alert ('string is null and ncount');
//      return 0;
      if ( this.bEnd && bExact && (this.nCount == 1) ) return 0;
      else return this.nCount;

            // otherwise, pull the first letter off the string
   var letter = str.substring(0,1);
   var rest = str.substring(1,str.length);

   // and look for case-insensitive matches
   var nCount = 0;
   var lLetter = letter.toLowerCase();
   if ( this.aStr[lLetter] )
      nCount += this.aStr[lLetter].getCount(rest, bExact && (letter == lLetter));

   var uLetter = letter.toUpperCase();
   if ( this.aStr[uLetter] )
      nCount += this.aStr[uLetter].getCount(rest, bExact && (letter == uLetter));

//alert (nCount);
   return nCount;
}

AutoCompleteDB.prototype.getStrings = function(str1, str2, outStr)
{
   if ( str1 == "" )
   {
  // add matching strings to the array
      if ( this.bEnd )
         outStr.push(str2);

        // get strings for each child node
      for ( var i in this.aStr )
          this.aStr[i].getStrings(str1, str2 + i, outStr);
    }
    else
    {
   // pull the first letter off the string
       var letter = str1.substring(0,1);
       var rest = str1.substring(1,str1.length);

      // and get the case-insensitive matches.
       var lLetter = letter.toLowerCase();
//alert('lLetter is ' + lLetter);
       if ( this.aStr[lLetter] )
          this.aStr[lLetter].getStrings(rest, str2 + lLetter, outStr);

       var uLetter = letter.toUpperCase();
       if ( uLetter != lLetter )
       {
//alert('uLetter is ' + uLetter);
          if ( this.aStr[uLetter] )
             this.aStr[uLetter].getStrings(rest, str2 + uLetter, outStr);
       }
   }
}

function createAutoComplete()
{
    var aNames =
    [
      "Hilton Head, SC",
      "Hilton Head Island, SC",
      "Savannah, GA",
      /* intermediate names removed for brevity */
      "Atlanta, GA"
    ];
//    alert("I made the list");
    new AutoComplete(
       aNames,
    document.getElementById('search_loc'),
    document.getElementById('theDiv'),
    15
    );
}

window.onload = function()
{
//    s_query = document.getElementById('search_query');

//    s_query.onfocus = function()
//    {
//        if(this.value == 'business name, category, or keyword')
//        {
//            this.value = '';
//            this.style.color = '#000';
//        }
//    }

   createAutoComplete();
}

function doSearch()
{
    srch_form = document.getElementById('srch_form');
    srch_form.submit()
}

function setDefaultLocation()
{
    new Ajax.Request('/userprefs/setdefaultlocation', {
        method: 'get',
        parameters: {defloc: $F('search_loc')},
        onSuccess: function(reply)
        {
            response = reply.responseText;
            $('defloc_status').setStyle({color:'#004400'});
            $('defloc_status').update('Set!');
        },
        onLoading: function()
        {
            $('defloc_status').update('Setting...');
        },
        onFailure: function()
        {
            $('defloc_status').setStyle({color:'#990000'});
            $('defloc_status').update('Unable to set!');
        }
    } );
}

function ieReturn(e)
{
    if(navigator.appVersion.indexOf('MSIE') != -1)
    {
        e.cancelBubble = true;
        var cc;
        if(e && e.which)
        {
            e = e;
            cc = e.which;
        }
        else
        {
            e = event;
            cc = e.keyCode;
        }

        if(cc == 13)
        {
            $('srch_form').submit();
            return false;
        }
        else
        {
            return true;
        }
    }

    return true;
}

function CheckSearch()
{
//    var search = document.getElementById('query').value;
//    var loc = document.getElementByID('location').value;
    var search = document.getElementById('search_query').value;
    var loc = document.getElementById('search_loc').value;
//    var search = "cats";
//    var loc = "dogs";
    if (search != "" && loc != "")
    {
        document.getElementById('srch_form').submit();
    }
    if (search == "")
    {
        alert("No search query was entered.  Please enter a search query and try again");
    }
    if (loc == "")
    {
        alert("No location was entered.  Please enter a search location and try again");
    }
}                                                    
