//Aitport Seacrh
var urlAP = "../desktopmodules/tripmamaotherpages/airportcode.aspx?textbox=";

var urlMaster = "../default.aspx?"
var dtCh= "/";
var minYear=1900;
var maxYear=2100;

var errMsgs = "";
var fWtrmrk = "Enter a city or airport";
var hWtrmrk = "Enter a city, airport or landmark";
var cWtrmrk = "Enter a city or airport";
var pWtrmrk = "Enter a city or airport";
var dateWtrmrk ="mm/dd/yyyy";

//Below variable used to called the New AutoSuggest, this variable is used in autosuggestdropdownnew.js
var version ="1.0";

//add no of months in date
Date.prototype.addMonths = function(n)
{
    this.setMonth(this.getMonth()+n);
    return this;
}

String.prototype.trim = function() 
{ 
    return this.replace(/^\s+|\s+$/, ''); 
};
function SetInitialDates()
{
	document.onclick = HCal;
}

function HCal()
{
	if (GetTag('calendar'))
	{
		GetTag('calendar').style.visibility="hidden";
	}
}

function StDteOb(objNm,dtObj)
{
	GetTag(objNm).value = (dtObj.getMonth()+1) + "/" + dtObj.getDate() + "/" + dtObj.getFullYear();
}
SetInitialDates(); //Initialize Dates

function GetTag(tagId)
{
	return document.getElementById(tagId);
}
function setRdate(depID, retID)
{
    setReturnDate(depID, retID, curTab, $("#rbOW").is(':checked'));
}

function setReturnDate(depID, retID, bookingType, isOneWayTrip)
{
	if(bookingType=="F" && isOneWayTrip == true)
        return;

    if (GetTag(depID).value == "" || GetTag(depID).value == "mm/dd/yyyy")
        return;
    var curDt = new Date(GetTag(depID).value);
    if(curDt != "Invalid Date" &&  curDt != "NaN")
    {
		/*if(bookingType=="H")
			curDt.setDate(curDt.getDate()+2);
		else
			curDt.setDate(curDt.getDate()+7);
			
		var retDt = new Date(GetTag(retID).value);
		if(retDt == "Invalid Date" || retDt == "NaN" || (new Date(GetTag(depID).value)) > retDt)
            GetTag(retID).value = curDt.getMonth()+1+'/'+curDt.getDate()+'/'+curDt.getFullYear();*/
    }
}
//Checking if the query string has some value the it return false
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;
}
//Get Query String Value
function GetValForQParam(name) {
    var results = (new RegExp("[\\?&]" + name.toLowerCase().replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]") + "=([^&#]*)")).exec(window.location.href.toLowerCase());
    if (results != null && results.length > 1)
        return unescape(results[1]);
    return "";
}
//Save key/value pair for cookie
function SaveCookie(key, val, fltp, mtchIdxNo,Isfrmcruise) {
    //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) {
            if (Isfrmcruise == true)
                srch = srch + ($("#" + val[i]).is(":checkbox") == true ? $("#" + val[i]).is(':checked') : $("#" + val[i]).val()) + '##';
            else
                srch = srch + ($("#" + val[i]).is(":radio") == true ? $("#" + val[i]).is(':checked') : $("#" + 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));
        }
        $.cookie("srOr" + "-" + fltp, soVal);
    }
    catch (err) {
        alert(err.Message);
    }

}
function FillCtrlLstSrch(sOrdCk, flTpCk, ctRL, idxDepDate) {
    try {
        var dtl = $.cookie(flTpCk + "-" + $.cookie(sOrdCk).split(",")[0]);
        if (dtl != null)
            if ((Math.round(Math.abs(((new Date(dtl.split('##')[idxDepDate])).getTime() - new Date().getTime())) / (1000 * 60 * 60 * 24))) >= 0) // checking if date is today onwards    
                LoadRcntSrch(dtl, String(ctRL));
    }
    catch (err) { alert(err.Message); }
}
//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));
    });
}
function SetWaterMark(tbNm, evnt)
{
    var el = GetTag(tbNm);
    var wtrmrk = "";
    
    if(el.id=="tbFrom" || el.id=="tbTo" || el.id=="tbReturn_From" || el.id=="tbReturn_To")
        wtrmrk = fWtrmrk;
    else if(el.id=="tbCLoc")
        wtrmrk = cWtrmrk;
    else if(el.id=="tbHLoc")
        wtrmrk = hWtrmrk;
    else if(el.id=="tbPkgFrom" || el.id=="tbPkgTo")
        wtrmrk = pWtrmrk;
        
    if(evnt=="focus")
        if(el.value==wtrmrk)
            el.value="";
        else
            el.select();    
    else if(el.value=='')	
            el.value=wtrmrk;
    
}
//Form Validation
function AddVldtnMsg(tab)
{
	if(errMsgs != null && errMsgs != undefined)
		if(errMsgs!="")
		{
		    switch(tab)
		    {
		        case "F":
			        GetTag('errMsgAir').innerHTML  =  errMsgs ;
			        break;
		        case "H":
    			    GetTag('errMsgHotel').innerHTML  =  errMsgs ;
			        break;
		        case "C":
			        GetTag('errMsgCar').innerHTML  =  errMsgs ;
			        break;
			    case "VS":
			        GetTag('errMsgPack').innerHTML  =  errMsgs ;
			        break;
			case "CR":
				GetTag('errMsgCru').innerHTML = errMsgs ;
				break; 
		    }
		}	
	errMsgs = "";
}

