//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();
var autoSgstVer="";
if (!window.portalId)
    var portalId = "92";
// checking variable exists and set to true to use web service for autosuggest
if (!window.useWebServiceAutoSuggest)
    useWebServiceAutoSuggest = false;
    
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);
        var isActionkey = curKyCd != 38 && curKyCd != 40 && curKyCd != 13 && curKyCd != 9

        if (isActionkey) 
        {
            for (i = 0; i < hdnCtrlIdsToFillCd.length; i++)
                $('#' + hdnCtrlIdsToFillCd[i]).val('');            
        }

        if ($(txtDestCltID).val().length < 3) 
        {
            HidSugBx(); 
            return;
        }

        if (isActionkey)
        {
            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("<div class='pleasewait'><span></span> Please wait...</div>", true);
    if (useWebServiceAutoSuggest)//calling autosuggest web service
        GetAutosuggestWS($(txtDestCltID).val(), fType, autoSgstVer);
    else
        MakeRequest(urlLS + "?prefix=" + $(txtDestCltID).val() + "&type=" + fType + "&ver=" + autoSgstVer, "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"); 
        GetRecentSrch();
        hideSelForIE6($(actBox), $(trHide).attr('id'), "hidden");
        
        rwSug = $("#ulSuggest").get(0).childNodes[0].childNodes[0];
        $(rwSug).addClass('divHover');
        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><div class='closeautosuggest'><a href='javascript:void(0);'>Close</a></div></div>"
        msge = "<div class='autosuggestboxlt'>" + msge + "</div>";
    }
    else
    {
        $('#divMain').removeAttr('class');      
        $('#divMainout').removeAttr('class'); 
    }
    msg.innerHTML = msge;
    var pos = jQuery(txtDestCltID).offset();
    var hight = jQuery(txtDestCltID).outerHeight();
    $(actBox).css('position','absolute');
    $(actBox).css('left', pos.left);
    var ulSgst = $("#ulSuggest").get(0);
    $(actBox).css('top', pos.top + hight);

    $(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, ""));
    if(fType.toUpperCase() == "C")
    {
        var zipCode = str.split("|")[0];
        if(isValidZipCode(zipCode))
            $(hdLocID).val(zipCode);
    }

    var displaystr=  str.split("***");   
    if(displaystr.length >1)
        $(txtDestCltID).val(displaystr[1].replace(/<\/?[^>]+(>|$)/g, ""));
    else
        $(txtDestCltID).val(displaystr[0].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).addClass('divHover');
        curRwNo=0;
    }
    else if (ulSgst.childNodes[curRwNo+1] != null)
    {
        $(ulSgst.childNodes[curRwNo].childNodes[0]).removeClass('divHover');
        rwSug = ulSgst.childNodes[curRwNo+1].childNodes[0];
        $(rwSug).addClass('divHover');
        
        curRwNo++;
    }
}

function SgstGoUp()
{
    var ulSgst = $("#ulSuggest").get(0);
    
    if (rwSug == null)
    {
        rwSug = ulSgst.childNodes[0].childNodes[0];
        $(rwSug).removeClass('divHover');
        curRwNo=0;
    }
    else if (curRwNo>0 && ulSgst.childNodes[curRwNo-1] != null)
    {
        $(ulSgst.childNodes[curRwNo].childNodes[0]).removeClass('divHover');
        rwSug = ulSgst.childNodes[curRwNo-1].childNodes[0];
        $(rwSug).addClass('divHover');
        
        curRwNo--;
    }
}

function SuggestMouseOver(liElm)
{
    if (rwSug != null)
    $(rwSug).removeClass('divHover');
    rwSug = liElm;
    curRwNo = GtRwIdx(rwSug.id);
    $(rwSug).addClass('divHover');
}

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) {
       try {  
       	var pos=parseInt($(actElm).attr('offsetTop'));
        	absY +=pos;
	 } catch (ex) { }
        actElm = $(actElm).attr('offsetParent');
    }
    return absY;
}

function absXFrmLft(el)
{
    var absX = 0;
    var actElm = el;
    while(actElm) {
        try {          
            absX += $(actElm).attr('offsetLeft');

        } catch (ex) { }
        actElm = $(actElm).attr('offsetParent');
    }
    return absX;
}

