﻿//Aitport Seacrh
var urlAP = "/DesktopModules/Fareportal/Modules/Flight/AirportCode.aspx?frm=Form&textbox=";
//Airline Seacrh
var urlAL = "/DesktopModules/Fareportal/Modules/Flight/AirlineCode.aspx?textbox=";
var minYear=1900;var maxYear=2100;

var erMsgs = "";
var searchUnder;

var frmDt,toDt,hfd,htd;
var onNewWin = false; //For TravelSpot

var clickCount = 0;

var searchPopunder = true;  // For Search Pop under

//for storing portal path on ops team request
var globalPortalPath = "/";
//****************Culture Datetime Format Begin********************
var dtSep = "/";
var dayPos=1;
var monthPos=0;
var yearPos=2;
if (!window.cultureDateTimeFormat)
    var cultureDateTimeFormat = "mm/dd/yyyy";
if (!window.startDayOfWeek)
    var startDayOfWeek = 0;

function setDateParameters(cultureDateTimeFormatParam) {
    cultureDateTimeFormat = cultureDateTimeFormatParam;
    var dtymdPos = cultureDateTimeFormat.toLowerCase().split(dtSep);
    if (dtymdPos.length == 3) {
        if (dtymdPos[0].indexOf("d") >= 0) dayPos = 0; else if (dtymdPos[0].indexOf("m") >= 0) monthPos = 0; else if (dtymdPos[0].indexOf("y") >= 0) yearPos = 0;

        if (dtymdPos[1].indexOf("d") >= 0) dayPos = 1; else if (dtymdPos[1].indexOf("m") >= 0) monthPos = 1; else if (dtymdPos[1].indexOf("y") >= 0) yearPos = 1;

        if (dtymdPos[2].indexOf("d") >= 0) dayPos = 2; else if (dtymdPos[2].indexOf("m") >= 0) monthPos = 2; else if (dtymdPos[2].indexOf("y") >= 0) yearPos = 2;

    }
}
//****************Culture Datetime Format End********************


if(window.fpPortalPath)
    globalPortalPath = window.fpPortalPath;

//Contains pattern to match for formatting AutoSuggest List
var textToFormat = new Array();
function InitDates()
{
    document.onclick = HCal;
    //set default Dates
    frmDt = new Date();
    toDt = new Date();
    //Hotel only 2 days and for others 7 days
    frmDt.setDate(frmDt.getDate()+14);
    toDt.setDate(toDt.getDate()+16);    
    hfd = frmDt;
    htd = toDt;
    toDt.setDate(toDt.getDate()+5);
}

function InitPage()
{     
   var sLoc=window.location.search.toLowerCase();

    if(!singleTab)
    {
        var divName = GetDivName($.cookie("lstTab"));
        if (divName != 'undefined' && $('#' + divName).length > 0 && ((!window.fixTab) || fixTab == false))
        {
            showTab=$.cookie("lstTab");
            LoadRTab(showTab);
        }
    }

   InitDates(); //Initialize Dates    
   ShowForm(showTab);    
}

var bckGrnd = "pkgtabs STabflightbg4t";
function ShowForm(flowType)
{      
   curTab = flowType;   
   $("#hdFlt,#hdHtl,#hdCar,#hdPkg").hide();
   $("#errMsg").html("");
   $('#tabTd').removeAttr('class');
   HCal();

    switch (flowType)
    {
 
        case "F":
            bckGrnd = "pkgtabs STabflightbg";
            $('#hotelWidget,#carWidget,#packageWidget,#packageWidgetHC,#sugestBox').hide();
            $('#flightWidget,#hdFlt').show();
            if (window.LoadFltData) LoadFltData();
            break;
        case "H":
            bckGrnd = "pkgtabs STabhotelbg";
            $('#flightWidget,#carWidget,#packageWidget,#packageWidgetHC,#sugestBox').hide();
            $('#hotelWidget,#hdHtl').show();
            if (window.LoadHtlData) LoadHtlData();
            break;
        case "C":
            bckGrnd = "pkgtabs STabcarbg";
            $('#flightWidget,#hotelWidget,#packageWidget,#packageWidgetHC,#sugestBox').hide();
            $('#carWidget,#hdCar').show();
            if (window.LoadCarData) LoadCarData();
            break;
        case "P":
            bckGrnd = "pkgtabs STabpkgbg";
            $('#flightWidget,#hotelWidget,#carWidget,#packageWidgetHC,#sugestBox').hide();
            $('#packageWidget,#hdPkg').show();
            if (window.LoadPkgData) LoadPkgData();
            break;
        case "HC":
            bckGrnd = "pkgtabs STabpkgbgFH";
            $('#flightWidget,#hotelWidget,#carWidget,#packageWidget,#sugestBox').hide();
            $('#packageWidgetHC,#hdPkg').show();
            $("#rHtlCarHC").attr('checked', true);
            if (window.LoadPkgDataHC) LoadPkgDataHC();
            break;
    }

    if (window.visibleTabs)
        bckGrnd += window.visibleTabs;

    $("#tabTd").addClass(bckGrnd);
}

//Add tooltip message box and its cover
document.write("<div id='msgBox' class='msg_box'><div id='msgBoxInner' onclick='hideHoverInfo();'></div><div align='right'><a href='JavaScript:hideHoverInfo()' class='msgclosebtn'>Close [X]</a></div></div>");
    