function ShowTabs(showFor)
{
    
    if(curTab == showFor)
        return;

	var bckGrnd = "";
	
	GetTag("tb1").className = 'TabFlights';
	GetTag("tb2").className = 'TabHotels';
	GetTag("tb3").className = 'TabCars';
	GetTag("tb4").className = 'TabCruises';
	GetTag("tb5").className = 'TabPackages';
	
	var selTab ="";
    
    switch (showFor)
    {
		case "F":
			curTab = "F";
			$('#hotelWidget,#carWidget,#packageWidget,#cruiseWidget').hide();     
			$('#flightWidget').show();
			bckGrnd = 'TabFlightsActive';
			selTab ='tb1'
			break;
		case "H":
			curTab = "H";
			$('#flightWidget,#carWidget,#packageWidget,#cruiseWidget').hide();     
			$('#hotelWidget').show();
			bckGrnd = 'TabHotelsActive';
			selTab ='tb2'
			break;
		case "C":
			curTab = "C";
			$('#flightWidget,#hotelWidget,#packageWidget,#cruiseWidget').hide();     
			$('#carWidget').show();
			bckGrnd = 'TabCarActive';
			selTab ='tb3'
			break;   
		case "CR":
			curTab = "CR";
			$('#flightWidget,#hotelWidget,#carWidget,#packageWidget').hide();     
			$('#cruiseWidget').show();
			bckGrnd = 'TabCruisesActive';
			selTab ='tb4'
			break; 
		case "VS":
			curTab = "VS";
			$('#flightWidget,#hotelWidget,#carWidget,#cruiseWidget').hide();     
			$('#packageWidget').show();
			bckGrnd = 'TabPackagesActive';
			selTab ='tb5'
			break;   
    }

	
	GetTag(selTab).className=bckGrnd;
}
//Fill html for respective div (Flight, Car, Hotel)
function LoadTab(category)
{ 
    jQuery('#'+ GetDivName(category)).html(" ");   
     jQuery.ajax({
         url: "/widget/widgetV2/" + category + ".htm",
          cache: true,
          timeout : 10000,
          tryCount : 0,  
          retryLimit : 3,		  
          success: function(html){
            ShowTabs(category);           
            jQuery('#'+ GetDivName(category)).html(html);
            jQuery('#dvLoader').hide();
            ShowTabs(category);           

          },
        error: function(xhr, textStatus, errorThrown){   
		    if (textStatus == 'timeout' || xhr.status == 500 || xhr.status == 0) 
		    {
    		    this.tryCount++;
    		    if (this.tryCount <= this.retryLimit) 
    		    {
        		    //try again
        		    jQuery.ajax(this);
        		    return;
			    }
    		    return;
		    }
            jQuery('#dvLoader').hide();
            jQuery('#'+ GetDivName(category)).html('<div style="font-family:Arial; font-size:12px; color:#000000;"><b>Please refresh your browser window.</b></div>');
          }        
	});
}