function hideSelForIE6(actDiv, objHaveSel, status)
{
    var ieVer= -1;
    
    if(!$.browser.msie || $.browser.version!="6.0")
        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;
    //Flight version setting
    if(type =="F" ) 
    {
        if( window.fltVer == undefined || window.fltVer == null) 
        {
            if(window.fpVersion != undefined && window.fpVersion != null) 
                autoSgstVer = fpVersion;
            else if( window.version != undefined && window.version != null) 
                autoSgstVer = version;
        }
        else
            autoSgstVer = fltVer;
    }

    //Hotel version setting
    if(type =="H" ) 
    {
        if ( window.htlVer == undefined || window.htlVer == null) 
        {
            if(window.fpVersion != undefined && window.fpVersion != null) 
                autoSgstVer = fpVersion;
            else if( window.version != undefined && window.version != null) 
                autoSgstVer = version;
        }
        else
            autoSgstVer = htlVer;
    }

    //Car version setting
    if(type =="C" )
    {
        if( window.carVer == undefined || window.carVer == null)
        {
            if(window.fpVersion != undefined && window.fpVersion != null) 
                autoSgstVer = fpVersion;
            else if( window.version != undefined && window.version != null) 
                autoSgstVer = version;     
        }
        else
            autoSgstVer = carVer;
    }

    //Package version setting
    if(type =="P")
    {
        if ( window.pkcVer == undefined || window.pkgVer == null)
        {
            if(window.fpVersion != undefined && window.fpVersion != null) 
                autoSgstVer = fpVersion;
            else if( window.version != undefined && window.version != null) 
                autoSgstVer = version;   
        }
        else
         autoSgstVer = pkgVer;
    }


    switch(event.keyCode) {
        
            case 9:
                HidSugBx();
                break;
            case 38:case 40:case 13:
                AutoSuggest(event,txtBox_,hdnBox_,tab_,type_);
                break;
            default:
                $(".pplrdest input:radio").each(function() {$(this).attr('checked',false);});
                clearTimeout(timeout);
                timeout = setTimeout(onDefault, 100);
                break;
    }
}

//Function gets last searches based on the category
function GetRecentSrch() 
{
    if (window.blockRcntSrch != 'undefined' && window.blockRcntSrch != null && window.blockRcntSrch == true)
    {
        AplyRcntSrchCss(false); //remove recent search css
        return;
    }

    var lstRcntSrch;

    switch (window.curTab != undefined && window.curTab != null && window.curTab.length > 0 ? window.curTab : fType)
    {
        case "F":
            if(window.GetRecentSrchAir)
                lstRcntSrch = GetRecentSrchAir();
             break;
         case "H":
             if (window.GetRecentSrchHotel)
                lstRcntSrch = GetRecentSrchHotel();
             break;
         case "C":
             if (window.GetRecentSrchCar)
                lstRcntSrch = GetRecentSrchCar();
             break;
         case "P":
             if (window.GetRecentSrchPkg)
                lstRcntSrch = GetRecentSrchPkg();
             break;
         case "HC":
             if (window.GetRecentSrchPkgHC)
                 lstRcntSrch = GetRecentSrchPkgHC();
             break;
    }
    
    if(lstRcntSrch != null && lstRcntSrch != '' && lstRcntSrch.length > 0)
    {
        $(msg).append(lstRcntSrch);
        AplyRcntSrchCss(true); // apply recent search css      
    }
    else
        AplyRcntSrchCss(false); //remove recent search css
        
}

function AplyRcntSrchCss(isRcntSrchExists)
{
    if(isRcntSrchExists)
    {
        $('#divMain').removeClass('autosuggestbox1');      
        $('#divMain').addClass('autosuggestbox');
        $('#divMainout').removeClass('autosuggestboxout1');      
        $('#divMainout').addClass('autosuggestboxout');
    }
    else
    {
        $('#divMain').addClass('autosuggestbox1');
        $('#divMain').removeClass('autosuggestbox');      
        $('#divMainout').addClass('autosuggestboxout1');
        $('#divMainout').removeClass('autosuggestboxout'); 
    }
}


//Unselect element if mouse is over recent searches section
function SuggestUnselect()
{  
    $("#ulSuggest li:eq(" + curRwNo + ")").children(0).css('backgroundColor','transparent');
}
function GetAutosuggestWS(prefix_, flowType_, version_) {

    $.ajax({
        type: "POST",
        cache: false,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        url: "LocationSuggest/LocationSuggest.asmx/GetAutoSuggest",
         data: "{prefix_:" +"\""+ prefix_ +"\""+ ",flowType_:" +"\""+ flowType_ +"\""+",version_:" +"\""+ version_ +"\""+ ",portalId_:" +"\""+ portalId +"\""+ "}",
        success: function (response) {            
            //Load the content  
            if (response != null && response.d != 'undefined' && response.d != "SessionExpired") {
                
                DispSgstLst(response.d);
            }
        },
        beforeSend: function (XMLHttpRequest) {

        },
        complete: function (XMLHttpRequest, textStatus) {

        },
        error: function (xmlHttpRequest, status, err) {
        }
    });
}
//this method is used to check is valid zip code
function isValidZipCode(locCode)
{
    var re = new RegExp( "(^\\d{3,5}?$)|(^[ABCEGHJKLMNPRSTVXY]{1}\\d{1}[A-Z]{1} *\\d{1}[A-Z]{1}\\d{1}$)");     
    if (locCode.match(re)) 
       return true;    
    else  
        return false;       
}                  