function StDteOb(objNm,dtObj)
{
    $("#"+objNm).val((dtObj.getMonth()+1) + "/" + dtObj.getDate() + "/" + dtObj.getFullYear());
}

function GetDivName(tb)
{
    switch(tb)
    {
        case "F": return 'flightWidget';
        case "H": return 'hotelWidget';
        case "C": return 'carWidget';
        case "P": return 'packageWidget';
        case "HC": return 'packageWidgetHC';
    }
}

function LoadRTab(tb)
{
    if (tb == null || tb == '') return;

    if (window.Widget_OnTabChanged)
        window.Widget_OnTabChanged(curTab);

    $.cookie( "lstTab", tb, { path: '/', expires: 365 });
     if($('#'+GetDivName(tb)).html() == "") 
     {
        $('#dvLoader').show();
        LoadTab(tb);
     }
     else
        ShowForm(tb);

     return false;
}

$(document).ready(function () {

    if (!singleTab) {
        $('#showFlights').click(function () {
            LoadRTab("F");
        });

        $('#showCars').click(function () {
            LoadRTab("C");
        });

        $('#showHotels').click(function () {
            LoadRTab("H");
        });

        $('#showPkg').click(function () {
            if ($("#packageWidgetHC").length && $("#rHtlCar").attr('checked'))
                LoadRTab("HC");
            else
                LoadRTab("P");
        });
    }
    InitPage();

    if (window.Widget_OnLoad)
        window.Widget_OnLoad(curTab);
});

function SearchNow()
{
   var qry = "";
    switch (curTab)
    {
        case "F":            
             qry = GetAirQry();
            break;
        case "H":
             qry = GetHtlQry();
             break;
        case "C":
             qry = GetCarQry();
              break;
        case "P":
            qry = GetPkgQry();
            break;
        case "HC":
            qry = GetPkgHCQry();
    }
    
    if (qry == undefined) return;
     
    //For CheapoStay
    var qPrmVal = GetValForQParam("FpAffiliate");    
    var aQry = "";
    if(!IsNullEmpt(qPrmVal))
    {
        aQry += "&FpAffiliate=" +qPrmVal;
             
        qPrmVal = GetValForQParam("FpSub");
        if(!IsNullEmpt(qPrmVal))  aQry += "&FpSub=" +qPrmVal;
     
        qPrmVal = GetValForQParam("caid");
        if(!IsNullEmpt(qPrmVal))  aQry += "&caid=" +qPrmVal;
    }

    if (!window.disablePupupAndPopUnder || window.disablePupupAndPopUnder == false) {
        //For Search Popunder
        if (searchPopunder) {
            var clickedOnSearchButton = ++clickCount;
            try {
                if (!$.cookie('searchpopunder')) {
                    if (clickedOnSearchButton < 2) {
                        OpenSearchPopup(curTab);
                    }
                }
            }
            catch (err) { }
        }
        if (onNewWin)
            window.open(aQry + qry, "fareportal");
        else {
            if (curTab == "F" && (window.location.href.indexOf("cheapoair.com") != -1 || window.location.href.indexOf("onetravel.com") != -1) && !$.cookie('flightsu')) {
                DoSearchUnder(qry);
            }
            else if (curTab == "H" && (window.location.href.indexOf("cheapoair.com") != -1 || window.location.href.indexOf("onetravel.com") != -1 || window.location.href.indexOf("cheapostay.com") != -1)) {
                DoSearchUnderHotel(qry);
            }
            if (window.URLForPopupBeforeSearch != undefined && window.URLForPopupBeforeSearch != null) {
                var clicked = ++clickCount;
                try {
                    if (!$.cookie('signupuser')) {
                        if (clicked < 2) {
                            searchUnder = window.open(window.URLForPopupBeforeSearch, "fareportal", "resizable=no,toolbar=no,width=640,height=445,status=no,scrollbars=no,resizable=no");
                            searchUnder.blur();
                        }
                    }
                }
                catch (err) { }
                window.blur();
                window.focus();
            }
        }
    }
	if (window.Widget_BeforeSearch)
	    window.Widget_BeforeSearch(curTab);

    location = qry;
}

function GetTag(tagId)
{
    return document.getElementById(tagId);
}

