var _SCinp = null;
var _SCsearch = null;
var _SCtimeout = 0;
var _SCrefocus = null;
var _SCnextcontrol = null;

var _SChibc = "#3366cc";
var _SChifc = "white";

var _SCnohibc = "white";
var _SCnohifc = "black";

var _SCselhibc = "navy";
var _SCselhifc = _SChifc;

var _SCscrollBy  = 20;  // tbs, this will have to be computed from font size.
var _SChtDivLine = 20;  // tbs, this will have to be computed from font size.


function setnonhighlight (c)
{
  if (c.parentDiv.parentSelect.type == "select-multiple" && 
      c.selectIndex >= 0                                 && 
      c.parentDiv.parentSelect.options[c.selectIndex].selected)
  {
    c.style.backgroundColor=_SCselhibc;
    c.style.color=_SCselhifc;
  }
  else
  {
    c.style.backgroundColor=_SCnohibc;
    c.style.color=_SCnohifc;
  }
}


function unhighlightAll (c)
{
  var n = Math.round(c.scrollTop / _SChtDivLine);
  if (c)
  {
    for (var i = n; i < n + 20; i++)
    {
      if (i >= c.childNodes.length) break;
      var ce = c.childNodes[i];
      setnonhighlight(ce);
    }
  }
}

function setHighlighted (c, h)
{
  if (c)
  {
    if (h)
    {
      if (c.parentDiv.parentSelect.type == "select-multiple" && 
          c.selectIndex >= 0                                 && 
          c.parentDiv.parentSelect.options[c.selectIndex].selected)
      {
         c.style.backgroundColor=_SCselhibc;
         c.style.color=_SCselhifc;
      }
      else
      {
        c.style.backgroundColor=_SChibc;
        c.style.color=_SChifc;
      }
    }
    else
    {
      setnonhighlight(c);
    }
  }
}

function mouseDownMulti (c, event)
{
  makeSelection (c, true);
  if (c.parentDiv.parentSelect.onclick)
  {
    c.parentDiv.parentSelect.onclick();
  }
}

var _scMouseDown=function(event)
{
  if (this.parentDiv.parentSelect.type == "select-multiple")
  {
     mouseDownMulti (this, event);
     return;
  }
  makeSelection (this, true);
  if (this.parentDiv.parentSelect.onclick)
  {
    this.parentDiv.parentSelect.onclick();
  }
};

var _scMouseOver=function()
{
  unhighlightAll(this.parentDiv.parentSelect.suggestDiv.inputControl.suggestsDiv);
  if(this.parentDiv.highlightedSpan) {
    setHighlighted(this.parentDiv.highlightedSpan, false);
  }
  setHighlighted(this,true)
  this.parentDiv.highlightedSpan = this;
};

var _scMouseOut=function()
{
  setHighlighted(this,false);
  this.parentDiv.highlightedSpan = null;
};

function setSelectionRange(i, ss, se) {
  if (i.setSelectionRange) 
  {
    i.setSelectionRange(ss, se);
  }
  else if (i.createTextRange) 
  {
    var r = i.createTextRange();
    r.collapse(true);
    r.moveEnd('character', se);
    r.moveStart('character', ss);
    r.select();
  }
}

function refocusSelect()
{
  if (_SCrefocus)
  {
    _SCrefocus.focus();
  }
  _SCrefocus = null;
};

function refocusNext()
{
  try
  {
    if (_SCnextcontrol)
    {
      _SCnextcontrol.focus();
      if (_SCnextcontrol.tagName == "INPUT" && _SCnextcontrol.type == "text")
      {
	 setSelectionRange(_SCnextcontrol,0,_SCnextcontrol.value.length);
      }
    }
  } 
  catch (ex)
  {
  }
  _SCnextcontrol = null;
}

var _scTextBlur=function()
{
  if (_SCinp)
  {
    if(navigator&&navigator.userAgent.toLowerCase().indexOf("msie")!=-1){
      var ae = null;
      try
      {
        ae = document.activeElement;
      } 
      catch (err)
      {
        this.focus();
        return;
      }
      if (ae && (ae.id == "_scMatches" || ae.id == "_scMatchSpan"))
      {
        this.focus();
        return;
      }
    }
    showHideSuggest (this.parentSelect, false);
  }
};

var _scDivScroll = function()
{
  this.justScrolled=true;
};

function makeDynamicSelection(ctl, idx) {
    // Get the value selected from the dynamic list
    //
    var sel = ctl.rtSuggest.lastSearchResults[idx].disp;

    // Search through the options and see if this
    // one exists.
    //
    var selidx = -1;
    if (ctl.options != null) {
        for (var i = 0; i < ctl.options.length; i++) {
            if (ctl.options[0].text.toLowerCase() == sel.toLowerCase()) {
                selidx = i;
                break;
            }
        }
    }

    // If not found, add it in and select it
    //
    if (selidx == -1) {
        var val = ctl.rtSuggest.lastSearchResults[idx].value;
        var opt = new Option(sel, val, true, true);
        try {
            ctl.add(opt, ctl.length);
        }
        catch (ex) {
            ctl.add(opt, null);
        }
    } else {
        ctl.options[selidx].selected = true;
    }
    
}

