timeOutHandle = 0;
keyWords = '';
suggestionList = new Array();
mainElement = null;

window.onload = function(){
  AutoSuggest(document.getElementById('q'), new Array());
}

function trim(txt)
{
  return txt.replace(/^\s+|\s+$/g,"");
}

function googleSuggest()
{
  //q = document.getElementById('q');
  //val = q.value.replace(/^\s+|\s+$/g,"");
  if (keyWords.length > 0 && keyWords.match(/[a-zA-Z 0-9]$/))
  {
    var url = 'http://www.google.com/complete/search?hl=en&client=suggest&js=true&q='+encodeURIComponent(keyWords);
    return jsRemote(url);
  }
}

function jsRemote(url) {
 if (document && document.getElementsByTagName) {
  var head = document.getElementsByTagName('head')[0];
  var script = document.createElement('script');
  script.src = url;
  script.type = 'text/javascript';
  //alert(script.src);
  head.appendChild(script);
  return true;
 }
 return false;
}

// handle google sugest
google = {
 ac:{
      h:function(arr)
        {
          suggestionList = parseList(arr[0], arr[1]);
          refreshDropDown();
        }
     }
  }

function parseList(keyword, arr)
{
  for(i=0; i<arr.length; ++i)
  {
    str = arr[i]+"";
    //alert(str);
    arr[i] = hiliteWords(keyword, str.split(',', 1)+'');
  }
  return arr;
}

function hiliteWords(word, str)
{
  var intIndexOfMatch = str.indexOf( word );
  //alert(intIndexOfMatch + str + " " + word);
  while (intIndexOfMatch != -1)
  {
    str = str.replace( word, "," );
    if(word.length < 4) break;
    intIndexOfMatch = str.indexOf( word );
  }
  //var txt = str.replace(word,",");
  var hilite = "<span class=normal>"+word+"</span>";
  str = str.replace(/\,/g, hilite);
  return str;
}

function trimTag(str)
{
  str = str.replace(/<.*?>/g,'');
  //alert (str);
  return str;
}


function refreshDropDown()
{
  //alert (mainElement);
  var me = mainElement;
  if(me.getEligible())
  {
    me.createDiv();
    me.positionDiv();
    me.showDiv();
  }
  else
  {
    me.hideDiv();
  }
}

function setSuggestCall()
{
//alert('calling');
  if(timeOutHandle>0) clearTimeout(timeOutHandle);
  timeOutHandle = setTimeout(googleSuggest, 200);
}