function isDate(txtDate_, ctrlName, vldMsgReq)// expected format is mm/dd/yyyy
{
      var txtDt = $("#"+txtDate_).val();
      var oDt;  // date object initialized from the txtDate string
      var mSec; // milliseconds from txtDate	  
      
      if (txtDt.length > 10 || txtDt.length < 8) 
      {
          if (vldMsgReq == true) erMsgs += "<div> Please enter a valid " + ctrlName + " date in  " + cultureDateTimeFormat + ". </div>"; // The date format should be : "+ dtFrmt +" for " + ctrlName + " date </div>";
			return false;
      }

      try
      { 
        var date = txtDt.split("/");

        if(date.length == 3)
        {// subtraction will cast variables to integer implicitly
            var day = date[dayPos] - 0;
            var month = date[monthPos] - 1; // because months in JS start with 0
            var year  = date[yearPos] - 0;
        }
        else
        {
            if (vldMsgReq == true) erMsgs += "<div> Please enter a valid " + ctrlName + " date in  " + cultureDateTimeFormat + ". </div>";
            return false;
            
        }
      }
      catch(err)
      {
          if (vldMsgReq == true) erMsgs += "<div> Please enter a valid " + ctrlName + " date in  " + cultureDateTimeFormat + ". </div>"; 
        return false;
      }

    if (day > 31) {
        if (vldMsgReq == true) erMsgs += "<div> Please enter a valid " + ctrlName + " date in  " + cultureDateTimeFormat + ". </div>";
        return false;
    }
    if (month > 12) {
        if (vldMsgReq == true) erMsgs += "<div> Please enter a valid " + ctrlName + " date in  " + cultureDateTimeFormat + ". </div>";
        return false;
    }
    if (year < minYear || year > maxYear) 
      {
        if(vldMsgReq==true) erMsgs += "<div> Please enter a valid 4 digit year between " +  minYear +  " and " + maxYear + " for " + ctrlName + " date. </div>";
        return false;// test year range
      }

      mSec = (new Date(year, month, day)).getTime();// convert txtDate to the milliseconds
      oDt = new Date();// set the date object from milliseconds
      oDt.setTime(mSec);

      // if there exists difference then date isn't valid
      if (oDt.getFullYear() != year || oDt.getMonth() != month || oDt.getDate() != day)  
      {
          if (vldMsgReq == true) erMsgs += "<div> Please enter a valid " + ctrlName + " date. </div>";
        return false;
      }

      if(oDt < (new Date(new Date().toDateString())))//Can not less then current Date
      {
          if(vldMsgReq==true) erMsgs += "<div> " + ctrlName +" date can't be before today's date. </div>"; 
	      return false;
      }
      return true;
}

//--------calx.js

var CalS = '';
var CalE = '';

var cF=null;var cW=null;var g_tid=0;var g_cP,g_eD,g_eDP,g_dmin,g_dmax,g_dtsToBeSlct;
var g_dispCalOnRightOfCtrl;
var g_isDtRng;
var nextFocus;var g_fNoCal=false;

function SCal(cP,eD,eDP,dmin,dmax,dtsToBeSlct)
{
 clearTimeout(g_tid);

 if(g_fNoCal)
 {
    g_fNoCal=false;
    return;
 }
 if(g_calShown && eD==g_eD)
 {
    //    return;
 }
 g_calShown = true;
 g_calCB = null;
 g_cP=cP;
 g_eD=eD;
 g_eDP=eDP;
 g_dmin=dmin;
 g_dmax=dmax;
 g_dtsToBeSlct=dtsToBeSlct;
 
 WaitCal();
}

function WaitCal()
{ 
 if(!cW) cW=frames['calendar'];
 
 if(null==cW || null==cW.g_fCL || false==cW.g_fCL) g_tid=setTimeout("WaitCal()", 200);
 else
 {
     if(!cF)cF=getObj('calendar'); cF.style.visibility="hidden";
    setTimeout("DoCal()",1);
 }
}

function DoCal(){
    PosCal(g_cP);
    if (!cW) cW = frames['calendar']; cW.DoCal(g_eD, g_eDP, g_dmin, g_dmax, g_dtsToBeSlct, 2, curTab, g_isDtRng);
}

function getScrollTop()
{
    if(document.documentElement.scrollTop) return document.documentElement.scrollTop;
    if(document.body.scrollTop) return document.body.scrollTop;
    if(window.pageYOffset) return window.pageYOffset;
    return 0;
}

function getWinHeight()
{
    if(window.innerHeight) return window.innerHeight;
    if(document.documentElement.clientHeight) return document.documentElement.clientHeight;
    if(document.body.clientHeight) return document.body.clientHeight;
    return 0;
}

function PosCal(cP)
{
    var dB=document.body;var eL=0;var eT=0;
    if(!cF)cF=getObj('calendar');
    for(var p=cP;p&&p.tagName!='BODY';p=p.offsetParent){eL+=p.offsetLeft;eT+=p.offsetTop;}
    var eH=cP.offsetHeight;var dH=parseInt(cF.style.height);var sT=getScrollTop();
    
    if(g_dispCalOnRightOfCtrl)
    {
        //show cal with the top of text box if open at bottom 
        //and show cal with the bottom of text box if open at top
        if(eT-dH>=sT&&eT+dH>getWinHeight()+sT)eT-=(dH-eH);
        //Show cal on right of text box after image
            cF.style.left=eL+30+cP.offsetWidth+'px';cF.style.top=eT+'px'; 
    }
    else
    {
        if(eT-dH>=sT&&eT+eH+dH>getWinHeight()+sT)eT-=dH;else eT+=eH;
            cF.style.left=eL+'px';cF.style.top=eT+'px';
    }
}

function CalSetFocus(e){if(e){g_fNoCal=true;e.focus();setTimeout("EndCalFocus()", 200);}}
function EndCalFocus(){g_fNoCal=false;}

function CalDateSet(eInp,d,m,y,giveFocus)
{
    //var ds=GetDtSep();
    eInp.value= GetFormattedDate(y,m,d);
    if(!giveFocus)
    CalSetFocus(eInp);
}

var g_calShown = false;
function SetCalShown(fcshown){g_calShown=fcshown;}

var g_calCB;
function CalCallback(){if(g_calCB)g_calCB();}
function SetCalendarCallback(cb){g_calCB=cb;}