function makeSelection (c, refocus)
{

  if (!c) return;

  if (c.selectIndex == -3)
  {
    return;
  }
  
  if (c.selectIndex == -2)
  {
    c.parentDiv.parentSelect.suggestDiv.inputControl.showAll = true;
    recreateSuggestionDiv (c.parentDiv.parentSelect.suggestDiv.inputControl);
    setTimeout("checkSuggestInput(true);",0);
    return;
  }

  if (c.selectIndex >= 0) {

    // Handle selection of underlying select control
    // based on if it is dynamic or not
    //
    if (c.parentDiv.parentSelect.p_isDynamic) {
      makeDynamicSelection(c.parentDiv.parentSelect, c.selectIndex);
    } else {
      c.parentDiv.parentSelect.options[c.selectIndex].selected = !c.parentDiv.parentSelect.options[c.selectIndex].selected;
    }

    // Invoke the onchange event handler
    //
    if (c.parentDiv.parentSelect.onchange)
    {
      c.parentDiv.parentSelect.onchange();
    }
  }
  
  if (c.parentDiv.parentSelect.type != "select-multiple") {
  
      showHideSuggest (c.parentDiv.parentSelect, false);
  
      if (refocus)
      {
        _SCrefocus = c.parentDiv.parentSelect;
        setTimeout ("refocusSelect();", 0);
      }
  }
  
}

function createMatchSpan(p,si,text,selStart,selEnd)
{
  var ft  = "";
  var ftc = "";
  var f = p.parentSelect.sfontClass;
  if (f)
  {
    ft  = "<font class='" + f + "'>";
    ftc = "</font>";
  }
  var c = document.createElement("SPAN");
  c.id="_scMatchSpan";
  c.style.overflow="hidden";
  c.style.height=_SChtDivLine+"px";
  c.style.wordWrap="normal";
  c.style.display="block";
  c.style.paddingLeft="3";
  c.style.paddingRight="3";
  c.style.color="black"
  if (selStart < 0)
  {
    c.innerHTML = ft + text + ftc;
  }
  else
  {
    c.innerHTML = ft + text.slice(0, selStart) + "<strong>" + text.slice(selStart,selEnd) + "</strong>" + text.slice(selEnd) + ftc;
  }
  c.parentDiv   = p;
  c.selectIndex = si;
  c.onmousedown = _scMouseDown;
  c.onmouseover = _scMouseOver;
  c.onmouseout  = _scMouseOut;
  return c;
}

function createTopInputSpan()
{
  var c = document.createElement("SPAN");
  c.style.display="block";
  c.style.paddingLeft="3";
  c.style.paddingRight="3";
  c.style.overflow="hidden";
  c.style.color="black"
  c.style.height=_SChtDivLine+"px";
  c.style.wordWrap="normal";
  return c;
}

function createInputSpan()
{
  var c = document.createElement("SPAN");
  c.style.display="block";
  c.style.overflow="hidden";
  c.style.cssFloat="left";
  c.style.width="100%";
  c.style.height=_SChtDivLine+"px";
  c.style.wordWrap="normal";
  return c;
}

function createSuggestInput()
{
  var c = document.createElement("INPUT");
  c.style.width="100%";
  c.style.color="black";
  c.style.value="XXXXXX";
  c.style.height=_SChtDivLine+"px";
  c.onkeydown=_scSuggestInputKeyHandler;
  c.onblur=_scTextBlur;
  c.id = "_scSuggestInput";
  return c;
}

function createCloseSuggestion()
{
  var c = document.createElement("A");
  c.innerHTML = "Close";
  c.href="javascript:doCloseSuggest();"
  return c;
}

function createSuggestionsDiv(numVisible, parElem)
{
  var c = document.createElement("DIV");
  c.id="_scMatches";
  c.style.overflow = "auto";
  c.style.cssFloat="left";
  c.style.textAlign="left";
  c.style.borderRight="0px";
  c.style.borderLeft="0px";
  c.style.borderTop="0px";
  c.style.borderBottom="0px";
  c.style.paddingRight="0";
  c.style.paddingLeft="0";
  c.style.paddingTop="0";
  c.style.paddingBottom="0";
  c.style.width="100%";
  c.style.height=(_SChtDivLine * numVisible) + "px";
  c.highlightedSpan=null;
  c.highlightedSpanIndex=-1;
  c.onscroll=_scDivScroll;
  c.parentSelect=parElem;
  c.justScrolled=false;
  return c;
}