function LoadRTab(tb)
{
    if(tb==null || tb=='') return;

    jQuery.cookie( "lstTab", tb);
     if(jQuery('#'+GetDivName(tb)).html() == "") 
     {
        jQuery('#dvLoader').show();
        LoadTab(tb);
     }
     else
        ShowTabs(tb);
     changeLogos(tb);

     return false;
}
function GetDivName(tb)
{
    switch(tb)
    {
        case "F": return 'flightWidget';
        case "H": return 'hotelWidget';
        case "C": return 'carWidget';
        case "VS": return 'packageWidget';
	case "CR": return 'cruiseWidget';
    }
}

jQuery(document).ready(function() {
      jQuery('#tb1').click(function() {
            LoadRTab("F");
      });
      
      jQuery('#tb2').click(function() {
            LoadRTab("H");
      });
      
      jQuery('#tb3').click(function() {
            LoadRTab("C");
      }); 

      jQuery('#tb4').click(function() {                
            LoadRTab("CR");
  }); 
      jQuery('#tb5').click(function() {                
            LoadRTab("VS");
  }); 
InitPage();
  
});
function IsBlank(ctrlName, errMsg, wtrmark,stFocus)
{
	var ctrl = GetTag(ctrlName);
    if(ctrl.value.trim().length==0 || ctrl.value == wtrmark)
    {   
        errMsgs += "<div>&bull; " + errMsg + "</div>";
        if(stFocus)ctrl.focus();
		return true;
    }
	return false;
}

function IsVldNmOrCd(ctlNm, errMsg, isCde,stFocus)
{
	var ctrl = GetTag(ctlNm);

    var regExp = null;
    if(isCde == true)
        regExp = "(?=.*([0-9a-zA-Z]))";
    else if(ctlNm =='tbHLoc')
        regExp = "(?=.+([a-zA-Z]))([0-9a-zA-Z ',&amp;()./\_-]*)";
    else
        regExp = "(?=.+([a-zA-Z]))([0-9a-zA-Z ',&amp;()./\_-]*).{3,}";

	var re = new RegExp(regExp);    
	if (!ctrl.value.match(re)) 
	{
		errMsgs += "<div>&bull; " + errMsg + "</div>";
		if(stFocus) ctrl.focus();
		return false;
	}
    return true;
}