function AutoSuggest(elem, suggestions)
{
  //The 'me' variable allow you to access the AutoSuggest object
  //from the elem's event handlers defined below.
  var me = this;

  //A reference to the element we're binding the list to.
  this.elem = elem;

  this.suggestions = suggestions;

  //Arrow to store a subset of eligible suggestions that match the user's input
  this.eligible = new Array();

  //The text input by the user.
  this.inputText = null;

  //A pointer to the index of the highlighted eligible item. -1 means nothing highlighted.
  this.highlighted = -1;

  //A div to use to create the dropdown.
  this.div = document.getElementById("autosuggest");
  //alert(document.getElementById("q").offsetWidth);
  this.div.style.width = '545px';

  //Do you want to remember what keycode means what? Me neither.
  var TAB = 9;
  var ESC = 27;
  var KEYUP = 38;
  var KEYDN = 40;
  var ENTER = 13;


  //The browsers' own autocomplete feature can be problematic, since it will
  //be making suggestions from the users' past input.
  //Setting this attribute should turn it off.
  elem.setAttribute("autocomplete", "off");

  //We need to be able to reference the elem by id. If it doesn't have an id, set one.
  if(!elem.id)
  {
    var id = "autosuggest" + idCounter;
    idCounter++;

    elem.id = id;
  }


  /********************************************************
  onkeydown event handler for the input elem.
  Tab key = use the highlighted suggestion, if there is one.
  Esc key = get rid of the autosuggest dropdown
  Up/down arrows = Move the highlight up and down in the suggestions.
  ********************************************************/
  elem.onkeydown = function(ev)
  {
    var key = me.getKeyCode(ev);

    switch(key)
    {
      case ENTER:
      case TAB:
      me.useSuggestion();
      break;

      case ESC:
      me.hideDiv();
      break;

      case KEYUP:
      if (me.highlighted > 0)
      {
        me.highlighted--;
      }
      me.changeHighlight(key);
      break;

      case KEYDN:
      if (me.highlighted < (me.eligible.length - 1))
      {
        me.highlighted++;
      }
      me.changeHighlight(key);
      break;
    }
  };

  /********************************************************
  onkeyup handler for the elem
  If the text is of sufficient length, and has been changed,
  then display a list of eligible suggestions.
  ********************************************************/
  elem.onkeyup = function(ev)
  {
    var key = me.getKeyCode(ev);
    switch(key)
    {
    //The control keys were already handled by onkeydown, so do nothing.
    case TAB:
    case ESC:
    case KEYUP:
    case KEYDN:
      return;
    default:

      if (me.inputText != this.value && this.value.length > 0)
      {
        var f = document.getElementById("cse-search-box");
        if(!(f == undefined))
        {
          f.q.style.cssText = '';
        }
        if(keyWords != trim(this.value))
        {
          keyWords = trim(this.value);
          me.inputText = this.value;
        }
        mainElement = me;
        setSuggestCall();

        /*
        me.getEligible();
        me.createDiv();
        me.positionDiv();
        me.showDiv();
       */
      }
      else
      {
        me.hideDiv();
      }
    }
  };

  elem.onblur = function(ev)
  {
    //alert(ev);
    me.hideDiv();
  };

  /********************************************************
  Insert the highlighted suggestion into the input box, and
  remove the suggestion dropdown.
  ********************************************************/
  this.useSuggestion = function()
  {
    //alert(1);
	//alert(this.highlighted);
    if (this.highlighted > -1)
    {
      var val = this.eligible[this.highlighted] + '';
      if(val != "null" && val != "undefined")
      {
        this.elem.value = trimTag(val);
      }
      this.hideDiv();
      //It's impossible to cancel the Tab key's default behavior.
      //So this undoes it by moving the focus back to our field right after
      //the event completes.
      setTimeout("document.getElementById('" + this.elem.id + "').focus()",0);
      if(!(topMenuType == undefined) && topMenuType != 'web')
      {
		//don't do anything, let user click on submit	  
      }		  
      else
      {
    	  document.getElementById('cse-search-box').submit();
      }
    }
  };

  /********************************************************
  Display the dropdown. Pretty straightforward.
  ********************************************************/
  this.showDiv = function()
  {
    this.div.style.display = 'block';
  };

  /********************************************************
  Hide the dropdown and clear any highlight.
  ********************************************************/
  this.hideDiv = function()
  {
    this.div.style.display = 'none';
    //this.highlighted = -1;
  };

  /********************************************************
  Modify the HTML in the dropdown to move the highlight.
  ********************************************************/
  this.changeHighlight = function()
  {
    var lis = this.div.getElementsByTagName('LI');
    for (i in lis)
    {
      //alert(i);
      //alert(lis[i]);
      var li = lis[i];

      if (this.highlighted == i)
      {
        li.className = "selected";
      }
      else
      {
        li.className = "";
      }
    }
  };

  /********************************************************
  Position the dropdown div below the input text field.
  ********************************************************/
  this.positionDiv = function()
  {
    var el = this.elem;
    var x = 0;
    var y = el.offsetHeight;

    //Walk up the DOM and add up all of the offset positions.
    while (el.offsetParent && el.tagName.toUpperCase() != 'BODY')
    {
      x += el.offsetLeft;
      y += el.offsetTop;
      el = el.offsetParent;
    }

    x += el.offsetLeft;
    y += el.offsetTop;

    this.div.style.left = x + 'px';
    this.div.style.top = y + 'px';
  };

  /********************************************************
  Build the HTML for the dropdown div
  ********************************************************/
  this.createDiv = function()
  {
    me.highlighted = -1;
    var ul = document.createElement('ul');

    //Create an array of LI's for the words.
    for (i in this.eligible)
    {
      var word = this.eligible[i];

      var li = document.createElement('li');
      var a = document.createElement('a');
      a.href="javascript:false";
      a.innerHTML = word;
      li.appendChild(a);

      if (me.highlighted == i)
      {
        li.className = "selected";
      }

      ul.appendChild(li);
    }

    this.div.replaceChild(ul,this.div.childNodes[0]);


    /********************************************************
    mouseover handler for the dropdown ul
    move the highlighted suggestion with the mouse
    ********************************************************/
    ul.onmouseover = function(ev)
    {
      //Walk up from target until you find the LI.
      var target = me.getEventSource(ev);
      while (target.parentNode && target.tagName.toUpperCase() != 'LI')
      {
        target = target.parentNode;
      }

      var lis = me.div.getElementsByTagName('LI');


      for (i in lis)
      {
        var li = lis[i];
        if(li == target)
        {
          me.highlighted = i;
          break;
        }
      }
      me.changeHighlight();
      //alert('tt');
    };

    /********************************************************
    click handler for the dropdown ul
    insert the clicked suggestion into the input
    ********************************************************/
    ul.onmousedown = function(ev)
    {
      //alert('clicked');
      me.useSuggestion();
      me.hideDiv();
      me.cancelEvent(ev);
      return false;
    };


    this.div.className="suggestion_list";
    this.div.style.position = 'absolute';

  };

  /********************************************************
  determine which of the suggestions matches the input
  ********************************************************/
  this.getEligible = function()
  {
    /*this.eligible = new Array();
    this.eligible[0] = 'hello';
    this.eligible[1] = 'hello1';*/
    this.eligible = suggestionList;
    return this.eligible.length;

    this.eligible = new Array();
    for (i in this.suggestions)
    {
      var suggestion = this.suggestions[i];

      if(suggestion.toLowerCase().indexOf(this.inputText.toLowerCase()) == "0")
      {
        this.eligible[this.eligible.length]=suggestion;
      }
    }
  };

  /********************************************************
  Helper function to determine the keycode pressed in a
  browser-independent manner.
  ********************************************************/
  this.getKeyCode = function(ev)
  {
    if(ev)      //Moz
    {
      return ev.keyCode;
    }
    if(window.event)  //IE
    {
      return window.event.keyCode;
    }
  };

  /********************************************************
  Helper function to determine the event source element in a
  browser-independent manner.
  ********************************************************/
  this.getEventSource = function(ev)
  {
    if(ev)      //Moz
    {
      return ev.target;
    }

    if(window.event)  //IE
    {
      return window.event.srcElement;
    }
  };

  /********************************************************
  Helper function to cancel an event in a
  browser-independent manner.
  (Returning false helps too).
  ********************************************************/
  this.cancelEvent = function(ev)
  {
    if(ev)      //Moz
    {
      ev.preventDefault();
      ev.stopPropagation();
    }
    if(window.event)  //IE
    {
      window.event.returnValue = false;
    }
  }
}