function createSuggestDiv (parElem, numVisible, maxResults, sfontClass)
{

  // Create an IFRAME element that will occlude everything
  // under the suggest control

  var sf = document.createElement("IFRAME");
  sf.src="nullpage.htm";
  sf.style.zIndex="1";
  sf.style.frameBorder="0px";
  sf.style.scrolling="no";
  sf.style.display="block";

  setOccludeFramePosition(parElem, sf);
  
  sf.style.visibility="hidden";
  sf.style.position="absolute";
  sf.style.backgroundColor="white";
  sf.style.height = _SChtDivLine * (numVisible + 1) + "px";
  document.body.appendChild(sf);
  parElem.occludeFrame = sf;

  // Make the suggest div
  //

  var sd = document.createElement("DIV");
  sd.id="suggestDiv";
  sd.style.borderRight="black 1px solid";
  sd.style.borderLeft="black 1px solid";
  sd.style.borderTop="black 1px solid";
  sd.style.borderBottom="black 1px solid";
  sd.style.zIndex="2";
  sd.style.paddingRight="0";
  sd.style.paddingLeft="0";
  sd.style.paddingTop="0";
  sd.style.paddingBottom="0";
  
  setSuggestDivPosition(parElem, sd);
  
  sd.style.visibility="hidden";
  sd.style.position="absolute";
  sd.style.backgroundColor="white";
  
  document.body.appendChild(sd);
  parElem.suggestDiv = sd;

  // Create the first span containing sub-spans that contain the input control
  //
  var topSpan = createTopInputSpan ();
  var inputSpan = createInputSpan ();

  sd.appendChild(topSpan);
  topSpan.appendChild(inputSpan);

  // Create the input control and the close control.
  //
  var inp = createSuggestInput();
  var cl  = createCloseSuggestion();
  inputSpan.appendChild(inp);

  if (parElem.p_isDynamic) {
      inp.onfocus = _scSuggestInputFocusHandler;
  }

  // Create the div that holds the suggestions
  //
  var sgsd = createSuggestionsDiv(numVisible, parElem);
  sd.appendChild(sgsd); // restore!

  // Setup input control pointers and backpointers
  //
  inp.parentSelect   = parElem;
  inp.parentDiv      = sd;
  inp.suggestsDiv    = sgsd;
  inp.maxResults     = maxResults;
  inp.showAll        = false;
  inp.numVisible     = numVisible;
  inp.nextInTabOrder = findNextControl(parElem);
  sd.inputControl    = inp;
  sd.parentSelect    = parElem;
  parElem.sfontClass = sfontClass;

  return sd;
}

function setOccludeFramePosition(parElem, sf)
{
  sf.style.left=calculateOffsetLeft(parElem)+"px";
  sf.style.top=calculateOffsetTop(parElem)+"px";
  sf.style.width=parElem.offsetWidth + "px";
}

function setSuggestDivPosition(parElem, sd)
{
  sd.style.left=calculateOffsetLeft(parElem)+"px";
  sd.style.top=calculateOffsetTop(parElem)+"px";
  sd.style.width=parElem.offsetWidth + "px";
}

var _searchMouseOver = function()
{
    this.src = "../../acc/../acc/SiteImages/1/SCsearch_Rollover.gif";
}

var _searchMouseOut = function()
{
    this.src = "../../acc/../acc/SiteImages/1/SCsearch.gif";
}

var _searchClick = function()
{
  showHideSuggest(this.parentSelect, true);
  this.parentSelect.suggestDiv.inputControl.focus();
  if (this.parentSelect.onclick)
  {
    this.parentSelect.onclick();
  }

}

function ptInRect(ptx, pty, rsx, rsy, rex, rey)
{
  if (ptx >= rsx & ptx <= rex && pty >= rsy && pty <= rey) return true;
}

function occludeTestOnTags(c, tname)
{
  var els = document.getElementsByTagName(tname);
  if (els.length == 0) return false;
  
  var csx = parseInt(c.style.left.replace("px",""));
  var cex = csx + 16;
  var csy = parseInt(c.style.top.replace("px",""));
  var cey = csy + 16;
  
  for (var i = 0; i < els.length; i++)
  {
    var el = els[i];
    if (el.offsetHeight > 0 && el.offsetWidth > 0)
    {
      var esx = calculateOffsetLeft(el);
      var eex = esx + el.offsetWidth - 1;
      var esy = calculateOffsetTop(el);
      var eey = esy + el.offsetHeight - 1;
      
      if (ptInRect (csx, csy, esx, esy, eex, eey)) return true;
      if (ptInRect (cex, cey, esx, esy, eex, eey)) return true;
    }
  }
  return false;
}

function occludeTest(c)
{
  if (occludeTestOnTags(c,"IMG")) return true;
  if (occludeTestOnTags(c,"INPUT")) return true;
  if (occludeTestOnTags(c,"SELECT")) return true;
  if (occludeTestOnTags(c,"TEXTAREA")) return true;
  return false;
}

