﻿// ** function getObj(name) **
// parameters: name = id of the object to get
// performs: sets the variable to the DOM object associated with the ID
// returns: object (x)
function getObj(strName)
{
  if (document.getElementById)
  {
    return document.getElementById(strName);
  }
  else if (document.all)
  {
    return document.all[strName];
  }
  else if (document.layers)
  {
    return document.layers[strName];
  } 
  else 
  {
    return null;
  }
}

// ** function fill AutoComplete **
// parameters:  result - pipe-delimited list of matching entries
// performs: Clears list, then fills matching values
// returns: none
function fillAutoComplete(strResult) 
{
    var divResults = getObj(strResultDivName);
    
    strFields = strResult.split('|');  // split the results into a string[]
    var strOptionString = "";
    
    if(strFields.length >= 1 && strFields[0] != "")
    {
        divResults.style.display = "block"
        var strOptionID;
        for (var i = 0; i <  strFields.length; i++)
        {
             //strOptionString += "<a href=\"javascript:Choose('" + strFields[i] + "'); \"><div class=\"" + strOptionCSS + "\" onmouseover=\"this.className='" + strOptionHighlightedCSS + "'\" onmouseout=\"this.className='" + strOptionCSS + "'\">" + strFields[i] + "</div></a>\n"; // add Results to result group
             //var id = i * 2;
             var txtQuery = getObj(strQueryBoxName);
             var highlitedText = GetSearchStringHighlights(txtQuery.value, strFields[i]);
             strOptionString += "<a href=\"javascript:MouseChoose('" + strFields[i] + "'); \"><div class=\"" + strOptionCSS + "\" id='" + 
                divResults.id + i + "'" + "\" onmouseover=\"SetAutoCompleteSelectedItem(this.id, true)\"\" onmouseout=\"SetAutoCompleteSelectedItem(this.id, false);\">" +  highlitedText + "</div></a>\n"; // add Results to result group
        }
    } 
    else 
    {
        divResults.style.display = "none"
    }
            
    divResults.innerHTML = strOptionString; //add result group to Div
}

// ** function Choose **
// parameters:  strSelectedTerm - selected value
// performs: Fills Querybox with selected value, and submits if AutoPostBack is enabled
function Choose(strSelectedTerm)
{
  var txtQuery = getObj(strQueryBoxName);
  var divResults = getObj(strResultDivName);
  var retVal = false;
  divResults.style.display = "none";
  
  if(txtQuery.value != strSelectedTerm)
  {
    strSelectedTerm = strSelectedTerm.replace(RegExp("<b>","gi"), "");
    strSelectedTerm = strSelectedTerm.replace(RegExp("</b>","gi"), "");
    txtQuery.value = strSelectedTerm;
    retVal = true;
  }
  else
  {
    divResults.style.display = "none";
  }
 
  return retVal;
}

function SetTextOfSelectedItem()
{
     if(ctrlCurrentSelection != null)
    {
        return Choose(ctrlCurrentSelection.innerHTML);
    }
}

function MouseChoose(strSelectedTerm)
{
  var txtQuery = getObj(strQueryBoxName);
  var divResults = getObj(strResultDivName);
  divResults.style.display = "none";
  
  if(txtQuery.value != strSelectedTerm)
  {
    strSelectedTerm = strSelectedTerm.replace(RegExp("<b>","gi"), "");
    strSelectedTerm = strSelectedTerm.replace(RegExp("</b>","gi"), "");
    txtQuery.value = strSelectedTerm;
  }
  else
  {
    divResults.style.display = "none";
  }


  if(blnAutoPostBack)
  {
        var submitButton = getObj(strSubmitButtonName);
        submitButton.click();
  }
  
}

// ** function GetSearchStringHighlights(searchString, resultText) **
// parameters:  searchString - search string typed by user
//              resultText - string returned from server that contains the search string
// performs: Highlights all the instances of searchString inside resultsText.
// returns: The string with bolded highlights of the search string in the text.
function GetSearchStringHighlights(searchString, resultText)
{
    var indexOfSearchString = resultText.toLowerCase().indexOf(searchString.toLowerCase());
    var splitResultText = resultText.substring(indexOfSearchString, searchString.length);
    var boldedResultText = '';
    var replaceString = '<b>' + splitResultText + '</b>';
        
    boldedResultText = resultText.replace(RegExp(splitResultText,"g"), replaceString);
    boldedResultText = boldedResultText.replace(RegExp(splitResultText.toUpperCase(),"g"), replaceString.toUpperCase());
    boldedResultText = boldedResultText.replace(RegExp(splitResultText.toLowerCase(),"g"), replaceString.toLowerCase());
    boldedResultText = boldedResultText.replace(RegExp("<b><b>","gi"), "<b>");
    boldedResultText = boldedResultText.replace(RegExp("</b></b>","gi"), "</b>");
    
    return boldedResultText;
}