function isDtVld(ctrlName,ctlDtl,stFocus)
{
	var ctrl = GetTag(ctrlName);
	if(!IsDtVld(ctrl.value,ctlDtl))
	{
		//if(stFocus)ctrl.focus();
		return false;
	}  
	return 	true;
}
function IsDtVld(dtStr,ctrlName)
{
	var daysInMon = DaysArray(12);
	var pos1=dtStr.indexOf(dtCh);
	var pos2=dtStr.indexOf(dtCh,pos1+1);
	var strMon=dtStr.substring(0,pos1);
	var strDay=dtStr.substring(pos1+1,pos2);
	var strYr=dtStr.substring(pos2+1);
	var isvalid=true;
	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
	if (strMon.charAt(0)=="0" && strMon.length>1) strMon=strMon.substring(1)
	for (var i = 1; i <= 3; i++) 
	{
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1);
	}
	month=parseInt(strMon);
	day=parseInt(strDay);
	year=parseInt(strYr);
	if (pos1==-1 || pos2==-1)
	{
		errMsgs += "<div>&bull; The date format should be : mm/dd/yyyy for " + ctrlName + " date</div>";
		return false;
	}
	if (strMon.length<1 || month<1 || month>12)
	{
		errMsgs += "<div>&bull; Please enter a valid month for " + ctrlName + " date </div>";
		return false;
	}
	//if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMon[month])
	if (day<1 || day>31)
	{
		errMsgs += "<div>&bull; Please enter a valid day for " + ctrlName + " date </div>";
		return false;
	}
	if (strYr.length != 4 || year==0 || year<minYear || year>maxYear)
	{
		errMsgs += "<div>&bull; Please enter a valid 4 digit year between " +  minYear +  " and " + maxYear + " for " + ctrlName + " date </div>";
		return false;
	}

	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || IsInt(stripCharsInBag(dtStr, dtCh))==false)
	{
		errMsgs += "<div>&bull;  Please enter a valid " + ctrlName + " date </div>"; 
		return false;
	}
	
	if((new Date(dtStr)) < (new Date(new Date().toDateString())))//Can not less then current Date
	{
	    errMsgs += "<div>&bull; " + ctrlName + " date can't be before today's date </div>"; 
		return false;
	}
	return isvalid;
	
}
function DaysArray(n)
{
	for (var i = 1; i <= n; i++)
	{
		this[i] = 31;
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
   }
   return this;
}
function IsInt(s)
{
	var i;
    for (i = 0; i < s.length; i++)
	{
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}
function stripCharsInBag(s, bag)
{
	var i;
    var retStr = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++)
	{
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) retStr += c;
    }
    return retStr;
}

function GetLocCD(locTB)
{
    var loc = GetTag(locTB).value.toUpperCase();
	if(loc.length > 3)
		loc = loc.substring(0,3).toUpperCase();
	return loc;
	
}
function IsVldDtRng(fmCtlNm, toCtlNm, errMsg,stFocus)
{
    var valDt
    if(curTab=="A" || curTab=="C")
    	valDt = (new Date(GetTag(fmCtlNm).value)) > (new Date(GetTag(toCtlNm).value));
    else
    	valDt =(new Date(GetTag(fmCtlNm).value)) >= (new Date(GetTag(toCtlNm).value))
    if (valDt)
	{
		 errMsgs += "<div>&bull; " + errMsg + "</div>";
		 if(stFocus)GetTag(fmCtlNm).focus();
		 return false;
	}
	return true;
}

//Check Departure and Return Date is Greater Than Today Date And Not greater than 11 months
function IsValidDepartureAndReturnDate(tbDepReturnDate,errMsg,isDepDate)
{
    var valDt  
    if(isDepDate)
    {              
       valDt = (new Date(GetTag(tbDepReturnDate).value)) > (new Date()) && (new Date(GetTag(tbDepReturnDate).value))< (new Date().addMonths(11)) ; 
    }
    else
    {
       valDt =(new Date(GetTag(tbDepReturnDate).value))<=(new Date().addMonths(11)) ;  
    }
      
    if (!valDt)
    {
        errMsgs += "<div>&bull; " + errMsg + "</div>";        
        return false;
    }
    return true;        
}

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 SearchNow() {

    var srchStr = urlMaster;
    switch (curTab) {
        case "F":
            srchStr = GetAirQry(srchStr);
            break;
        case "H":
            srchStr = GetHtlQry(srchStr);
            break;
        case "C":
            srchStr = GetCarQry(srchStr);
            break;
        case "CR":
            srchStr = GetCRQry(srchStr);
            break;
        case "VS":
            srchStr = GetPkgQry(srchStr);
            break;
    }
if (srchStr == undefined) return;
	        location = srchStr;
}

function gtAptCde(theTagID)
{
    GetTag(theTagID).value="";
    GetTag('hdnLocFrom').value ="";
	window.open(urlAP + theTagID,"AirportPicker","toolbar=no,status=no,resizable=no,scrollbars=yes,width=650,height=650,top=100,left=100");
}

/*-------------js required by calendar---------------------*/

//--------calx.js

var FDate = 'mm/dd/yy';
var TDate = 'mm/dd/yy';
var MDate = '';
var CalS = '';
var CalE = '';