function nextControl (c, tname)
{
  var nxc = null;
  var ssf = 9999;
  var els = document.getElementsByTagName(tname);
  if (els.length == 0) return null;
  for (var i = 0; i < els.length; i++)
  {
    var el = els[i];
    if (el.tabIndex)
    {
      if (el.tabIndex > c.tabIndex && el.tabIndex < ssf)
      {
        nxc = el;
        ssf = nxc.tabIndex;
      }
    }
  }
  return nxc;
}

function findNextControl(c)
{
  var cti = c.tabIndex;
  var ntc = null;
  var ssf = 9999;
  var ntx;
  
  ntc = nextControl(c,"INPUT");
  if (ntc && ntc.tabIndex) ssf = ntc.tabIndex
  
  ntx = nextControl(c,"SELECT");
  if (ntx && ntx.tabIndex && ntx.tabIndex < ssf)
  {
    ntc = ntx;
    ssf = ntc.tabIndex
  }
  
  ntx = nextControl(c,"TEXTAREA");
  if (ntx && ntx.tabIndex && ntx.tabIndex < ssf)
  {
    ntc = ntx;
    ssf = ntc.tabIndex
  }
  
  return ntc;
  
}

function createSearchIcon(parElem)
{
  var ic = document.createElement("IMG");
  ic.src = "../SiteImages/1/SCsearch.gif";
  ic.style.borderRight="0px";
  ic.style.borderLeft="0px";
  ic.style.borderTop="0px";
  ic.style.borderBottom="0px";
  setSearchIconPosition(parElem, ic);
  ic.style.visibility="visible";
  ic.style.position="absolute";
  ic.onmouseover=_searchMouseOver;
  ic.onmouseout=_searchMouseOut;
  ic.onclick=_searchClick;
  ic.title="Search";
  ic.id="_scSearchIcon";
  ic.parentSelect = parElem;
  return ic;
}

function setSearchIconPosition(parElem, ic)
{
  ic.style.left=calculateOffsetLeft(parElem)+ parElem.offsetWidth + 8 + "px";
  ic.style.top=calculateOffsetTop(parElem) + 4 + "px";
}

function calculateOffsetLeft(r){
    var kb = 0;
    while (r) {
        kb += r.offsetLeft;
        if (r.nodeName.toLowerCase() == "div") {
            kb -= r.scrollLeft;
        }
        r = r.offsetParent;
    }
    return kb;
}

function calculateOffsetTop(r){
  var kb = 0;
  var node = r;
  while (r) {
      if (r.offsetTop != undefined) {
          kb += r.offsetTop;
          if (r.nodeName.toLowerCase() == "div") {
              kb -= r.scrollTop;
          }
      }
      r = r.offsetParent;
  }
  
  // Adjust for firefox
  if (navigator && navigator.userAgent.toLowerCase().indexOf("msie") == -1) {
      while (node) {
          if (node.nodeName.toLowerCase() == "div") {
              kb -= node.scrollTop;
          }
          node = node.parentNode;
      }
  }

  return kb;
  
}

function showHideSuggest (ps, sf)
{
recomputePosition(ps);
  if (sf && ps)
  {
    _SCinp=ps.suggestDiv.inputControl;
    _SCsearch = null;
    _SCtimeout = 0;
    ps.suggestDiv.style.visibility="visible";
    ps.occludeFrame.style.width = ps.suggestDiv.offsetWidth;
    ps.occludeFrame.style.height = ps.suggestDiv.offsetHeight;
    ps.occludeFrame.style.top = ps.suggestDiv.style.top;
    ps.occludeFrame.style.left = ps.suggestDiv.style.left;
    ps.occludeFrame.style.zIndex = ps.suggestDiv.style.zIndex - 1;
    ps.occludeFrame.style.display = "block";
    ps.occludeFrame.style.visibility="visible";
    unhighlightAll (ps.suggestDiv.inputControl.suggestsDiv);
  }
  else if (!sf && ps)
  {
    if (_SCinp)
    {
      _SCinp=null;
      _SCsearch = null;
      _SCtimeout = 0;
      ps.style.visibility="visible";
      ps.occludeFrame.style.visibility="hidden";
      ps.suggestDiv.style.visibility="hidden";
    }
  }
}

function computeTopIndex (c,lh)
{
  var ti = (c.scrollTop/lh);
  return ti;
}