// ** function onError(message) **
// parameters:  message - error message to be appended
// performs: pops up a Javascript alert when there's an error
// returns: none
function onError(strMessage) 
{
    alert("Error:\n" + strMessage);
}


function HideAutoSearch()
{
    var d = getObj('AutoCompleteResultsHome');
    if (d == null)
        d = getObj('AutoCompleteResults')
    
    if (d != null)
        eval(d).style.display = "none";
}

function FormSubmit(e)
{
	if ( typeof(ctrlCurrentSelection) == 'undefined' )
		return ( true );

    if(e == null)
    {
        if(navigator.appName.indexOf('Internet Explorer') > 0)
        {
            SetTextOfSelectedItem();
            var submitButton = getObj(strSubmitButtonName);
           // submitButton.click();
            return true;
        }
        else
        {
            SetTextOfSelectedItem();
            return true;
        }
    }
}

function FormKeyDown(e, form)
{
    var keycode;
    if(e)
        keycode = e.keyCode;
    else if (event && event.which == 13)
        keycode = event.which;
    
    if (keycode)	
    {
        if(keycode == 13)
        {
//            SetTextOfSelectedItem();
//            var submitButton = getObj(strSubmitButtonName);
//            submitButton.click();
        }
        
        // Arrow Up
        if(keycode == 38)
        {
           HandleUpDownArrowEvents(-1);
           
        }else if(keycode == 40)// Arrow Down
        {
            HandleUpDownArrowEvents(1);
        }
        else
        {
            if(ctrlCurrentSelection != null)
                SetItemUnselcted(ctrlCurrentSelection);
            GetAutoComplete();    
            var divResults = getObj(strResultDivName);
            divResults.style.display = "block";
        }
     
    }else
    {
        GetAutoComplete();    
        GetAutoComplete();
        var divResults = getObj(strResultDivName);
        divResults.style.display = "block";
    }
    
   
    return true;
}

function HandleUpDownArrowEvents(step)
{
    var allItems = GetAutoCompleteItems();
    var divResults = getObj(strResultDivName);
    divResults.style.display = "block";
    
    ctrlCurrentSelection = GetSelectedItem();
        
    if(ctrlCurrentSelection != null) 
    {
        ChangeAutoCompleteSelection(ctrlCurrentSelection, step);
    }
    else
    {
        // No itmes are selected so select either the first one or the last one in the list
        if(allItems.length > 0)
        {
            var itemToSelect = null;
            if(step > 0)
            {
                itemToSelect = allItems[0];
            }else
            {
                itemToSelect = allItems[allItems[allItems.length - 1].id];
            }
            SetItemSelected(itemToSelect);
        }
    }
    
  
//    if(navigator.appName.indexOf('Internet Explorer') < 0)
//    {
//        //divResults.focus();
//        //selObj = window.getSelection();
//        //window.alert(selObj);
//    }
    
}

function SetAutoCompleteSelectedItem(itemDivId, onOrOff)
{
    var divItem = getObj(itemDivId);
    ctrlCurrentSelection = GetSelectedItem();
    if(ctrlCurrentSelection != null)
    {
        SetItemUnselcted(ctrlCurrentSelection);
    }
    
    if(onOrOff)
    {
        SetItemSelected(divItem);
    }
   
}

function ChangeAutoCompleteSelection(selectedItem, step)
{
    // Set current node to normal
    var allNodes = GetAutoCompleteItems();
    SetItemUnselcted(selectedItem);

    var i = 0;
    var index = 0;
    for(i = 0; i < allNodes.length; i++)
    {
        if(selectedItem == allNodes[i])
        {
            index = i;
            break;
        }        
    }

    index = index + step;
    
    // Check to see if we are at the beginning or end and set index to other end
    if(index < 0)
        index = allNodes.length - 1;
    else if( index >= allNodes.length)
        index = 0;
    
    // Change the next or previous node active    
    var nextNode = allNodes[index];
    
    SetItemSelected(nextNode);
}

function GetAutoCompleteItems()
{
    var divResults = getObj(strResultDivName);
    return divResults.getElementsByTagName('div');    
}

// Search the div for the currently selected item and returns it.
function GetSelectedItem()
{
    var allItems = GetAutoCompleteItems();
    var selectedItem = null;
    var i = 0;
    for(i=0; i < allItems.length; i++)
    {
        var curNode = allItems[i];
        var classAttr = curNode.className;
        if(classAttr == strOptionHighlightedCSS)
        {
            selectedItem = curNode;
            break;
        }
    }
    
    return selectedItem;
}

function SetItemSelected(item)
{
    item.className = strOptionHighlightedCSS;
//    item.style.fontWeight = 'bold';
    ctrlCurrentSelection = item;
}

function SetItemUnselcted(item)
{
    item.className = strOptionCSS;
//    item.style.fontWeight = 'normal';
    ctrlCurrentSelection = null;
}