var isOpera=(navigator.userAgent.toLowerCase().indexOf("opera")!= -1);
var strLastValue = '';
var bMadeRequest = false;
var theTextBox;
var objLastActive;
var currentValueSelected = -1;
var bNoResults = false;
var responseJSON = '';
var resArray = [];
var hasMore = true;

function initSuggest(suggestURL) {
   //appendDropdown(createElement('span'));
   //createQueryObject(suggestURL);
   bindEvents();
   focusSearchBox();
}

function addHandler(objText) {
   Event.observe($(objText), 'keyup', giveOptions);
   if(isOpera){objText.onkeypress = giveOptions;}
}

function appendDropdown(element) {
   element.id = "spanOutput";
   element.className = "spanTextDropdown";
   document.body.appendChild(element);
}

function bindEvents() {
   Event.observe('submitButton', 'click', submitForm);      
   Event.observe('searchField', 'blur', doBlur);
}

function createElement(tag) {
   return document.createElement(tag);
}

function createQueryObject(suggestURL) {
   theTextBox = document.Form1.query;
   theTextBox.obj = setProperties(theTextBox, suggestURL);
}

function focusSearchBox() {
   theTextBox.focus();
}

function getTextBox() {
   return document.Form1.query;
}

function setProperties(xElem,xserverCode) {
   var props = {elem: xElem, serverCode: xserverCode};
   addHandler(xElem);
   return props;
}

function submitForm() {
   document.Form1.submit();
}

function giveOptions(e) {
   var intKey = -1;
      
   if(window.event) {
      intKey = event.keyCode;
      theTextBox = event.srcElement;
   }
   else {
      intKey = e.which;
      theTextBox = e.target;
   }
   
   if(theTextBox.value.length === 0 && !isOpera) {
      resArray = [];
      HideTheBox();
      strLastValue = '';
      bMadeRequest = false;
      return false;
   }
   
   if(objLastActive == theTextBox){
      if(intKey == 13) {
         grabAndSubmit();
         return false;
      }
      else if(intKey == 38) {
         MoveHighlight(-1);
         return false;
      }
      else if(intKey == 40) {
         MoveHighlight(1);
         return false;
      }
      else if(intKey == 27) {
         HideTheBox();
         return false;
      }
   }
   else if(intKey == 13) {
         grabAndSubmit();
         return false;
   }
   
   if(canMakeRequest())   {
      objLastActive = theTextBox;
      bMadeRequest = true;
      TypeAhead(theTextBox.value); 
   }
   else {
      if(theTextBox.value.length < 3) {
         HideTheBox();
      }
      else {
         BuildList(theTextBox.value);
      }
   }
   strLastValue = theTextBox.value;
}

function canMakeRequest() {
  // return ( theTextBox.value.length == 3 || (hasMore == "true" && theTextBox.value.length > 2));
  return ( theTextBox.value.length == 3);
}

function grabAndSubmit() {
   GrabHighlighted();
   theTextBox.blur();
   document.Form1.submit();
}
         
function TypeAhead(xStrText)  {
   var strParams = "?q=" + xStrText;
   var loader1 = new net.ContentLoader(theTextBox.obj.serverCode + strParams, BuildChoices, null, "GET", strParams);
}

function BuildChoices(){
   responseJSON = this.req.responseText.evalJSON();
   
   resArray = responseJSON;
   BuildList(strLastValue);
   bMadeRequest = false;
}

function BuildList(theText) {
   SetElementPosition(theTextBox);
   var theMatches = MakeMatches(theText);
   theMatches = theMatches.join().replace(/\,/gi,"");
   if(theMatches.length > 0) {
      $('spanOutput').innerHTML = theMatches;
      bNoResults = false;
   }
   else {
      currentValueSelected = -1;
      bNoResults = true;
      HideTheBox();
      objLastActive = null;
      //$('spanOutput').innerHTML = '';
   }
}