function GetInputDate(t)
{
    if(IsNullEmpt(t)) return null;
    t=t.replace(/\s+/g,"");
    if(t.match(/[^-|\d|\.|\/]/)) return null;
    var rgt=t.split(dtSep);
    for(var i=0;i<rgt.length;i++) rgt[i]=parseInt(rgt[i],10);
    if(!rgt[1]) return null;
    var m,d,y;

    if (!rgt[dayPos] || !rgt[monthPos] || !rgt[yearPos]) return null;
	m=rgt[monthPos];d=rgt[dayPos];y=rgt[yearPos];

    m-=1;if(y<100)y+=2000;
    if(y<1601||y>4500||m<0||(m)>11||d<1||d>GetMonthCount(m,y))return null;

    return new Date(y,m,d);
}


var rM=new Array(12);rM[0]=rM[2]=rM[4]=rM[6]=rM[7]=rM[9]=rM[11]=31;rM[3]=rM[5]=rM[8]=rM[10]=30;rM[1]=28;
function GetMonthCount(m,y){var c=rM[m];if((1==m)&&IsLY(y))c++;return c;}
function IsLY(y){if(0==y%4&&((y%100!=0)||(y%400==0)))return true;else return false;}
function DefYr(m,d){var dt=new Date();var yC=(dt.getYear()<1000)?1900+dt.getYear():dt.getYear();if(m<dt.getMonth()||(m==dt.getMonth()&&d<dt.getDate()))yC++;return yC;}

function GetDowStart() { return startDayOfWeek; } function GetDtFmt() { return "mmddyy"; } function GetDtSep() { return "/"; }
function ShowCalendar(eP,eD,eDP,dmin,dmax,dtsToBeSlct)
{
    SCal(eP,eD,eDP,dmin,dmax,dtsToBeSlct);
}

var zz, zv, d, fTSR;
d = new Date();
fTSR=0;
zv = d.getTime();
zz = "&zz="+zv;

var gBF=false;
function GoTo(u){window.top.location = u + zz;}
function Go(u){window.top.location = u;} 

function BF(){gBF=true;}

function getObj(objID)
{
    if (GetTag) return GetTag(objID);
    else if (document.all) return document.all[objID];
    else if (document.layers) return document.layers[objID];
}

var actvEl;
function HCal()
{
    if ($('#calendar'))    
        $('#calendar').hide();    
}

if(window.navigator.appName.toLowerCase().indexOf("netscape") > -1)
{
    window.captureEvents(Event.CLICK);
    window.onmousemove = NS_MouseEventHandler;
    window.event = new Object;
}

function NS_MouseEventHandler(theMouseEvent)
{
    window.event.clientX = theMouseEvent.pageX;
    window.event.clientY = theMouseEvent.pageY;

    //back to main event handler for the desired purpose
    if (window.routeEvent)
        window.routeEvent(theMouseEvent);
}

document.onkeydown = StartSearch; 
function StartSearch(keyEvent)
{   
    var keyPressedCode = (keyEvent != null ? keyEvent.keyCode : event.keyCode);
        
    if (keyPressedCode == 13 && blockSrch==false)
    {
        SearchNow();
        return false;//If Search is called then not do anything
    }
}

function showCalToSelectDate(obj,dtsToBeSlct,dtMin)
{
    var ctrl = GetTag(obj);
    CalS=dtMin;//set Minimum date
    SC(ctrl,dtsToBeSlct);
}

function hideCalendar()
{
    $("#calendar").hide();    
    $("#"+actvEl).focus();    
}

function SC(el,dtsToBeSlct)
{
    if ($('#calendar') == null) return;    
    var id = el.id;
    var n = el.id;
    el.select();
    var temp=id;
    ShowCalendar(el,el,GetTag(temp),CalS,CalE,dtsToBeSlct);
}

//Form Validation
function AddVldtnMsg()
{    
    if(erMsgs != undefined)
        if(!IsNullEmpt(erMsgs))
            $('#errMsg').html(erMsgs);    
    erMsgs = "";
}

function IsBlank(ctrlName, erMsg, wtrmark)
{
    var ctrl = $("#" +ctrlName);
    if(jQuery.trim(ctrl.val()).length==0 || ctrl.val() == wtrmark)
    {   
        erMsgs += "<div> " + erMsg + "</div>";      
        return true;
    }
    return false;
}

function IsVldDtRng(fmCtlNm, toCtlNm, erMsg)
{
    var valDt
    if(curTab=="H") valDt =(GetInputDate($("#"+fmCtlNm).val())) < (GetInputDate($("#"+toCtlNm).val()));
    else//Allow same day pickup and drop for car and same day Departure and Return for Air
        valDt = (GetInputDate($("#"+fmCtlNm).val())) <= (GetInputDate($("#"+toCtlNm).val()));
    if (!valDt)
    {
         erMsgs += "<div> " + erMsg + "</div>";
         return false;
    }
    return true;
}

