//Dropdown list related variables
var rwSug = null; //Current highlighted row
var curRwNo = -1; //Current highlighted Row index
var showLoader = true;
var curKyCd = null;
var blockSrch =false; //to prevent submit on enter key
var showAutoSugst=false; //to store search process
addEvent(document,"click",HidSugBx);

var txtDestCltID = null;
var hdLocID = null;
var trHide = null;
var fType = null;
var ddState = new Array();
function AutoSuggest(evnt, txtBxId, hdnLocId, trToHd, fTyp)
{ 
    if(blockSrch==false)
    {
        txtBxToFillDesc=txtBxId.split(',');   
        txtDestCltID = $('#'+txtBxToFillDesc[0]);     
          
        hdnCtrlIdsToFillCd=hdnLocId.split(',');
        hdLocID=$('#'+hdnCtrlIdsToFillCd[0]);   
        trHide = $('#'+trToHd);
        fType = fTyp;

        curKyCd = CurrKyCde(evnt);
        if ($(txtDestCltID).val().length < 3) 
        {
            if ($(actBox) != null)
                $(actBox).css('display','none'); 
            return;
        }
        
        if (curKyCd != 38 && curKyCd != 40 && curKyCd != 13 && curKyCd != 9)
        {
            GtSgsts();
            $(hdLocID).val('');
        }
        else if (curKyCd == 38 || curKyCd == 40 || curKyCd == 13)
        {
            var ulSgst = $("#ulSuggest").get(0);                       
            if (ulSgst == null || ulSgst.childNodes.length == 0 || $(actBox).css('display') == 'none') 
            {
                return;
            }
            evnt.preventDefault();
            SgstChkKy();
        }
    }
    else    
        if(curKyCd == 38 || curKyCd == 40 ) blockSrch = false; else return;    
}


function GtSgsts()
{   
    showAutoSugst=true;//setting flag value
    if (showLoader)
        DispSgst("<span class='pleasewait'><img src='../widget/images/loader.gif' alt='Please Wait...' />Please wait...</span>", true);
    MakeRequest(urlLS + "?prefix=" +  $(txtDestCltID).val() + "&type=" + fType + "&ver=" + (window.version != undefined && version != null ? version : ''), "DispSgstLst");
}

function DispSgstLst(sugLstRes)
{
    if(showAutoSugst==false)
        return;
    DispSgst(unescape(sugLstRes),false);
    showLoader = false;   //Diplay Please wait only the first time user types in
    //Show Recent Search only when user comes from Widget    
    if(window.curTab != undefined && curTab != null && curTab.length > 0 && unescape(sugLstRes).length != 0 && $("#ulSuggest")!=null && $("#ulSuggest").html() && $("#ulSuggest").html().length > 0)
    {
        hideSelForIE6($(actBox), $(trHide).attr('id'), "visible"); 
      
        hideSelForIE6($(actBox), $(trHide).attr('id'), "hidden");
        
        rwSug = $("#ulSuggest").get(0).childNodes[0].childNodes[0];
        $(rwSug).css('backgroundColor','#E1F1FF');
        curRwNo=0;
    }
    else
    {
        HidSugBx();
        rwSug=null;
        curRwNo=-1;
    }
}

function CurrKyCde(evnt)
{
    if (!evnt) var evnt = window.event
    if (evnt.keyCode) var keyCode = evnt.keyCode;
    else if (evnt.which) var keyCode = evnt.which;
    return keyCode;
}

function DispSgst(msge,isLoader)
{
    if (msge == null || msge.length == 0)
        return;
    
    if(!isLoader)
    {
        msge+="<div class='closeautosuggest'><span>...and more, keep typing to refine search</span><a href='#'>close</a></div>"
        msge="<div class='autosuggestboxlt'>"+msge+"</div>";
    }
    else
    {
        $('#divMain').removeAttr('class');      
        $('#divMainout').removeAttr('class'); 
    }
    msg.innerHTML = msge;

    $(actBox).css('position','absolute');
    $(actBox).css('left',absXFrmLft($(txtDestCltID)) + "px");
    var ulSgst = $("#ulSuggest").get(0);
        
    $(actBox).css('top',absYFrmTp($(txtDestCltID))+ $(txtDestCltID).attr('clientHeight') + "px");

    $(actBox).css('display','');
          
    hideSelForIE6($(actBox), $(trHide).attr('id'), "visible");    

    if(ulSgst != null)
        hideSelForIE6($(actBox), $(trHide).attr('id'), "hidden");
    

}

function HidSugBx()
{  
    showLoader=true;
    if(typeof hideHoverInfo == 'function')
        hideHoverInfo();

    if ($(actBox) != null)
        $(actBox).css('display','none');    
    
    if(typeof hideSelForIE6 == 'function')
        hideSelForIE6($(actBox), $(trHide).attr('id'), "visible");
          
    blockSrch = curKyCd==13 ? true : false;    
    showAutoSugst=false;  
}

function SetLocationStrings(str)
{
    $(hdLocID).val(str.replace(/<\/?[^>]+(>|$)/g, ""));
    $(txtDestCltID).val(str.split("***")[1].replace(/<\/?[^>]+(>|$)/g, ""));

    for(i=1;i<txtBxToFillDesc.length;i++)
    {
        if($('#'+txtBxToFillDesc[i])!=null)      
            $('#'+txtBxToFillDesc[i]).val($(txtDestCltID).val());           
        
       
        if($('#'+hdnCtrlIdsToFillCd[i]) !=null)
             $('#'+hdnCtrlIdsToFillCd[i]).val($(hdLocID).val());
    }   
     
}

