﻿var _ActiveRow = null;
var _CallBack = null;

var _LastKey = -1;
var _DropWidth = 400;
var _TypeAheadIsRendered = false
var KEY_CODE_ENTER = 13;
var KEY_CODE_TAB = 9;
var KEY_CODE_DOWN_ARROW = 40;
var KEY_CODE_UP_ARROW = 38;

function fnOnKeyPress(evt, fnCallBack)
{
    _LastKey = evt.keyCode;
    _CallBack = fnCallBack;

    if (_LastKey == KEY_CODE_TAB || _LastKey == KEY_CODE_ENTER) {
        var text = evt.target || evt.srcElement;
        if ($(text).attr("hidName")) {
            fnSetSelected(text.id, $(text).attr("hidName"));
        } 
    }  
}

function fnCatchKey(evt, lookUp, dataType, dropWidth)
{
  _DropWidth = (_DropWidth)? dropWidth : _DropWidth;

  var iKeyCode = evt.keyCode;
  var text = evt.target || evt.srcElement;
  
  if (iKeyCode == KEY_CODE_DOWN_ARROW || iKeyCode == KEY_CODE_UP_ARROW) 
  {
    fnScrollResults(text, iKeyCode);
  }
  else if (iKeyCode == KEY_CODE_ENTER)
  {
    fnSetSelected(text.id, $(text).attr("hidName"));
    fnRemoveSuggest(text.id);
  }
  else
  {
    fnGetSuggestResults(evt, lookUp, dataType)
  } 
}

function fnGetSuggestResults(evt, lookUp, dataType)
{
    var text = evt.target || evt.srcElement;
    text = $(text);

    var sTargetID = text.attr("id");
    if(lookUp != text.attr("OrgTextValue"))
    {
        eval("var cache = window._resultCache_"+sTargetID);
        cache = (cache)? cache[lookUp] : null;
        
        if(!cache)
        {        
            if(lookUp)
            {
                var txtTarget = $(document.getElementById(sTargetID));
                var sParams = (txtTarget.attr("Params"))? "&p=" + txtTarget.attr("Params") : "";
                var sUrl = "/TypeAhead.aspx?id="+sTargetID+"&lu="+lookUp+"&dt="+dataType+sParams;

                $.ajax({
                    type: "GET",
                    url: sUrl,
                    dataType: 'text',
                    success: function(msg) {
                        eval(msg);
                    },
                    error: function(XmlHttpRequest, textStatus, errorThrown) {
                        
                    }
                });
            }
            else
            {
                // clear the value.
                var txtTarget = document.getElementById(sTargetID);
                var txtValue = document.getElementById($(txtTarget).attr("hidName"));
                txtValue.value = "";
                
                // remove the div tag.
                fnRemoveSuggest(sTargetID);
            }   
         }
         else
         {
             fnDisplaySuggestedList(sTargetID, cache[0], cache[1], cache[2])
         } 
   }                
}

// this function gets sent back from the server and then eval'd in fnGetSuggestResults()
function fnRenderSuggest(sTargetID, sSearchText, arrValue, arrText, arrOptionalText)
{
    // cache new results
    fnCacheResults(sTargetID, sSearchText, arrValue, arrText, arrOptionalText);
    
    // display the list
    fnDisplaySuggestedList(sTargetID, arrValue, arrText, arrOptionalText);
}

function fnDisplaySuggestedList(sTargetID, arrValue, arrText, arrOptionalText)
{
    var divSuggest = fnCreateDropDiv(sTargetID);
    var divOuter = document.createElement("SPAN");
    var divContainer = document.createElement("DIV");
    var txtTarget = $(document.getElementById(sTargetID));
    var blnCanShowSearch = (txtTarget.get(0) && txtTarget.attr("CanSearch") == "true")

    if(blnCanShowSearch)
    {
        fnCreateRow(divContainer, sTargetID, "-1", "< Search... >", "")
    }
    
    for(var i = 0; i < arrValue.length; i++)
     { 
        if(arrValue[i] != "")
        {
            fnCreateRow(divContainer, sTargetID, arrValue[i], arrText[i], arrOptionalText[i]);
        }
     }

    if(blnCanShowSearch || arrValue.length > 0)
    {
        divContainer.setAttribute("onmouseout", "window.fnOnMouseOut()");
        divOuter.appendChild(divContainer);
        divSuggest.innerHTML = divOuter.innerHTML;
        _TypeAheadIsRendered = true;
     // fnCreatePopup(txtTarget, _DropWidth, divOuter.innerHTML)
        fnSetFirstActive(sTargetID);
        txtTarget.focus();
    }
    else
    {
        fnRemoveSuggest(sTargetID);
    }
}