function IsNumOrCd(ctlNm, erMsg, isCde)
{
    var ctrl = $("#"+ctlNm);
    var regExp = null;
    if(isCde == true) regExp = "(?=.*([0-9a-zA-Z]))";
    else regExp = "(?=.+([0-9a-zA-Z]))([0-9a-zA-Z ',&amp;().\/\_\-]*)";
   
    var re = new RegExp(regExp); 
    
    if (!ctrl.val().match(re)) 
    {
        erMsgs += "<div> " + erMsg + "</div>";        
        return false;
    }
    return true;
}
//create options list
function GenOpsForDDL(name,ops, strt, opToSel)
{
    for(var i=strt; i<ops + strt;i++)
        $('#'+name).append('<option value="' + i + '">' + i + '</option>');
    $('#'+name).val(opToSel);
}

 
//Populate City/ Airport/ Location    
function SetHdnForLoc(tbID, str)
{
    $('#hdnLocFrom').val(str.replace(/<\/?[^>]+(>|$)/g, ""));
    $("#"+tbID).val(str.split("***")[1].replace(/<\/?[^>]+(>|$)/g, ""));
} 

function GetLocCD(autoSgstCD, locTB)
{
    var loc = $("#" + autoSgstCD).val().replace(/[^a-zA-Z0-9@!&]/g, " ").replace(/[\s]+/g, " ");
    if (loc == "") loc = RemoveVulnerableChars($("#" + locTB).val().toUpperCase());
    if(loc.length > 3 && $("#"+autoSgstCD).val()!="") loc = loc.substring(0,3).toUpperCase();
    return loc;
}

/******************getAirportCode*********************/
function gtAptCde(theTagID, hidCtrlCdId)
{
    $("#"+hidCtrlCdId).val("");
    $("#"+theTagID).val("");
    $(".pplrdest input:radio").each(function() {$(this).attr('checked',false);});
    window.open(urlAP + theTagID,"AirportPicker","toolbar=no,status=no,resizable=no,scrollbars=yes,width=650,height=650,top=100,left=100");
}

function ShowHidett(show_)
{
    if(show_ == 'show') $('#minorMsg').show();
    else $('#minorMsg').hide();
}
function toggle(id) {
    if($("#"+id).is(':visible')) $("#"+id).hide();
    else $("#"+id).show();
}


function dispCalendar(elm,dt1,dt2,isDtRng,dispCalOnRightOfCtrl,showPassedDate)
{    
    g_dispCalOnRightOfCtrl = true;
    g_isDtRng = true;
    blockSrch = false;
    if(dispCalOnRightOfCtrl!=null)
        g_dispCalOnRightOfCtrl=dispCalOnRightOfCtrl;
        
    if(isDtRng!=null)
        g_isDtRng = isDtRng;
    
    if(curTab == "F" && $("#rbOW").is(':checked'))
        g_isDtRng=false;
    
    if(curTab == "H")
        g_dispCalOnRightOfCtrl=false;
    
    var mindt = '';
    if(showPassedDate==null || showPassedDate==false)
            mindt = (new Date()).toDateString();
            
    if(dt1 != null && dt2!=null && $("#"+dt1) != null && $("#"+dt2) != null)
    { 
        var setDt = false;
        if(dt1 != null && $("#"+dt1) != null && elm != dt1 )//case of from date
        {
            if($("#"+dt1).val()!=cultureDateTimeFormat && isDate(dt1,"",false) == true)
            {
                mindt =  GetInputDate($("#"+dt1).val()); //mindate will be from date                
        
            }

            setDt = true;
        }
        if(showPassedDate == true && setDt == false)
            mindt = '';
    }
    
    var fromTo = '';
    if(dt1 != null && $("#"+dt1) != null && $("#"+dt1).val()!=cultureDateTimeFormat)
    {
        fromTo = $("#"+dt1).val();
    }

    if(dt2 != null && $("#"+dt2) != null && $("#"+dt2).val()!=cultureDateTimeFormat && g_isDtRng == true)
    {
        fromTo += "," + $("#"+dt2).val();
    }
    else
        fromTo+= ",";
    
    showCalToSelectDate(elm,fromTo,mindt);    
}

// Decide browser version
var ns6 = (document.getElementById)? true:false;
var ie4 = (document.all)? true:false;
var ie5 = false;
var mX = 4;
var mY = 4;

// IE Stupidity Check.
if (ie4) 
{
    if ((navigator.userAgent.indexOf('MSIE 5') > 0) || (navigator.userAgent.indexOf('MSIE 6') > 0) || (navigator.userAgent.indexOf('MSIE 7') > 0)) 
        ie5 = true;    
    if (ns6) ns6 = false;
}


//Handle mouse location
document.onmousemove = mouseMove;
function mouseMove(e) {
    if (ns6) {
        mX=e.pageX; 
        mY=e.pageY;
        }
    else if (ie5) {
        mX=window.event.clientX;
        mY=(document.documentElement.scrollTop +  window.event.clientY);
        }
    else if (ie4) {
        mX=event.x; 
        mY=event.y;
        }
}

//add no of months in date
Date.prototype.addMonths = function(n)
{
    this.setMonth(this.getMonth()+n);
    return this;
}

/* ---------------------Jquery Cookie Code Starts -------------------------*/
$.cookie = function(name, value, options) {
    if (typeof value != 'undefined') 
    { // name and value given, set cookie
        options = options || {};
        if (value == null) 
        {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 86400000));//(24 * 60 * 60 * 1000);
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    }
     else 
     { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};
/* ---------------------Jquery Cookie Code Ends -------------------------*/