function handleSpecialKeys(key, inp)
{
  if (key != 38 && key != 40 && key != 13 && key != 27 && key != 9 && 
      key != 34 && key != 33)
  {
    return false;
  }

  var k = -1;
  var h = null;

  var stop = inp.suggestsDiv.scrollTop;
  var sbot = stop + _SChtDivLine * (inp.numVisible - 1);

  if (key == 40 || key == 34) // DOWN or PAGEDOWN
  {
    if (inp.suggestsDiv.highlightedSpanIndex < inp.suggestsDiv.childNodes.length - 1)
    {
      if (key == 40)
      {
        k = ++inp.suggestsDiv.highlightedSpanIndex;
      }
      else
      {
        k = inp.suggestsDiv.highlightedSpanIndex + inp.numVisible - 1;
        if (k >= inp.suggestsDiv.childNodes.length - 1)
        {
          k = inp.suggestsDiv.childNodes.length - 1;
        }
        inp.suggestsDiv.highlightedSpanIndex = k;
      }
      h = inp.suggestsDiv.childNodes[k];
      var kscroll = _SChtDivLine * k;
      if (kscroll < stop || kscroll > sbot)
      {
        var newTop = kscroll - (_SChtDivLine * (inp.numVisible - 1));
        if (newTop < 0) newTop = 0;
        inp.suggestsDiv.scrollTop = newTop;
      }
    }
  }
  else if (key == 38 || key == 33) // UP or PAGEUP
  {
    if (inp.suggestsDiv.highlightedSpanIndex > 0)
    {
      if (key == 38)
      {
        k = --inp.suggestsDiv.highlightedSpanIndex;
      }
      else
      {
        k = inp.suggestsDiv.highlightedSpanIndex - inp.numVisible + 1;
        if (k < 0)
        {
          k = 0;
        }
        inp.suggestsDiv.highlightedSpanIndex = k;
      }
      h = inp.suggestsDiv.childNodes[k];
      var kscroll = _SChtDivLine * k;
      if (kscroll < stop || kscroll > sbot)
      {
        var newTop = _SChtDivLine * k;
        inp.suggestsDiv.scrollTop = newTop;
      }
    }
  }
  else if (key == 13) // ENTER
  {
    makeSelection (inp.suggestsDiv.highlightedSpan, true);
    return true;
  }
  else if (key == 9) // TAB
  {
    if (inp.suggestsDiv.highlightedSpan)
    {
      makeSelection (inp.suggestsDiv.highlightedSpan, false);
      _SCnextcontrol = inp.nextInTabOrder;
      setTimeout("refocusNext()",0);
      return true;
    }
    else
    {
      showHideSuggest (inp.parentSelect, false);
      _SCrefocus = inp.parentSelect;
      setTimeout ("refocusSelect();", 0);
      return true;
    }
  }
  else if (key == 27 || key == 9) // ESCAPE
  {
    showHideSuggest (inp.parentSelect, false);
    _SCrefocus = inp.parentSelect;
    setTimeout ("refocusSelect();", 0);
    return true;
  }

  if (h)
  {
    setHighlighted(h, true);
    setHighlighted(inp.suggestsDiv.highlightedSpan, false);
    inp.suggestsDiv.highlightedSpan = h;
  }
  return true;
}

function showHideSuggestInputPrompt(inputctl, show) {
    if (show && !inputctl.p_fDisplayingPrompt && inputctl.value.length == 0) {
        inputctl.p_fDisplayingPrompt = true;
        inputctl.ps_fontFamily = inputctl.style.fontFamily;
        inputctl.ps_fontsize = inputctl.style.fontsize;
        inputctl.ps_fontWeight = inputctl.style.fontWeight;
        inputctl.ps_fontStyle = inputctl.style.fontStyle;
        inputctl.ps_color = inputctl.style.color;
        inputctl.style.fontFamily = "Tahoma";
        inputctl.style.fontsize = "small";
        inputctl.style.fontWeight = "bolder";
        inputctl.style.fontStyle = "normal";
        inputctl.style.color = "#808080";
        inputctl.style.backgroundImage = "url(../../acc/../acc/SiteImages/1/SCsearch.gif)";
        inputctl.style.backgroundRepeat = "no-repeat";
        inputctl.style.paddingLeft = "20px";
        inputctl.value = "Search: ";
        if (document.selection) {
            var oSel = document.selection.createRange();
            oSel.moveStart('character', 0);
            oSel.select();
        }
    } else if (!show && inputctl.p_fDisplayingPrompt) {
        inputctl.p_fDisplayingPrompt = false;
        inputctl.style.fontFamily = inputctl.ps_fontFamily;
        inputctl.style.fontsize = inputctl.ps_fontsize;
        inputctl.style.fontWeight = inputctl.ps_fontWeight;
        inputctl.style.fontStyle = inputctl.ps_fontStyle;
        inputctl.style.color = inputctl.ps_color;
        inputctl.style.backgroundImage = "url(../../acc/../acc/SiteImages/1/SCsearch.gif)";
        inputctl.style.paddingLeft = "20px";
        inputctl.value = "";
    }

}

var _scSuggestInputBlurHandler = function(event) {
    showHideSuggestInputPrompt(this, false);
}

var _scSuggestInputFocusHandler = function(event) {
    showHideSuggestInputPrompt(this, true);
}

var _scSuggestInputKeyHandler = function(event) {
    if (!event && window.event) {
        event = window.event;
    }
    var key = event.keyCode;
    if (key == 0) return true;
    if (handleSpecialKeys(key, this)) {
        event.cancelBubble = true;
        event.returnValue = false;
        return false;
    }
    if (_SCtimeout != 0) {
        clearTimeout(_SCtimeout);
    }
    if (_SCinp.parentSelect.p_isDynamic) {
        showHideSuggestInputPrompt(_SCinp, false);
    }
    _SCtimeout = setTimeout("checkSuggestInput(false);", 150);
    return true;
}