function SetElementPosition(theTextBoxInt){
   var selectedPosX = 0;
   var selectedPosY = 0;
   var theElement = theTextBoxInt;
   if (!theElement) {return;}
   var theElemHeight = theElement.offsetHeight;
   var theElemWidth = theElement.offsetWidth;
   while(theElement !== null){
      selectedPosX += theElement.offsetLeft;
      selectedPosY += theElement.offsetTop;
      theElement = theElement.offsetParent;
   }
   xPosElement = $('spanOutput');
   xPosElement.style.left = selectedPosX + 'px';
   xPosElement.style.width = theElemWidth + 'px';
   xPosElement.style.top = selectedPosY + theElemHeight + 'px';
   xPosElement.style.display = 'block';
   xPosElement.onmouseout = null;
   xPosElement.onmouseover = null;
}

var countForId = 0;
function MakeMatches(xCompareStr) {
   countForId = 0;
   var matchArray = [];
   var regExp = new RegExp(xCompareStr, 'i');
   if(responseJSON.suggestions){
      for(var i = 0; i < responseJSON.suggestions.length; i++) {
         var suggestion = responseJSON.suggestions[i];
         var theMatch = suggestion.name.match(regExp);
         console.log(theMatch);
         if(theMatch && matchArray.length < 10){
            matchArray[matchArray.length] = CreateUnderline(suggestion.name, xCompareStr,i, suggestion);
         }
      }
   }
   return matchArray;
}

var undeStart = "<span class='spanMatchText'>";
var undeEnd = "</span>";
var selectSpanStart = '<span style="width:100%; display:block;" class="spanNormalElement" onmouseover="SetHighColor(this);" onmouseout="clearMouseOut(this);"';
var selectSpanEnd ="</span>";

function CreateUnderline(xStr, xTextMatch, xVal, theSuggestion) {
   selectSpanMid = 'id="OptionsList_' + countForId + '" theArrayNumber="'+ xVal +'">';
   var regExp = new RegExp(xTextMatch,'i');
   var aStart = xStr.search(regExp);
   var matchedText = xStr.substring(aStart, aStart + xTextMatch.length);
   var newSpan = '<span style="float:right; margin-top:-14px; margin-left:-14px; padding-right:7px;">';
   if(theSuggestion.positionCode !== '') {
      newSpan += theSuggestion.positionCode + ' | ' + theSuggestion.teamCode;
   }
   else {
      newSpan += theSuggestion.teamCode;
   }
   newSpan += '</span>';
   countForId++;
   return selectSpanStart + selectSpanMid + xStr.replace(regExp,undeStart + matchedText + undeEnd) + newSpan + selectSpanEnd;
}

function MoveHighlight(xDir){
   newValue = parseInt(currentValueSelected, null) + parseInt(xDir, null);
   if(newValue > -1 && newValue < countForId){
      currentValueSelected = newValue;
      SetHighColor (null, true);
   }
}
         
function SetHighColor(theTextBox, notMouseOver){
   if(theTextBox){
      currentValueSelected =
      theTextBox.id.slice(theTextBox.id.indexOf("_")+1, theTextBox.id.length);
   }
   for(i = 0; i < countForId; i++){
      $('OptionsList_' + i).className = 'spanNormalElement';
   }
  
   if(!notMouseOver) {
      $('OptionsList_' + currentValueSelected).className = 'spanHighElement mouseOver';
   }
   else {
      $('OptionsList_' + currentValueSelected).className = 'spanHighElement';
   }
}

function clearMouseOut(toClear) {
  $(toClear).removeClassName('mouseOver');
}

function SetText(xVal){
   theTextBox.value = resArray.suggestions[xVal].name; //set text value
   $('spanOutput').style.display = "none";
   currentValueSelected = -1; //remove the selected index
}

function GrabHighlighted() {
   if(currentValueSelected >= 0) {          
      xVal = $('OptionsList_' + currentValueSelected).getAttribute("theArrayNumber");
      SetText(xVal);
      HideTheBox();
   }
}

function HideTheBox(){
   $('spanOutput').hide();
   currentValueSelected = -1;
}

function doBlur() {
   for(i = 0; i < countForId; i++){
      if($('OptionsList_' + i).hasClassName('mouseOver')) {
         grabAndSubmit();
         return;
      }
   }
   HideTheBox();
}