function SgstChkKy() 
{  
    switch (curKyCd)
    {
        case 38:
            SgstGoUp();
            break;
        case 40:
            SgstGoDwn();
            break;
        case 13:
            if (rwSug != null)
                SetLocationStrings($(rwSug).attr('id'));
            HidSugBx();
            break;
        default:
            break;
    }
}

function SgstGoDwn()
{
    var ulSgst = $("#ulSuggest").get(0);
    
    if (rwSug == null)
    {
        rwSug = ulSgst.childNodes[0].childNodes[0];
        $(rwSug).css('backgroundColor','#E1F1FF');
        curRwNo=0;
    }
    else if (ulSgst.childNodes[curRwNo+1] != null)
    {       
        $(ulSgst.childNodes[curRwNo].childNodes[0]).css('backgroundColor','white');
        rwSug = ulSgst.childNodes[curRwNo+1].childNodes[0];
        $(rwSug).css('backgroundColor','#E1F1FF');      
        
        curRwNo++;
    }
}

function SgstGoUp()
{
    var ulSgst = $("#ulSuggest").get(0);
    
    if (rwSug == null)
    {
        rwSug = ulSgst.childNodes[0].childNodes[0];
        $(rwSug).css('backgroundColor','white');
        curRwNo=0;
    }
    else if (curRwNo>0 && ulSgst.childNodes[curRwNo-1] != null)
    {
        $(ulSgst.childNodes[curRwNo].childNodes[0]).css('backgroundColor','white');
        rwSug = ulSgst.childNodes[curRwNo-1].childNodes[0];
        $(rwSug).css('backgroundColor','#E1F1FF');
        
        curRwNo--;
    }
}

function SuggestMouseOver(liElm)
{
    if (rwSug != null)
        rwSug.style.backgroundColor = "";
    rwSug = liElm;
    curRwNo = GtRwIdx(rwSug.id);
    $(rwSug).css('backgroundColor','#E1F1FF');
}

function GtRwIdx(val)
{
    var ulSgstDdl = $("#ulSuggest").get(0);
    var rowNo = 0;
    for (var i=0; i<ulSgstDdl.childNodes.length; i++)
        if (ulSgstDdl.childNodes[i].childNodes[0] != null && ulSgstDdl.childNodes[i].childNodes[0].id == val)
            return rowNo;
        else
            rowNo++;    
}

function addEvent(obj,event_name,func_name)
{
    if (obj.attachEvent)
        obj.attachEvent("on"+event_name, func_name);
    else if(obj.addEventListener)
        obj.addEventListener(event_name,func_name,true);
    else
        obj["on"+event_name] = func_name;    
}

function absYFrmTp(el)
{
    var absY = 0;
    var actElm = el;

    while(actElm)
    {
        absY += $(actElm).attr('offsetTop');
        actElm = $(actElm).attr('offsetParent');
    }
    return absY;
}

function absXFrmLft(el)
{
    var absX = 0;
    var actElm = el;
    while(actElm)
    {
        absX += $(actElm).attr('offsetLeft');
        actElm = $(actElm).attr('offsetParent');
    }
    return absX;
}

function hideSelForIE6(actDiv, objHaveSel, status)
{
    var ieVer= -1
    if (/MSIE (\d+\.\d+);/.test(navigator.userAgent))
        ieVer=new Number(RegExp.$1); // capture x.x portion and store as a number

    if (!(navigator.appName == 'Microsoft Internet Explorer' &&  ieVer < 7))
        return;
    if(objHaveSel == null || actDiv == null) return;    
 
    if(status == "hidden")
    {
        var actTop = absYFrmTp($(actDiv));
        var actBxHt = actTop + $(actDiv).attr('offsetHeight');
        var actLft = absXFrmLft($(actDiv));
        var actBxWd = actLft + $(actDiv).attr('offsetWidth');
        ddState = new Array();       
        var selHt = 0;                
            
        $("#"+objHaveSel+" select").each(function() {            
            selTp = absYFrmTp($(this));
            selHt = selTp + $(this).attr('offsetHeight');
            selLft = absXFrmLft($(this));
            selWd = selLft + $(this).attr('offsetWidth');
            if(((selLft > actLft && selLft < actBxWd) || (selWd > actLft && selWd < actBxWd)) && ((selTp > actTop && selTp < actBxHt) || (selHt > actTop && selHt < actBxHt)))
            { 
                if($(this).is(':visible'))
                {                   
                    ddState[ddState.length] = this;       
                    $(this).hide();
                }
            }
        });
    }
    else
    {
        if(ddState==null) return;
        for(i=0;i<ddState.length;i++)    
            $(ddState[i]).show();
    }
}

var txtBox, hdnBox, tab, type, timeout, lastkeyPressed,evnt;
function onDefault()
{
    if(lastkeyPressed == 46)//Delete
        HidSugBx();
    AutoSuggest(evnt,txtBox,hdnBox,tab,type);
}
function CallAutoSuggest(event, txtBox_, hdnBox_, tab_, type_)
{
    blockSrch = false;
    evnt = event;
    txtBox = txtBox_;
    hdnBox = hdnBox_;
    tab = tab_;
    type = type_;
    
    lastkeyPressed = event.keyCode;
    
    switch(event.keyCode) {
        
            case 9:
                HidSugBx();
                break;
            case 38:case 40:case 13:
                AutoSuggest(event,txtBox_,hdnBox_,tab_,type_);
                break;
            default:
                 //$(".tabs-left-check input:radio").each(function() {$(this).attr('checked',false);});
                clearTimeout(timeout);
                timeout = setTimeout(onDefault, 300);
                break;
    }
}

//Unselect element if mouse is over recent searches section
function SuggestUnselect()
{  
    $("#ulSuggest li:eq(" + curRwNo + ")").children(0).css('backgroundColor','transparent');
}