function determineKeyChar(kc, e)
{
  if (kc == 16 && e.shiftKey) return "";
  if (kc >= 65 && kc <= 90 && !e.shiftKey)
  {
    return String.fromCharCode(kc + 32);
  }
  else if (kc >= 65 && kc <= 90)
  {
    return String.fromCharCode(kc);
  }
  else if (kc >= 48 && kc <= 57 && !e.shiftKey)
  {
    return String.fromCharCode(kc);
  }
  else if (e.shiftKey)
  {
    switch (kc)
    {
      case  49 : return "!";
      case  50 : return "@";
      case  51 : return "#";
      case  52 : return "$";
      case  53 : return "%";
      case  54 : return "^";
      case  55 : return "&amp;";
      case  56 : return "*";
      case  57 : return "(";
      case  48 : return ")";
      case 189 : return "_";
      case 187 : return "+";
      case 219 : return "{";
      case 221 : return "}";
      case 186 : return ":";
      case 222 : return '"';
      case 188 : return "&lt;";
      case 190 : return "&gt;";
      case 191 : return "?";
      case 220 : return "|";
      case 192 : return "~";
    }
  }
  else if (!e.shiftKey)
  {
    switch (kc)
    {
      case  96 : return "0";
      case  97 : return "1";
      case  98 : return "2";
      case  99 : return "3";
      case 100 : return "4";
      case 101 : return "5";
      case 102 : return "6";
      case 103 : return "7";
      case 104 : return "8";
      case 105 : return "9";
      case 106 : return "*";
      case 107 : return "+";
      case 109 : return "-";
      case 110 : return ".";
      case 189 : return "-";
      case 187 : return "=";
      case 219 : return "[";
      case 221 : return "]";
      case 186 : return ";";
      case 222 : return "'";
      case 188 : return ",";
      case 190 : return ".";
      case 191 : return "/";
      case 220 : return "\\";
      case 192 : return "`";
    }
  }
  return "";
}

var _scSuggestSelectKeyHandler = function(event)
{
  if(!event&&window.event) {
    event=window.event;
  }
  if (event.ctrlKey || event.altKey || event.metaKey)
  {
    return true;
  }
  var kc = event.keyCode;
  var keyChar = determineKeyChar(kc, event);
  if (keyChar != "")
  {
    this.suggestDiv.inputControl.value = "";
    recreateSuggestionDiv (this.suggestDiv.inputControl);
    showHideSuggest (this, true);
    this.suggestDiv.inputControl.focus();
    this.suggestDiv.inputControl.value = keyChar;
    checkSuggestInput(false);
    event.cancelBubble=true;
    event.returnValue=false;
    return false;
  }
}

function recreateSuggestionDiv (c)
{
  c.parentDiv.removeChild(c.suggestsDiv);
  c.suggestsDiv = createSuggestionsDiv(c.numVisible, c.parentSelect);
  c.parentDiv.appendChild(c.suggestsDiv);
}

function scGetNewResults(ctl, sMatch) {
    // Don't fetch if we already have a full set of results
    // and the new search string is a superset of the last one.
    //
    if (ctl.rtSuggest.lastSrchFull && sMatch.indexOf(ctl.rtSuggest.lastSrchChars) >= 0) {
        ctl.rtSuggest.lastSrchChars = sMatch;
        return ctl.rtSuggest.lastSearchResults;
    }
    // Fetch new document
    //
    var parms;
    var fid = ctl.p_fid;;
    var iids = ctl.name;
    var fname = ctl.p_formName;
    var fnid = null;

    // Try various ways to get a reference to the form object
    //

    if (isNaN(fname)) {
        fnid = document.getElementById(fname);
    } else {
        try {
            var fno = parseInt(fname);
            fnid = document.forms[fno];
            if (fnid == null) {
                fnid = document.forms[0];
            }
        } catch (ex) {
    }
    }

    if (fnid == null) {
        fnid = document.forms[0];
    }

    // Build the parameters including all form data to be posted
    //
    parms = ajxGetFormData(fnid) + "&IIDS=" + iids + "&FIDAJAX=" + fid;
    parms += "&MatchAJAX=" + sMatch;
    parms += "&MaxElements=" + ctl.p_maxResults;

    // Adjust base URL if running from ASP.NET
    //
    var base;
    base = "ajax.asp";
    if (document.URL.search("aspx") > 0) {
        base = "../../acc/../acc/pages/ajax.asp";
    }

    doc = ajxGetSyncAjaxDoc(base, "UI", "Refresh", parms, "noxml=true");

    // Point into the XML node
    //
    var allCR, optsxml;
    allCR = ajxGetNode(doc, "ControlsRefresh");
    if (allCR == null || allCR.childNodes.length == 0) {
        return null;
    }

    makeElement = ajxGetNode(doc, "MakeArray");
    if (makeElement == null) {
        return null;
    }

    // Create the array of results by dynamically executing the
    // javascript created by the MIE. This will be an array of
    // "Pair" objects each having value and disp properties.
    //
    var results;
    var make;
    make = ajxGetTextFromNode(makeElement, "");
    results = eval(make);

    // Save search state information, such as if this search
    // has returned all matches, and save what we searched for
    // and the results.
    //
    var selNode;
    selNode = ajxGetNode(allCR, "SelectRefresh");
    if (selNode == null) return;
    ctl.rtSuggest.lastSrchFull = (ajxGetAttrText(selNode, "More", "N") == "N");
    ctl.rtSuggest.lastSrchChars = sMatch;
    ctl.rtSuggest.lastSearchResults = results;
    ctl.rtSuggest.noSelectValue = ajxGetAttrText(selNode, "NoSelectValue", "-none-");
    return results;

}