function fnCreateRow(container, targetID, value, text, optionalText) {
    var spanRow = document.createElement("SPAN");
    spanRow.setAttribute("onmouseover", "window.fnOnMouseOver(event)");
    //spanRow.onclick = fnOnSuggestClick;
    //spanRow.setAttribute("onclick", "window.top.ActiveWin.fnOnSuggestClick(event)");
    spanRow.setAttribute("TargetID", targetID);
    spanRow.style.float = "left";
    spanRow.style.width = (_DropWidth+10)+"px";   
    spanRow.style.fontFamily = "verdana";
    spanRow.style.fontSize = "11px";
    spanRow.style.cursor = "default";

    var spanText = document.createElement("DIV");
    spanText.style.float = "left";
    spanText.style.width = (optionalText)? (_DropWidth * .7)+"px" : _DropWidth+"px";
    spanText.innerHTML = text; // the text for the suggested result...
    
    if(optionalText)
    {
        var spanOptionalText = document.createElement("DIV");
        spanOptionalText.align = "right";
        spanOptionalText.style.width = (_DropWidth * .3)+"px";
        spanOptionalText.innerHTML = (optionalText)? optionalText : "<br/>"; // optional text
    }
    
    var hidValue = document.createElement("INPUT");
    hidValue.id = "hid_" +targetID+"_"+value;
    hidValue.value = value
    hidValue.type = "hidden";

    spanRow.appendChild(spanText);
    if(optionalText)spanRow.appendChild(spanOptionalText);
    spanRow.appendChild(hidValue);
    
    container.appendChild(spanRow);
}

function fnCreateDropDiv(sTargetID)
{
    var divSuggest = document.getElementById(sTargetID+"_Suggest");
    if(!divSuggest)
    {
        var target = document.getElementById(sTargetID);
        
        divSuggest = document.createElement("DIV");
        divSuggest.id = sTargetID+"_Suggest";
        divSuggest.style.border = "black 1px solid";
        divSuggest.style.zIndex = "1";
        divSuggest.style.width = _DropWidth+"px";
        divSuggest.style.fontFamily = "verdana";
        divSuggest.style.fontSize = "11";
        divSuggest.style.cursor = "default";
        
        divSuggest.style.left = calculateOffsetLeft(target)+"px";
        divSuggest.style.top = calculateOffsetTop(target)+target.offsetHeight-1+"px";
        divSuggest.style.position = "absolute";
        divSuggest.style.backgroundColor = "white";
        
        document.forms[0].appendChild(divSuggest);              
    }
    return divSuggest
}

// this function will make an global array for each suggest style control to hold its
// search results.
function fnCacheResults(sTargetID, sSearchText, arrValue, arrText, arrOptionalText)
{
   try
   {
      // try to get a reference to the global array that is named with the target id of the calling control
      eval("var cache = window._resultCache_"+sTargetID);
      
      // if its there create the array of search results
      cache[sSearchText] = new Array(arrValue, arrText, arrOptionalText)
   }catch(e){
        // if it wasn't found, create the global variable for the array - then call fnCachResults again to populate it.
        eval("window._resultCache_"+sTargetID+" = new Object()");
        fnCacheResults(sTargetID, sSearchText, arrValue, arrText, arrOptionalText);
   }
}

function calculateOffsetLeft(r){
  return Ya(r,"offsetLeft")
}

function calculateOffsetTop(r){
  return Ya(r,"offsetTop")
}

function Ya(r,attr){
  var kb=0;
  while(r){
    kb+=r[attr]; 
    r=r.offsetParent
  }
  return kb
}

function fnScrollResults(txt, iKey)
{
    var divSuggest = document.getElementById(txt.id+"_Suggest");
    if(divSuggest)
    {
        var aDivs = divSuggest.getElementsByTagName("SPAN");
        if(aDivs.length > 0)
        {
            // if there is no currently selected row and the down arrow is being pressed, select the first row.
            if (_ActiveRow == null && iKey == KEY_CODE_DOWN_ARROW)
            {
                fnSetRowActive(aDivs[0]);
            }
            else
            {
                // stop scrolling if we are on the last row in the list
                if (_ActiveRow == aDivs[aDivs.length - 1] && iKey == KEY_CODE_DOWN_ARROW)
                {
                    return;
                }
                else if (_ActiveRow == aDivs[0] && iKey == KEY_CODE_UP_ARROW)
                {
                    fnRemoveSuggest(txt.id); // hide the list if the top is hit.
                }
                else
                {
                    // ...otherwise, select the previous or next row, depending on which arrow was selected.
                    var nextRow = (iKey == KEY_CODE_DOWN_ARROW) ? _ActiveRow.nextSibling : (_ActiveRow == aDivs[0]) ? aDivs[0] : _ActiveRow.previousSibling;
                    fnSetRowActive(nextRow);
                }
            }
        }
    }
    else
    {
        fnSuggest_ShowSearchOption(txt.id, "", txt.DataType, _DropWidth)
    }
}