var FTime = '362';
var TTime = '362';


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 getEventObj(e){if(!e)e=window.event;return e;}

function stopBubble(e){e=getEventObj(e);e.cancelBubble=true;if(e.stopPropagation)e.stopPropagation();}

function CB(){stopBubble(event);}

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 CancelCal(){clearTimeout(g_tid);if(!cF)cF=getObj('calendar');cF.style.visibility="hidden";g_calShown=false;}
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 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);else eT+=eH;
	    //Show cal on right of text box after image
	     cF.style.left=eL+'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 SetNextFocus(e){nextFocus=e;if(nextFocus)nextFocus.onfocus=CancelCal;}
function SetPrevFocus(e){if(e)e.onfocus=CancelCal;}

function FGoNextFocus(){if(nextFocus){nextFocus.focus();return true;}return false;}

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();
	var fmt=GetDtFmt();

	if(fmt=="mmddyy")eInp.value=m+ds+d+ds+y;
	else if(fmt=="ddmmyy")eInp.value=d+ds+m+ds+y;
	else eInp.value=y+ds+m+ds+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(!t.length) return null;
	t=t.replace(/\s+/g,"");
	if(t.match(/[^-|\d|\.|\/]/)) return null;
	var rgt=t.split(/-|\.|\//);
	for(var i=0;i<rgt.length;i++) rgt[i]=parseInt(rgt[i],10);
	if(!rgt[1]) return null;
	var m,d,y;
	var fmt=GetDtFmt();
	if(fmt=="yymmdd")
	{
	if(!rgt[2]) return null;
	m=rgt[1];d=rgt[2];y=rgt[0];
	}
	else
	{
	if(fmt=="mmddyy"){m=rgt[0];d=rgt[1];}
	else{m=rgt[1];d=rgt[0];}//fmt=="ddmmyy"
	if(rgt[2])y=rgt[2];
	else y=DefYr(m-1,d);
	}
	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 0;}function GetDtFmt() {return "mmddyy";}function GetDtSep() {return "/";}
function ShowCalendar(eP,eD,eDP,dmin,dmax,dtsToBeSlct)
{

	SCal(eP,eD,eDP,dmin,dmax,dtsToBeSlct);
	
}
function ShowCalSimp(fm,eD,eDP,dmin,dmax,dtsToBeSlct){
 if(!dmin)dmin='3/1/2005';if(!dmax)dmax='1/25/2006';
 if(fm){SetNextFocus(objNext(fm,eD));SetPrevFocus(objPrev(fm,eD));}
 SCal(eD,eD,eDP,dmin,dmax,dtsToBeSlct);
}
var actvEl;

function showCalToSelectDate(obj,dtsToBeSlct,dtMin)
{
    var ctrl = GetTag(obj);
    CalS=dtMin;//set Minimum date
	SC(ctrl,dtsToBeSlct);
}

function hideCalendar()
{
	GetTag("calendar").style.display = "none";
	GetTag(actvEl).focus();	
}

function DE(el)
{
    return GetTag(el);
}

function SC(el,dtsToBeSlct)
{
	if (DE('calendar') == null)
	{
	    return;
	}
	var id = el.id;
	var n = el.id;
	el.select();
	var temp=id;
	ShowCalendar(el,el,DE(temp),CalS,CalE,dtsToBeSlct);
}