function scRefreshSelectMatches(ctl) {
    // Get search results. These either come from the
    // server, or from cache if the last search returned
    // all records and the new search string is a superset
    // of the previous one.
    //
    var results;
    var sMatch = _SCinp.value.toLowerCase();
    
    results = scGetNewResults(ctl, sMatch);
    if (results == null) {
        ctl.searchIcon.src = "../../acc/../acc/SiteImages/1/SCsearch.gif";
        if (_SCinp != null) {
            _SCinp.style.backgroundImage = "url(../../acc/../acc/SiteImages/1/SCsearchNoMatches.gif)";
            _SCinp.style.backgroundRepeat = "no-repeat";
        }
        return;
    }

    // Add the results into the div. Always add the "not selected" value.
    //
    if (_SCinp == null) return;

    var sgc = _SCinp.suggestsDiv;
    var fMatched = false;

    // Add "not selected" value
    //
    if (ctl.rtSuggest.noSelectValue != null) {
        sp = createMatchSpan(sgc, 0, ctl.rtSuggest.noSelectValue, -1, -1);
        sgc.appendChild(sp);
    }
    
    for (var i = 0; i < results.length; i++) {
        var cstr = results[i].disp;
        if (!(cstr.length >= 1 && cstr.slice(0, 1) == "-")) {
            var selStart = -1;
            if (sMatch != "") {
                selStart = cstr.toLowerCase().indexOf(sMatch.toLowerCase());
            }
            if (sMatch == "" || selStart >= 0) {
                var selEnd = selStart + sMatch.length;
                sp = createMatchSpan(sgc, i, cstr, selStart, selEnd);
                sgc.appendChild(sp);
                fMatched = true;
            }
        }
    }

    ctl.searchIcon.src = "../../acc/../acc/SiteImages/1/SCsearch.gif";

    if (!fMatched) {
        _SCinp.style.backgroundImage = "url(../../acc/../acc/SiteImages/1/SCsearchNoMatches.gif)";
        _SCinp.style.backgroundRepeat = "no-repeat";
    } else {
        if (ctl.rtSuggest.lastSrchFull) {
            _SCinp.style.backgroundImage = "url(../../acc/../acc/SiteImages/1/SCsearchComplete.gif)";
            _SCinp.style.backgroundRepeat = "no-repeat";
        } else {
            _SCinp.style.backgroundImage = "url(../../acc/../acc/SiteImages/1/SCsearch.gif)";
            _SCinp.style.backgroundRepeat = "no-repeat";
        }
    }

    _SCinp.showAll = false;
    
}

function scDoRefreshTimeout(ctlName) {
    var e, s = document.getElementsByName(ctlName);
    if (s == null || s.length == 0) return;
    e = s[0];
    scRefreshSelectMatches(e);
}

function scFetchDynamicSuggestions(ctl) {
    // Create the rtSuggest object to hold the
    // context of the search
    //
    if (ctl.rtSuggest == null) {
        ctl.rtSuggest = new Object();
        ctl.rtSuggest.lastSrchChars = "";
        ctl.rtSuggest.lastSrchFull = false;
    }
    // Clear previous timer, then set a new one
    //
    if (ctl.rtSuggest.timer != null) {
        ctl.searchIcon.src = "../../acc/../acc/SiteImages/1/SCsearch.gif";
        clearTimeout(ctl.rtSuggest.timer);
    }

    // We can call directly inline without using a timer
    // if we already have the results cached.
    //
    if (_SCinp != null) {
        var sMatch = _SCinp.value.toLowerCase();
        if (ctl.rtSuggest.lastSrchFull && sMatch.indexOf(ctl.rtSuggest.lastSrchChars) >= 0) {
            scRefreshSelectMatches(ctl);
            return;
        }
    }

    // Otherwise, call from a timer routine to allow user fast
    // typing response. Only fetch from server every 1/4 second.
    //
    var f = "scDoRefreshTimeout ('" + ctl.id + "');";
    ctl.rtSuggest.timer = setTimeout(f, 250);
    ctl.searchIcon.src = "../../acc/../acc/SiteImages/1/SCsearchAnimated.gif";
    _SCinp.style.backgroundImage = "url(../../acc/../acc/SiteImages/1/SCsearchWait.gif)";
    _SCinp.style.backgroundRepeat = "no-repeat";
    return true;
}