function fnSetFirstActive(sTargetID)
{
    var divSuggest = document.getElementById(sTargetID + "_Suggest");
    if(divSuggest)
    {
        var aDivs = divSuggest.getElementsByTagName("SPAN");
        if (aDivs.length)
        {
            if (aDivs.length == 1) {
                var target = $(document.getElementById(sTargetID))
                var iRow = (aDivs.length > 1 && target.attr("CanSearch") == "true") ? 1 : 0;
                if (target.attr("CanSearch") == "true" && iRow == 0) return false;

                fnSetRowActive(aDivs[iRow]);
            } else {
                // select the first row
                var spnRow = aDivs[0];
                var aHids = spnRow.getElementsByTagName("INPUT");
                if (aHids.length > 0) {
                    var sValue = aHids[0].value;
                    var iRowToSelect = 0;
                    
                    // check to see if the first row is the <search> option
                    if (sValue == "-1") {
                        // if so, see if there is a second row and select it
                        if (aDivs.length > 1) {
                            iRowToSelect = 1;
                        }
                    }

                    fnSetRowActive(aDivs[iRowToSelect]);
                }               
            }
        }
    }
}

/***************************
  ****  EVENTS  *****
***************************/
function fnOnSuggestBlur(sTargetID, sValueID, fnCallBack)
{
    if(sTargetID && sValueID)
    {
        _CallBack = fnCallBack;
        
        fnSetSelected(sTargetID, sValueID, fnCallBack);
        fnRemoveSuggest(sTargetID);
    }
    return;
    var txtTarget = document.getElementById(sTargetID);
    if(txtTarget.value != "" && txtTarget.value != txtTarget.OrgTextValue)
    {
        txtTarget.value = txtTarget.OrgTextValue
    }
}

function fnRemoveSuggest(sTargetID)
{
    var divSuggest = $("#" + sTargetID + "_Suggest");
    if(divSuggest.get(0) && divSuggest.parent().get(0))divSuggest.parent().get(0).removeChild(divSuggest.get(0));

    _ActiveRow = null;
    _CallBack = null;
    _SelectedRow = null;
    _TypeAheadIsRendered = false;
    _LastKey = -1;
}

function fnSetSelected(sTargetID, sValueID, fnCallBack)
{
    var txtTarget = document.getElementById(sTargetID);
    var txtValue = document.getElementById(sValueID);

    var sTargetVal = ""; //(txtTarget.value == "")? "" : (txtTarget.OrgTextValue)? txtTarget.OrgTextValue : "";
    var sValueVal = ""; //(sTargetVal == "")? "" : (txtTarget.OrgValue)? txtTarget.OrgValue : ""; // this blanks out the hidden field value, if the target was blanked out.

    if (_ActiveRow)
    {
        var spnRow = _ActiveRow;
        var aHids = spnRow.getElementsByTagName("INPUT");
        var aDivs = spnRow.getElementsByTagName("DIV");
        if(aHids.length > 0)
        {
            sTargetVal = aDivs[0].innerHTML;
            sValueVal = aHids[0].value;
            _ActiveRow = null;
            if(sValueVal == "-1")
            {
                try
                {
                    var oHtc = document.getElementById(txtTarget.HtcID);
                    oHtc.OpenDialog(sTargetID, txtTarget.DataType);
                }catch(e){alert("Your htc needs to support the OpenDialog method.")}
                return;
            }
        }
    } else {
        sValueVal = "";
    }

    

    if(sValueVal){
      txtTarget.value = sTargetVal;
      txtValue.value = sValueVal;

        $(txtTarget).attr("OrgValue", sValueVal);
        $(txtTarget).attr("OrgTextValue", sTargetVal);  
    }

    if(_CallBack) _CallBack(sValueVal, sTargetID);
}

function fnOnMouseOver(evt)
{
    evt = (evt)? evt : event;
    var srcElement = evt.target || evt.srcElement;

    var spnDiv = (srcElement.tagName == "DIV")? $(srcElement).parent().get(0) : srcElement;

    fnSetRowActive(spnDiv);
}
    
function fnOnMouseOut()
{
    if(_ActiveRow)
    {
        fnSetRowInActive(_ActiveRow);
        _ActiveRow = null;
    }
}
                
function fnSetRowActive(objDiv)
{
    if(_ActiveRow)fnSetRowInActive(_ActiveRow);

    _ActiveRow = objDiv;
     if(_ActiveRow)
    {
        $(_ActiveRow).children().eq(0).css('background-color', '#333366');
        $(_ActiveRow).children().eq(0).css('color', '#FFFFFF');
    }
}

function fnSetRowInActive(objDiv)
{
    if(objDiv)
    {
        $(objDiv).children().eq(0).css('background-color', '#FFFFFF');
        $(objDiv).children().eq(0).css('color', '#000000');
    }
}

function fnSuggest_ShowSearchOption(targetID, lookUp, dataType, dropWidth)
{
    var txtTarget = $(document.getElementById(targetID));
    if(txtTarget.get(0) && txtTarget.attr("CanSearch") == "true")
    {
        _DropWidth = (_DropWidth)? dropWidth : _DropWidth;
        fnDisplaySuggestedList(targetID, new Array(""), new Array(""), new Array(""))
    }
}