/* -----------------------Method to set Location From Hotel and Car RadioButtons--------------*/

function SetLocForPopLoc(str,tbID,hdnCntl)
{
    $("#"+hdnCntl).val(str.replace(/<\/?[^>]+(>|$)/g, ""));
    $("#"+tbID).val(str.split("***")[1].replace(/<\/?[^>]+(>|$)/g, ""));   
}

//Set value for hidden field controls
function SetHdnLocCode(txtBx,val)
{
  val = val.replace(/<\/?[^>]+(>|$)/g, "");      
  if(txtBx == 'tbTo') $("#hdnLocTo").val(val);
  else  $("#hdnLocFrom").val(val);     
}

function RemoveVulnerableChars(val) {
    if (val) return val.replace(/[^0-9a-zA-Z ',&amp;().*\/\_\-|]/g, " ").replace(/[\s]+/g, " ")
    return val;
}


//Save key/value pair for cookie
function SaveCookie(key, val, fltp, mtchIdxNo)
{   
    //if Saving of Recent search disabled then not saving the values in cookie
    if(window.blockRcntSrch != 'undefined' && window.blockRcntSrch != null && window.blockRcntSrch == true)
        return ;   

    var soVal=$.cookie("srOr"+ "-" + fltp);
    var srchExst=false;
    var srch='';    
    var ckIdx=1;
    var forMtchCk="";
    try{

        jQuery.each(val, function(i) {
            srch = srch + ($("#" + val[i]).is(":radio") == true ? $("#" + val[i]).is(':checked') : RemoveVulnerableChars($("#" + val[i]).val())) + '##';
            if(mtchIdxNo==(i+1))
                forMtchCk=srch.toLowerCase();
        });

        if(forMtchCk!=null && forMtchCk.length>0 && forMtchCk.substring(forMtchCk.length-2, forMtchCk.length) == '##') //Remove trailing for mathcing string ##
           forMtchCk = forMtchCk.substring(0, forMtchCk.length-2);

         if(srch!=null && srch.length>0 && srch.substring(srch.length-2, srch.length) == '##') //Remove trailing ##
            srch = srch.substring(0, srch.length-2);

        if(soVal != null && soVal.length > 0)
        {
            var ckArr = soVal.split("$$"); 
            for (var i = 0; i < ckArr.length; i++)
            {
                var ck=$.cookie( key+"-"+ckArr[i]);
                if (ck!=null && ck.length>0 && ck.toLowerCase().indexOf(forMtchCk)==0)
                {                
                    if(i==0)//if found at first position then return no need to change
                        return;                

                    srchExst=true;                    
                    
                    soVal = soVal.replace("$$"+ckArr[i], "");                
                    soVal = ckArr[i] + "$$" + soVal;             
                    ckIdx = i+1;
                    break;
                 }    
            }
        }
       
        if(srchExst==false)
        {
            if(soVal != null && soVal.length > 0)
            {            
                if(ckArr.length < 3)
                    ckIdx = ckArr.length + 1;
                else
                {   
                    ckIdx = ckArr[ckArr.length-1];
                    soVal = soVal.replace("$$"+ckIdx, "");                
                }
                soVal = ckIdx + "$$" + soVal;       
            } 
            else
                soVal = ckIdx; 

            $.cookie(key + "-" + ckIdx, jQuery.trim(srch), { path: '/', expires: 365 }); 
        }
        $.cookie("srOr" + "-" + fltp, soVal, { path: '/', expires: 365 });
    }
    catch(err){}        
	
}

//Set controls based on cookie value
function LoadRcntSrch(key, elem)
{   
    //if Saving of Recent search disabled then not saving the values in cookie
    if(window.blockRcntSrch != 'undefined' && window.blockRcntSrch != null && window.blockRcntSrch == true)
        return;

    var ctRL = elem.split(',');
            
    jQuery.each(key.split('##'), function(i) {       
        if($("#"+ctRL[i]).is(":radio") == true)
            $("#"+ctRL[i]).attr('checked', jQuery.trim(this) == "true");
        else
            $("#"+ctRL[i]).val(jQuery.trim(this));
    });
    
}

//Check to see value is null or empty
function IsNullEmpt(val)
{
    return (val == undefined || val == null || val.length == 0);
}

//Get Query String Value
function GetValForQParam(name)
{
    var results = (new RegExp("[\\?&]" + name.toLowerCase().replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]") + "=([^&#]*)", "i")).exec(window.location.href);
    if (results != null && results.length > 1)
        return $('<div/>').text(unescape(results[1])).html();
            
    return "";
}

//Fill html for respective div (Flight, Car, Hotel)
function LoadTab(category)
{ 
    $('#'+ GetDivName(category)).html(" ");   
     $.ajax({
         url: GetHTMLFilePath(category)+"?ver=4.0.3",
          cache: true,
          timeout : 10000,
          tryCount : 0,  
          retryLimit : 3,		  
          success: function(html){
            $('#'+ GetDivName(category)).html(html);
            ShowForm(category);           
            $('#dvLoader').hide();

          },
        error: function(xhr, textStatus, errorThrown){   
		    if (textStatus == 'timeout' || xhr.status == 500 || xhr.status == 0) 
		    {
    		    this.tryCount++;
    		    if (this.tryCount <= this.retryLimit) 
    		    {
        		    //try again
        		    $.ajax(this);
        		    return;
			    }
    		    return;
		    }
            $('#dvLoader').hide();
            $('#'+ GetDivName(category)).html('<div style="font-family:Arial; font-size:12px; color:#000000;"><b>Please refresh your browser window.</b></div>');
          }        
	});
}

//This function checks to see if departure/checkin/pickup date is expired, if expired it doesn't display that recentsearch
function ResetCkOrd(soCk, fltpCk, ord)
{
    var soVal = $.cookie(soCk);
    var ckArr = soVal.split("$$");
    if(ckArr[ckArr.length-1] != ord)
    {           
        soVal = soVal.replace(ord + "$$", "") + "$$" + ord;
        $.cookie(soCk, soVal, { path: '/', expires: 365 });
    }
    $.cookie(fltpCk + "-" + ord, null);
}

//This function populates controls from last search saved in cookie on window load
function FillCtrlLstSrch(sOrdCk, flTpCk, ctRL, idxDepDate)
{
    try {

        var dtl = $.cookie(flTpCk + "-" + $.cookie(sOrdCk).split("$$")[0]);
        if (dtl != null) 
        {
            var timedifms = (GetInputDate(dtl.split('##')[idxDepDate])).getTime() - (new Date().getTime());
            // checking if date is today onwards
            if (timedifms > 86400000)//(1000 * 60 * 60 * 24) 
                LoadRcntSrch(dtl, String(ctRL));
        }
    }
    catch (err) { }
}

function FillWidgetFromQryStr(paraNms,ctrlNms)
{
    var qryStrFound=false;
    for(var i=0;i<paraNms.length;i++)
    {
        var val = GetValForQParam(paraNms[i]);
        if(val.length!=0)
        {
            $("#"+ctrlNms[i]).val(val);
            qryStrFound=true;
         }
    }
    return qryStrFound;
}

/******************getAirlineCode*********************/
function gtAlnCde(theTagID)
{
    window.open(urlAL + theTagID, 'AirlineCode', 'toolbar=no,status=no,resizable=no,scrollbars=yes,width=300,height=400,top=100,left=100');
}



//This function is used get date as per locale format
function GetFormattedDate(y,m,d)
{

 var dt;
if(window.dayPos != 'undefined'  && window.dayPos != null &&  window.monthPos != 'undefined' && window.monthPos != null  && window.yearPos != 'undefined' && window.yearPos != null)
{
    //genrating First block of date
    if(dayPos==0) dt = d + dtSep; else if(monthPos==0) dt=m + dtSep; else  dt= y + dtSep;
        //genrating Second block of date
    if(dayPos==1) dt += d + dtSep; else if(monthPos==1) dt += m + dtSep; else  dt +=  y + dtSep;
    //genrating Third block of date
    if(dayPos==2) dt += d; else if(monthPos==2) dt += m ; else  dt += y ;
}
else // otherwise use default format (mm/dd/yyyy) 
{ 
    dt= m + dtSep + d + dtSep + y;
}
return dt;
}

 

//this method will convert current date format to US date format for given date value
function  getDateInUSFormat(t)
{
    if(IsNullEmpt(t)) return null;
    t=t.replace(/\s+/g,"");
    if(t.match(/[^-|\d|\.|\/]/)) return null;
    var rgt=t.split(dtSep);
    for(var i=0;i<rgt.length;i++) rgt[i]=parseInt(rgt[i],10);
    if(!rgt[1]) return null;
    var m,d,y;
    
    
    if(!rgt[dayPos]) return null;
	m=rgt[monthPos];d=rgt[dayPos];y=rgt[yearPos];

    if(y<100)y+=2000;
    if(y<1601||y>4500||m<0||(m-1)>11||d<1||d>GetMonthCount(m-1,y))    return null;
    return ( m + dtSep + d + dtSep + y );
}


/*******************Start Code for Search popunder*************/
var origin = '';
var destination = '';
var originName = '';
var destinationName = '';
var responseService = '';
var popupUrl;
var pageReferral;
var paramSearchPopup;
var domainName;
var today = new Date();
var IsEnablePopupForVacation = false;
var expiryHour = new Date(today.getTime() + 3600000);//(1 * 60 * 60 * 1000) It will be used to expire cookie in an hour


// Latest Version to get search popunder
function OpenSearchPopup(curTab) {
    try {
        if (window.portalID) {
            var searchPopupUrl = "/Portals/" + (window.portalID ? window.portalID : "") + "/popups/searchpopup.asp?";
            pageReferral = location.href;
            domainName = document.domain;
            var flowType = curTab;
            switch (flowType) {
                case "F":
                    if ($("#tbFrom").val().toLowerCase().indexOf("enter") < 0 && $("#tbTo").val().toLowerCase().indexOf("enter") < 0) {
                        if ($("#tbFrom").val().length > 3) {
                            originName = $("#tbFrom").val().split("- ")[1].split(",")[0];
                            origin = $("#tbFrom").val().split(" -")[0];
                        }
                        else {
                            originName = $("#tbFrom").val()
                            origin = $("#tbFrom").val()
                        }
                        if ($("#tbTo").val().length > 3) {
                            destinationName = $("#tbTo").val().split("- ")[1].split(",")[0];
                            destination = $("#tbTo").val().split(" -")[0];
                        }
                        else {
                            destinationName = $("#tbTo").val();
                            destination = $("#tbTo").val();
                        }
                        if (origin != undefined && destination != undefined && origin != '' && destination != '') {
                            GetPoppupServiceResponseV2(origin, destination, "f");
                            if (responseService != '' && responseService.toLowerCase() != 'false') {
                                popupUrl = searchPopupUrl + responseService + "&pagerererral=" + pageReferral;
                                try {
                                    if (navigator.appName == "Microsoft Internet Explorer") {
                                        window.open(popupUrl, "searchUnder", "resizable=no,toolbar=no,width=681,height=362,status=no,scrollbars=no,resizable=no");
                                        $.cookie('searchpopunder', 'searchUnder', { expires: expiryHour });
                                    }
                                }
                                catch (err) { }
                            }
                        }
                    }
                    break;
                case "H":
                    if ($("#tbHLoc").val().toLowerCase().indexOf("enter") < 0) {
                        if (window.GetDestinationCityCode) {
                            destinationName = GetDestinationCityCode();
                        }
                        if (destinationName == '' || destinationName == undefined) {
                            if ($("#tbHLoc").val().length > 3) {
                                destinationName = $("#tbHLoc").val().split(",")[0];
                            }
                            else {
                                destinationName = $("#tbHLoc").val();
                            }
                        }
                        if (destinationName != undefined && destinationName != '') {
                            GetPoppupServiceResponseV2(origin, destinationName, "h");
                            if (responseService != '' && responseService.toLowerCase() != 'false') {
                                popupUrl = searchPopupUrl + responseService + "&pagerererral=" + pageReferral;
                                SearchUnderPopUpOpen(popupUrl, true);
                            }
                        }
                    }
                    break;
                case "C":
                    if ($("#tbCLoc").val().toLowerCase().indexOf("enter") < 0) {
                        if (window.GetOriginCityCode) {
                            origin = GetOriginCityCode();
                        }
                        if (origin == '' || origin == undefined) {
                            if ($('#tbCLoc').val().length > 3) {
                                originName = $('#tbCLoc').val().split(",")[0];
                                origin = $("#tbCLoc").val().split(" -")[0];
                            }
                            else {
                                origin = $('#tbCLoc').val();
                            }
                        }
                        if (origin != undefined && origin != '') {
                            GetPoppupServiceResponseV2(origin, destination, "c");
                            if (responseService != '' && responseService.toLowerCase() != 'false') {
                                popupUrl = searchPopupUrl + responseService + "&pagerererral=" + pageReferral;
                                SearchUnderPopUpOpen(popupUrl, true);
                            }
                        }
                    }
                    break;
                case "P":
                    if (IsEnablePopupForVacation) {
                        if ($("#tbPFrom").val().toLowerCase().indexOf("enter") < 0 && $("#tbPTo").val().toLowerCase().indexOf("enter") < 0) {
                            if ($("#tbPFrom").val().length > 3) {
                                originName = $("#tbPFrom").val().split(",")[0];
                            }
                            else {
                                originName = $("#tbPFrom").val();
                            }
                            if ($("#tbPTo").val().length > 3) {
                                destinationName = $("#tbPTo").val().split(",")[0];
                            }
                            else {
                                destinationName = $("#tbPTo").val();
                            }
                            if (originName != undefined && destinationName != undefined && originName != '' && destinationName != '') {
                                GetPoppupServiceResponseV2(originName, destinationName, flowType);
                                if (responseService != '' && responseService.toLowerCase() != 'false') {
                                    popupUrl = searchPopupUrl + responseService + "&pagerererral=" + pageReferral;
                                    SearchUnderPopUpOpen(popupUrl, false);
                                }
                            }
                        }
                    }
                    break;
            }
            window.blur();
            window.focus();
        }
    }
    catch (err) {
        //alert(err);
    }  
}

function SearchUnderPopUpOpen(popupUrl,IsEnable) {
    try {
        if (IsEnable) {
            if (navigator.appName == "Microsoft Internet Explorer") {
                window.open(popupUrl, 'searchUnder', "resizable=no,toolbar=no,width=681,height=362,status=no,scrollbars=no,resizable=no");
                $.cookie('searchpopunder', 'searchUnder', { expires: expiryHour });
            }
        }
    }
    catch (err) { }
}


function GetPoppupServiceResponseV2(origin, destination, flowType) {
    $.ajax({
        type: "POST",
        async: false,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        url: "/DesktopModules/Misc/AffiliatePopupService.asmx/GetSearchPopunderV2",
        data: "{'originCityCode_':'" + origin + "','destinationCityCode_':'" + destination + "','flowtype_':'" + flowType + "'}",
        success: function (response) {
            responseService =  response.d;
        }
    });
}


/*******************End Code for Search popunder*************/

function GetHTMLFilePath(category) {
    switch (category) {
        case "F": if (window.htmlFlight) return window.htmlFlight;
        case "H": if (window.htmlHotel) return window.htmlHotel;
        case "C": if (window.htmlCar) return window.htmlCar;
        case "P": if (window.htmlPackage) return window.htmlPackage;
        case "HC": if (window.htmlPackageHC) return window.htmlPackageHC;
    }
    return globalPortalPath + "portals/" + (window.portalID ? window.portalID : "") + "/widget/" + category + ".htm";
}