function checkSuggestInput(override)
{
  // Get the search string value
  //
  if (_SCinp == null) return;
  if (!override && _SCsearch == _SCinp.value) return;
  _SCsearch = _SCinp.value;

  // Remove and recreate the suggestion div
  //
  recreateSuggestionDiv(_SCinp);
  var sgc = _SCinp.suggestsDiv;

  // If the suggest control has dynamic behavior, delegate
  // to a different version of this routine.
  //
  if (_SCinp.parentSelect.p_isDynamic) {
      scFetchDynamicSuggestions(_SCinp.parentSelect);
      return;
  }

  // Add in the ones that match
  //
  var list = _SCinp.parentSelect.options;
  var total = 0;
  for (var i=0; i < list.length; i++)
  {
    var cstr = list[i].text;
    if (!(cstr.length >= 1 && cstr.slice(0,1) == "-"))
    {
      var selStart = -1;
      if (_SCsearch != "")
      {
         selStart = cstr.toLowerCase().indexOf(_SCsearch.toLowerCase());
      }
      if (_SCsearch == "" || selStart >= 0)
      {
         total++;
         if (!_SCinp.showAll && total > _SCinp.maxResults)
         {
           sp = createMatchSpan(sgc,-2,"-Show All-",0,0);
           sgc.appendChild(sp);
           break;
         }
         var selEnd = selStart + _SCsearch.length;
         sp = createMatchSpan(sgc,i,cstr,selStart,selEnd);
         sgc.appendChild(sp);
      }
    }
  }
  _SCinp.showAll = false;
}

function recomputePosition(p)
{
  if (p.occludeFrame) 
  {
     setOccludeFramePosition(p, p.occludeFrame);
  }
  if (p.suggestDiv)
  {
     setSuggestDivPosition(p, p.suggestDiv);
  }
}

function uninitSC (p)
{
  if (p == null) return;
  if (typeof p.p_hasKeyBehavior != 'undefined')
  {
    if (p.searchIcon != null)
    {
      p.searchIcon.style.visibility="hidden";
      p.searchIcon.onclick = null;
    }
    p.onkeydown = null;
  }
}

function reinitSC (parElem)
{
  p = document.getElementsByName(parElem)[0];
  if (!p) return;
  if (typeof p.p_numVisible == 'undefined') return;
  uninitSC (p);
  initSC(parElem, p.p_hasKeyBehavior, p.p_hasIcon, p.p_minSize, p.p_numVisible, p.p_maxResults, p.p_sfontClass)
}

function dynaTimeout(imgName) {
    var img = document.getElementsByName(imgName);
    if (img == null || img.length == 0) return;
    img[0].focus();
    img[0].onclick();
}

var _dynaClick = function() {
    this.blur();
    this.focus();
    window.setTimeout("dynaTimeout('" + this.searchIcon.name + "');",0);
}

function initSC2(parElem, hasKeyBehavior, hasIcon, minSize, 
                 numVisible, maxResults, sfontClass,
                 fid, fname) {

  var els;
  els = document.getElementsByName(parElem);
  
  if (!els || els.length == 0) return;
  p = els[0];
  if (!p) return;
  
  p.p_hasKeyBehavior = hasKeyBehavior;
  p.p_isDynamic = (minSize < 0);
  p.p_minSize = minSize;
  p.p_numVisible = numVisible;
  p.p_maxResults = maxResults;
  p.p_sfontClass = sfontClass;
  p.p_fid = fid;
  p.p_formName = fname;
  
  var ic = null;
  els = document.getElementsByName(parElem + "_IMG");
  if (els && els.length > 0) ic = els[0];
  
  p.searchIcon = ic;
  
  if (p.searchIcon)
  {
    p.searchIcon.style.visibility="hidden";
    p.searchIcon.onclick = null;
    p.searchIcon.parentSelect = p;
  }
  
  if (p.options==undefined) {return;}
  if (p.options.length < minSize) return;

  if (p.searchIcon)
  {
    p.searchIcon.style.visibility = "visible";
    p.searchIcon.onclick = _searchClick;
  }

  var sd = createSuggestDiv (p, numVisible, maxResults, sfontClass);
  p.suggestDiv = sd;

  if (hasKeyBehavior) p.onkeydown = _scSuggestSelectKeyHandler;

  if (p.p_isDynamic) {
      p.onmousedown = _dynaClick;
  }
  
}

function initSC(parElem, hasKeyBehavior, hasIcon, minSize, numVisible, maxResults, sfontClass) {
    // Legacy version, pre-dynamic behavior
    return initSC2(parElem, hasKeyBehavior, hasIcon, minSize, numVisible, maxResults, sfontClass,0,"");
}