function IsOffAirport(hdnVal)
{
    if(GetTag(hdnVal) != null && GetTag(hdnVal).value != "" && 
       GetTag(hdnVal).value.split("|").length > 0 && GetTag(hdnVal).value.split("|")[1] != null && GetTag(hdnVal).value.split("|")[1] != undefined &&
       GetTag(hdnVal).value.split("|")[1].split("***")[0] != null && GetTag(hdnVal).value.split("|")[1].split("***")[0] != undefined)
            return GetTag(hdnVal).value.split("|")[1].split("***")[0];
    else
        return "1"; //By Default At Airport
}
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()!=dateWtrmrk && isDate(dt1,"",false) == true)
                mindt= $("#"+dt1).val(); //mindate will be from date 

            setDt = true;
        }
        if(showPassedDate == true && setDt == false)
            mindt = '';
    }
    
    var fromTo = '';
    if(dt1 != null && $("#"+dt1) != null && $("#"+dt1).val()!=dateWtrmrk )
        fromTo = $("#"+dt1).val();

    if(dt2 != null && $("#"+dt2) != null && $("#"+dt2).val()!=dateWtrmrk && g_isDtRng == true)
        fromTo += "," + $("#"+dt2).val();
    else
        fromTo+= ",";
    
    showCalToSelectDate(elm,fromTo,mindt);    
}

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 select a valid " + ctrlName + " date. Required Format -  "+ dateWtrmrk + " </div>"; // The date format should be : "+ dateWtrmrk +" 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[1] - 0;
            var month = date[0] - 1; // because months in JS start with 0
            var year  = date[2] - 0;
        }
        else
        {	                  
            if(vldMsgReq==true) erMsgs += "<div> Please select a valid " + ctrlName + " date. Required Format -  "+ dateWtrmrk + " </div>";
            return false;
            
        }
      }
      catch(err)
      {
        if(vldMsgReq==true) erMsgs += "<div> Please select a valid " + ctrlName + " date. Required Format -  "+ dateWtrmrk + " </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 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;
}

/*-------------End of -- js required by calendar---------------------*/

function GoToMaster(goFor_)
{
    if(goFor_ == "D")
    {
        //In case of Deals, redirect to Travel Deal
        Go(urlMaster + "tabid=64");
    }
    else if(goFor_ == "C")
    {
        //In case of Cars, redirect to Master Car
        Go(urlMaster + "tabid=116");
    }
    else if(goFor_ == "H")
    {
        //In case of Hotels, redirect to Master Hotel
        Go(urlMaster + "tabid=115");
    }
    else
    {
        Go(urlMaster + "tabid=36");
    }
}
function UnCheckRadioSelection(tagName)
{
 var radioBtnList = document.getElementsByName(tagName);
 for(var item = 0; item<radioBtnList.length; item++)
 {
    if(radioBtnList[item].checked == true)
    {
        radioBtnList[item].checked = false;
    }
 }
}
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 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 getObj(objID)
	{
	if (document.getElementById) {return document.getElementById(objID);}
	else if (document.all) {return document.all[objID];}
	else if (document.layers) {return document.layers[objID];}
	}

//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);
}

//Code Added to execute Search on Enter click on Continue Button
document.onkeydown = ContinueSearch; 
function ContinueSearch(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
	}
	else if( blockSrch==true)
	{
	     blockSrch=false;
	}
}

function SetEmailIdInAllBox(curTab)
{
	switch (curTab)
    {
		case "F":
			selTab=1;
			break;
		case "H":
			selTab=2;
			break;
		case "C":
			selTab=3;
			break;   
		case "CR":
			selTab=4;
			break; 
		case "VS":
			selTab=5;
			break;   
    }
	for(i=1;i<=5;i++)
	{
		 $('#emailID'+i).val($('#emailID'+selTab).val());
	}
}
function SendSignUpEmail(selTab)
{
	if(GetTag("rbYes"+selTab) != null && GetTag("rbYes"+selTab).checked == true)
    {
		var currentObj=this;
	
        jQuery.ajax({
               type: "POST",
               async:false,
               contentType: "application/json; charset=utf-8",  
               dataType: "json",
               url: "http://www.tripmama.com/tmnewsletterservice.asmx/dosignupontripmama",
               data: "{'email_':'" + GetTag("emailID"+selTab).value + "','originCity_':''}"
            });
    }
}
function ValidateEmailAddress(selTab)
{
	if(GetTag("rbYes"+selTab) != null && GetTag("rbYes"+selTab).checked == true)
    {	
		var emailpat = /^((\w+\+*\-*)+\.?)*[\w-]+@((\w+\+*\-*)+\.?)*[\w-]+\.[a-z]{2,6}$/;
		var emailField = GetTag("emailID"+selTab);

		if(emailField.value.trim().length==0 )
		{
			errMsgs += "<div>&bull; Email id can't be left blank! </div>";
			return false;
		}
		else if(!emailpat.test(emailField.value ))
		{
			errMsgs += "<div>&bull; Enter correct e-mail address! </div>";
			emailField.focus();
			emailField.select();
			return false;
		}
		return true;
	}
	return true;
}
function ShowHideEmailBox(isSubscribe_, selTab)
{
	if(isSubscribe_ == true)
	{	
		for(i=1;i<=5;i++)
		{		$('#divEmailBox'+i).show(); $('#rbYes'+i).attr('checked', true);$('#rbNo'+i).attr('checked', false);}
	}
	else
	{	for(i=1;i<=5;i++)
		{		$('#divEmailBox'+i).hide(); $('#emailID'+i).val(''); $('#rbYes'+i).attr('checked', false);$('#rbNo'+i).attr('checked', true);}
	}
}
/*******************Add Cookie Library*******************/

function GetCookieVal(offset) {
    var endstr = document.cookie.indexOf(";", offset);
    if (endstr == -1) { endstr = document.cookie.length; }
    return unescape(document.cookie.substring(offset, endstr));
}

function GetCookie(name) {

    var arg = name + "=";
    var alen = arg.length;
    var clen = document.cookie.length;
    var i = 0;
    while (i < clen) {
        var j = i + alen;
        if (document.cookie.substring(i, j) == arg) {
            return GetCookieVal(j);
        }
        i = document.cookie.indexOf(" ", i) + 1;
        if (i == 0) break;
    }
    return null;
}

function DeleteCookie(name, path, domain) {
    if (GetCookie(name)) {
        document.cookie = name + "=" +
    ((path) ? "; path=" + path : "") +
    ((domain) ? "; domain=" + domain : "") +
    "; expires=Thu, 01-Jan-2000 00:00:01 GMT";
    }
}
function SetCookie(name, value, expires, path, domain, secure) {


    window.opener.document.cookie = name + "=" + escape(value) +

    ((expires) ? "; expires=" + expires.toGMTString() : "") +
    ((path) ? "; path=" + path : "") +
    ((domain) ? "; domain=" + domain : "") +
    ((secure) ? "; secure" : "");

}
/*******************End Code Cookie Library *******************/    

                    
      

/* ---------------------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 * 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 -------------------------*/
function changeLogos(flowtype) {
	switch (flowtype){
		case 'F':
			jQuery("#midPanelLogoImage").attr("src","/portals/0/images/google-logo1.gif");
			jQuery('#mid-panel-title1').text('Compare hundreds of cheap flights with just a click & save up to 65%');
			break;
		case 'H':
			jQuery("#midPanelLogoImage").attr("src","/portals/0/images/google-logo2.gif");
			jQuery('#mid-panel-title1').text('Compare hundreds of cheap hotels with just a click & save up to 65%');
			break;
		case 'C':
			jQuery("#midPanelLogoImage").attr("src","/portals/0/images/google-logo3.gif");
			jQuery('#mid-panel-title1').text('Compare hundreds of rental car deals with a click & save up to 65%');
			break;
		case 'CR':
			jQuery("#midPanelLogoImage").attr("src","/portals/0/images/google-logo4.gif");
			jQuery('#mid-panel-title1').text('Compare hundreds of cruise deals with a click & save up to 85%');
			break;	
		case 'VS':
			jQuery("#midPanelLogoImage").attr("src","/portals/0/images/google-logo5.gif");
			jQuery('#mid-panel-title1').text('Compare hundreds of package deals with a click & save up to 65%');
			break;
			}
}

function InitPage()
{     
        var divName = GetDivName(jQuery.cookie("lstTab"));
        if (divName != 'undefined' && jQuery('#' + divName).length > 0 && ((!window.fixTab) || fixTab == false))
        {
            showTab=jQuery.cookie("lstTab");
            LoadRTab(showTab);
        }
}

