var gStartDate  		= new Date();
var gDaysArr    		= new Array();
var gDepTimeArr   	= new Array();
var gArrTimeArr   	= new Array();
var gTimeRouteArr   	= new Array();
var gRouteGroup   	= new Object();
var gMaxDay 	     	= new Object();
var gMaxMth	      	= new Object();
var gMaxYer    	  	= new Object();
var gTimeRoute       = new Object();
var gVehicleClick 	= false;
var gOutTimeClick 	= false;
var gRetTimeClick 	= false;
var gMaxPax       	= 9;	
var gDayMillis    	= 86400000;
var gOpacity			= 0.50;
var gLng             = $('#Language').val();
var lcluetipDefaultsL= {
								attribute: 'id',
								positionBy: 'auto', //'auto', 'mouse', 'bottomTop', 'fixed'
								splitTitle: '|',
								waitImage: false,
								leftOffset: 140,
								topOffset:0
								};
var lcluetipDefaultsM= {
								attribute: 'id',
								positionBy: 'auto', //'auto', 'mouse', 'bottomTop', 'fixed'
								splitTitle: '|',
								waitImage: false,
								leftOffset: 90,
								topOffset:0
								};
var lcluetipDefaultsR= {
								attribute: 'id',
								positionBy: 'auto', //'auto', 'mouse', 'bottomTop', 'fixed'
								splitTitle: '|',
								waitImage: false,
								leftOffset: 15,
								topOffset:0
								};

gRouteGroup.Out 	= new Array("-");
gRouteGroup.Ret	= new Array("-", "$");
gTimeRoute.Out    = new Array();
gTimeRoute.Ret    = new Array();
gStartDate.setYear(STARTYER);
gStartDate.setMonth(STARTMTH -1);
gStartDate.setDate(STARTDAY);
//******************************************************
$(document).ready(function(){   
 	$("#OutCal").datepicker({
		firstDay: 1,
		minDate: new Date(),
		maxDate: new Date(2020, 12 - 1, 31), 
		buttonImage: "images/Booking/calendar.gif", 
		buttonImageOnly: true,
		showOn: "both",
		numberOfMonths: 2,
		monthNames: LongMonths[gLng],
		beforeShow: readOutLinked,
		onSelect: updateOutLinked,
		beforeShowDay: checkDateOut,
		navigationAsDateFormat: true,
		dayNamesMin: Days[gLng],
		currentText: ' ',
		closeText: 'X',
		mandatory: true,
		duration: 'fast',
		nextText: ">",
		prevText: "<",
		hideIfNoPrevNext: true,
		buttonText: "",
		changeMonth: false,
		changeYear: false,
		changeFirstDay: false
	});

	$("#RetCal").datepicker({ 
		firstDay: 1,
		minDate: new Date(),
		maxDate: new Date(2020, 12 - 1, 31), 
		buttonImage: "images/Booking/calendar.gif", 
		showOn: "both",
		buttonImageOnly: true,
		numberOfMonths: 2,
		monthNames: LongMonths[gLng],
		beforeShow: readRetLinked,
		navigationAsDateFormat: true,
		onSelect: updateRetLinked,
		beforeShowDay: checkDateRet,
		dayNamesMin: Days[gLng],
		currentText: ' ',
		closeText: 'X',
		mandatory: true,
		duration: 'fast',
		nextText: ">",
		prevText: "<",
		hideIfNoPrevNext: true,
		buttonText: "",
		changeMonth: false,
		changeYear: false,
		changeFirstDay: false
	});      

	if (!$.browser.msie) {
		$('#Vehicle').removeClass('VehDDLIE')
		$('#Vehicle').addClass('VehDDL')
	}
	BuildDefaultText();
	BuildRouteDDLs("OutRoute");
	BuildPaxDDL('Adult');
	BuildPaxDDL('Child');
	BuildPaxDDL('Infant');
	BuildVehicles();

	$("#Return").click(ShowOutAndReturn);
	$("#OutRoute").change(SetOutMonths);
	$("#OutMonth").change(SetOutDays);
	$("#OutDay").change(SetOutTimes);
	$("#RetRoute").change(SetRetMonths);
	$("#RetMonth").change(SetRetDays);
	$("#RetDay").change(SetRetTimes);
	$("#Vehicle").change(setVehDims);

	$("#OutAdult").change(function() {
		if (!$("#RetAdult").attr('disabled') != false) $("#RetAdult").val($(this).val());
		ShowChildren("Out");
		if ($('#RetRoute').attr('selectedIndex') > 1) {
			ShowChildren("Ret");
		}
	});
	$("#RetAdult").change(function() {
		ShowChildren("Ret");
	});
	$("#OutChild").change(function() {
		if (!$("#RetChild").attr('disabled') != false) $("#RetChild").val($(this).val());
	});
	$("#OutInfant").change(function() {
		if (!$("#RetInfant").attr('disabled') != false) $("#RetInfant").val($(this).val());
	});
   $(".GreyText").focus(function() {
        if ($(this).val() == $(this)[0].title) {
            $(this).removeClass("GreyText");
            $(this).val("");
        }
   });
    
   $(".GreyText").blur(function() {
        if ($(this).val() == "") {
            $(this).addClass("GreyText");
            $(this).val($(this)[0].title);
        }
   });
    
	$(".GreyText").blur();  
	$('#LowFares').attr('title', Tooltips[gLng].LowFares);
	$('#PromoCode').val(Page[gLng].Promotion);
	
	CreateTooltips();
	$("#LowFaresTT").cluetip(lcluetipDefaultsR);
	/*
	$("#PromoCodeTT").cluetip(lcluetipDefaultsR);
	$("#OutRouteTT").cluetip(lcluetipDefaultsR);
	$("#OutMonthTT").cluetip(lcluetipDefaultsL);
	$("#OutDayTT").cluetip(lcluetipDefaultsM);
	$("#OutTimeTT").cluetip(lcluetipDefaultsR);
	$("#OutCalTT").cluetip(lcluetipDefaultsL);
	$("#RetRouteTT").cluetip(lcluetipDefaultsR);
	$("#RetMonthTT").cluetip(lcluetipDefaultsL);
	$("#RetDayTT").cluetip(lcluetipDefaultsM);
	$("#RetTimeTT").cluetip(lcluetipDefaultsR);
	$("#RetCalTT").cluetip(lcluetipDefaultsL);
	$("#AdultTT").cluetip(lcluetipDefaultsL);
	$("#ChildTT").cluetip(lcluetipDefaultsM);
	$("#InfantTT").cluetip(lcluetipDefaultsR);
	$("#VehicleTT").cluetip(lcluetipDefaultsR);
	$("#GetQuote").cluetip(lcluetipDefaultsR);
	$("#ChangeBooking").cluetip(lcluetipDefaultsL);
	$("#AdvancedSearch").cluetip(lcluetipDefaultsR);
	*/

	ShowTimes("Out", false);
	ShowRoute("Ret", false);
	ShowTimes("Ret", false);
	HidePax("Out",   false);
	HidePax("Ret",   false);
	ShowVeh(false);
	$("#Return").attr("checked", true);

	if ($("#DefaultPromoCode").val() != "") 
		$("#PromoCode").val($("#DefaultPromoCode").val());

	init_Booking_Map();
	init_Vehicle_Popup();
});
//******************************************************
function CreateTooltips() {
	$('#LowFaresTT').attr(		'title', Tooltips[gLng].LowFares);
	/*
	$('#PromoCodeTT').attr(		'title', Tooltips[gLng].PromoCode);
	$('#OutCalTT').attr(			'title', Tooltips[gLng].CalTooltip);
	$('#RetCalTT').attr(			'title', Tooltips[gLng].CalTooltip);
	$('#VehicleTT').attr(		'title', Tooltips[gLng].VehicleTooltip);
	$('#GetQuote').attr(			'title', Tooltips[gLng].GetQuote);
	$('#ChangeBooking').attr(	'title', Tooltips[gLng].ChangeBooking);
	$('#AdvancedSearch').attr(	'title', Tooltips[gLng].AdvancedSearch);
	$('#AdultTT').attr(			'title', Tooltips[gLng].Adult);
	$('#ChildTT').attr(			'title', Tooltips[gLng].Child);
	$('#InfantTT').attr(			'title', Tooltips[gLng].Infant);
	$('#OutRouteTT').attr(		'title', Tooltips[gLng].OutRoute);
	$('#OutMonthTT').attr(		'title', Tooltips[gLng].OutMonth);
	$('#OutDayTT').attr(			'title', Tooltips[gLng].OutDay);
	$('#OutTimeTT').attr(		'title', Tooltips[gLng].OutTime);
	$('#RetRouteTT').attr(		'title', Tooltips[gLng].RetRoute);
	$('#RetMonthTT').attr(		'title', Tooltips[gLng].RetMonth);
	$('#RetDayTT').attr(			'title', Tooltips[gLng].RetDay);
	$('#RetTimeTT').attr(		'title', Tooltips[gLng].RetTime);
	*/

}
//******************************************************
function BuildDefaultText() {
	$("#OutRoute").addOption('-', Page[gLng].ChooseOut, false);
	$("#RetRoute").addOption('-', Page[gLng].ChooseRet, false);
	$("#OutMonth").addOption('-', Page[gLng].Months, false);
	$("#OutDay").addOption('-',	Page[gLng].Days, false);
	$("#OutTime").addOption('-',	Page[gLng].Times, false);
	$("#RetMonth").addOption('-', Page[gLng].Months, false);
	$("#RetDay").addOption('-',	Page[gLng].Days, false);
	$("#RetTime").addOption('-',	Page[gLng].Times, false);

	$('#OneStepText').html(Page[gLng].OneStepText);
	$('#ReturnText').html(Page[gLng].ReturnText);
	$('#OutwardRouteText').html(Page[gLng].OutwardRoute);
	$('#ReturnRouteText').html(Page[gLng].ReturnRoute);
	$('#OutMonthText').html(Page[gLng].Month);
	$('#OutDateText').html(Page[gLng].Date);
	$('#OutTimeText').html(Page[gLng].Time);
	$('#RetMonthText').html(Page[gLng].Month);
	$('#RetDateText').html(Page[gLng].Date);
	$('#RetTimeText').html(Page[gLng].Time);
	$('#PaxText').html(Page[gLng].PaxText);
	$('#PaxOutText').html(Page[gLng].PaxOut);
	$('#PaxRetText').html(Page[gLng].PaxRet);
	$('#AdultText').html(Page[gLng].Adult);
	$('#ChildText').html(Page[gLng].Child);
	$('#InfantText').html(Page[gLng].Infant);
	$('#VehicleText').html(Page[gLng].Vehicle);
	$('#VehTypeText').html(Page[gLng].VehType);
	$('#BookNowText').html(Page[gLng].BookNow);
	$('#ChangeBookingText').html(Page[gLng].ChangeBooking);
	$('#MoreOptionsText').html(Page[gLng].MoreOptions);
	$('#PromoText').html(Page[gLng].Promotion);
	$('#VehDimsText').html(Page[gLng].VehDims);
	$('#VehQtyText').html(Page[gLng].VehQuantity);
	$('#ManageBooking').html(Page[gLng].ManageBooking);
	$('#TowingText').html(Page[gLng].Towing);
	$('#TowingYesText').html(Page[gLng].TowingYes);
	$('#TowingNoText').html(Page[gLng].TowingNo);
}
//******************************************************
function SetOutMonths() 		{SetMonths("Out");SetDays("Out");SetTimes("Out");SetRetRoute();SetRetMonths();};
function SetOutDays()   		{SetDays("Out");SetTimes("Out");CheckRetDate();};
function SetOutTimes()  		{SetTimes("Out");CheckRetDate();};
function SetRetMonths() 		{SetMonths("Ret");SetDays("Ret");SetTimes("Ret");CheckRetDate();};
function SetRetDays()   		{SetDays("Ret");SetTimes("Ret");CheckRetDate();};
function SetRetTimes()  		{CheckRetDate();SetTimes("Ret");};
//******************************************************
function readOutLinked()		{readLinked("Out");}
function readRetLinked()		{readLinked("Ret");}
function updateOutLinked(date){return updateLinked(date, "Out");}
function updateRetLinked(date){return updateLinked(date, "Ret");}
function checkDateOut(date)	{return CheckDate(date, "Out");}
function checkDateRet(date)	{return CheckDate(date, "Ret");}
//******************************************************
function ShowOutAndReturn() {
	if ($("#OutRoute").selectedValues().toString() != '-') {
		ShowRoute("Ret", true);
		if ($("#RetRoute").selectedValues().toString() != '-') {
			ShowTimes("Ret", true);
		}
		$('#RetRoute').val('-');
		ShowPax();
	}
}
//******************************************************
function ShowOutOnly() {
	if ($("#RetRoute").attr("selectedIndex") == 1) {
		ShowTimes("Ret", false);
		ShowPax();
	}
}
//******************************************************
function ShowRoute(pDir, pShow) {
var lOpacity = 1;

	if (!pShow) lOpacity = gOpacity;

	$("#" + pDir + "Route").fadeTo('normal', lOpacity);
	$("#" + pDir + "Route").attr('disabled', !pShow);
}
//******************************************************
function ShowTimes(pDir, pShow) {
var lOpacity = 1;

	if (!pShow) lOpacity = gOpacity;

	if (pShow)
		$("#" + pDir + "Cal").datepicker("enable");
	else
		$("#" + pDir + "Cal").datepicker("disable");

	$("#" + pDir + "Day").fadeTo('normal', lOpacity);
	$("#" + pDir + "Month").fadeTo('normal', lOpacity);
	$("#" + pDir + "Time").fadeTo('normal', lOpacity);

	$("#" + pDir + "Day").attr('disabled', !pShow);
	$("#" + pDir + "Month").attr('disabled', !pShow);
	$("#" + pDir + "Time").attr('disabled', !pShow);
}
//******************************************************
function HidePax(pDir) {
	$("#" + pDir + "Adult").fadeTo('normal', gOpacity);
	$("#" + pDir + "Child").fadeTo('normal', gOpacity);
	$("#" + pDir + "Infant").fadeTo('normal', gOpacity);
	$("#" + pDir + "Adult").attr('disabled', true);
	$("#" + pDir + "Child").attr('disabled', true);
	$("#" + pDir + "Infant").attr('disabled', true);
}
//******************************************************
function ShowPax() {
	if ($("#RetRoute").attr('selectedIndex') > 0) {
		$("#OutAdult").fadeTo('normal', 1);
		$("#OutAdult").attr('disabled', false);

		if ($("#RetRoute").attr('selectedIndex') > 1) {
			$("#RetAdult").fadeTo('normal', 1);
			$("#RetAdult").attr('disabled', false);
		} else {
			$("#RetAdult").fadeTo('normal', gOpacity);
			$("#RetAdult").attr('disabled', true);
		}
	} else {
		$("#OutAdult").fadeTo('normal', gOpacity);
		$("#OutAdult").attr('disabled', true);
	}
}
//******************************************************
function ShowChildren(pDir) {
	if ($("#" + pDir + "Adult").val() > 0) {
		$("#" + pDir + "Child").fadeTo('normal', 1);
		$("#" + pDir + "Child").attr('disabled', false);
		$("#" + pDir + "Infant").fadeTo('normal', 1);
		$("#" + pDir + "Infant").attr('disabled', false);
		ShowVeh(true);
	} else {
		$("#" + pDir + "Child").fadeTo('normal', gOpacity);
		$("#" + pDir + "Child").attr('disabled', true);
		$("#" + pDir + "Infant").fadeTo('normal', gOpacity);
		$("#" + pDir + "Infant").attr('disabled', true);
		ShowVeh(false);
		hideVehDims();
	}
}
//******************************************************
function ShowVeh(pShow) {
var lOpacity = 1;
	if (!pShow) {
		lOpacity = gOpacity;
		$('#open-vehicles').hide();
	} else {
		$('#open-vehicles').show();
	}
	$("#Vehicle").fadeTo('normal', lOpacity);
	$("#Vehicle").attr('disabled', !pShow);
	$('#VehTextInfo').fadeTo('normal',lOpacity);
}
//******************************************************
function BuildVehicles() {
	$("#Vehicle").removeOption(/./);

	for (var i in VehType[gLng]) {
		 $("#Vehicle").addOption(VehType[gLng][i][0], VehType[gLng][i][1], false);
	}

	hideVehDims();
	vehQty();
}
//******************************************************
function vehQty() {
	$("#VehQty").removeOption(/./);
	if (VehType[gLng][$('#Vehicle').attr('selectedIndex')][2] > 1) {
		$('#VehQty').fadeTo('normal',1);
		$('#VehQty').attr('disabled',false);
		for (i = 0;i <= VehType[gLng][$('#Vehicle').attr('selectedIndex')][2]; i++) $("#VehQty").addOption(i,i, false);
	} else {
		$('#VehQty').fadeTo('normal',gOpacity);
		$('#VehQty').attr('disabled',true);
		$("#VehQty").addOption(1,1, false);
		$('#VehQty').val(0);
	}
}
//******************************************************
function hideVehDims() {
	$("#VehDims").removeOption(/./);
	$("#VehDims").addOption('-', Page[gLng].PleaseSelect, false);
	$('#VehDims').fadeTo('normal',gOpacity);
	$('#VehDims').attr('disabled',true);
	$('#TowingYes').attr('disabled',true);
	$('#TowingNo').attr('disabled',true);
}
//******************************************************
function setVehDims() {
var lAdded		= false;
	$("#VehDims").removeOption(/./);
	$("#VehDims").addOption('-', Page[gLng].PleaseSelect, false);

	for (var i in VehDims[gLng]) {
		if (VehDims[gLng][i][0] == $('#Vehicle').val()) {
			lNewOpt			= document.createElement('option');
			lNewOpt.value	= VehDims[gLng][i][2];
			lNewOpt.appendChild(document.createTextNode(VehDims[gLng][i][1]));
			$("#VehDims").append(lNewOpt);
			lAdded = true;
		}
	}

	if (!lAdded) {
		hideVehDims();
	} else {
		$('#VehDims').fadeTo('normal',1);
		$('#VehDims').attr('disabled',false);
		$('#TowingYes').attr('disabled',false);
		$('#TowingNo').attr('disabled',false);
	}
	vehQty();
}
//******************************************************
function BuildPaxDDL(pPaxType) {
	for (lPaxNo=0;lPaxNo <= gMaxPax;lPaxNo++) {
		 $("#Out" + pPaxType).addOption(lPaxNo, lPaxNo, false);
		 $("#Ret" + pPaxType).addOption(lPaxNo, lPaxNo, false);
	}
}
//******************************************************
function BuildRouteDDLs(pPortFldId) {
var lGeoRouteGrps= new Array();
var lRGNames     = Routes[gLng];
var lRouteGroups = new Array();
var lRouteArray  = new Array();
var lDupPorts    = new Array();
var lRouteArr    = new Array();
var lRouteOptions= new Array();
var lAdded       = false;
var lGeoRG       = '';
var lRouteIdx    = 0;
var lRouteList   = '';
var lx           = 0;
var lSelectHtml  = '<option value="-">' + Page[gLng].ChooseOut + '</option>';

	for (x in lRGNames) {
		lRouteArray[lRGNames[x][0]] = new Array();
	}
	for (lOutIdx in PORTS) {
		lGeoRouteGrps= GEOROUTEGROUPS[lOutIdx];
		lRouteGroups = ROUTEGROUPS[lOutIdx];
		lAdded       = false;

		for (lArrIdx in PORTDESTS[lOutIdx]) {
			if (CheckRouteGroup(PORTS[lOutIdx][1], lDupPorts) < 0) {
				lRouteArray[lGeoRouteGrps[lArrIdx]].push(	[
																		[PORTS[lOutIdx][0] + '_' + PORTDESTS[lOutIdx][lArrIdx]],
																		[PORTS[lOutIdx][1] + ' - ' + GetPortName(PORTDESTS[lOutIdx][lArrIdx])],
																		lRouteGroups[lArrIdx]
																		]);

				lAdded = true;
			}
		}

		if (lAdded) {
			for (x in lRouteGroups) {
				if (CheckRouteGroup(lRouteGroups[x], lDupPorts) < 0) {
					lDupPorts.push(PORTS[lOutIdx][1]);
				}
			}
		}
	}

	for (lGeoRG in lRouteArray) {
		for (lRouteIdx in lRGNames) {
			if (lRGNames[lRouteIdx][0] == lGeoRG) {
				$("#" + pPortFldId).addOption(lRGNames[lRouteIdx][0],lRGNames[lRouteIdx][1], false);
				if (lSelectHtml != '') lSelectHtml += '</optgroup>';
				lSelectHtml += '<optgroup label="' + lRGNames[lRouteIdx][1] + '">';
			}
		}


		for (lRouteIdx in lRouteArray[lGeoRG]) {
			gRouteGroup["Out"].push(lRouteArray[lGeoRG][lRouteIdx][2]);
			lSelectHtml += '<option value="' + lRouteArray[lGeoRG][lRouteIdx][0] + '">' + lRouteArray[lGeoRG][lRouteIdx][1] + '</option>';
		}
	}
	lSelectHtml += '</optgroup>';
	$("#" + pPortFldId).html(lSelectHtml);
}
//******************************************************
function CheckRouteGroup(pRouteGroup, pRouteGroupArr) {
var lRG = 0;
	for (lRG in pRouteGroupArr) if (pRouteGroupArr[lRG] == pRouteGroup) return lRG;
	return -1;
}
//******************************************************
function GetPortName(pPortId) {
	for (lIdx in PORTS) {
		if (PORTS[lIdx][0] == pPortId) return PORTS[lIdx][1];
	}
	return pPortId;
}
//******************************************************
function SetRetRoute() {
var lOutRoute  = $("#OutRoute").selectedValues();
var lDepPort   = lOutRoute.toString().split('_')[0];
var lArrPort   = lOutRoute.toString().split('_')[1];
var lRoute     = lArrPort + '_' + lDepPort;
var lDupRGS      = new Array();
var lRouteGroup= '';
var lGeoRG     = '';
	gRouteGroup["Ret"] = ["-"];
	$("#RetRoute").removeOption(/./);
	$("#RetRoute").addOption('-', Messages[gLng].ChooseRet, true);
	$("#RetRoute").addOption('$', Messages[gLng].SingleOnly, false);

	for (lRetIdx in PORTS) {
		lAdded       = false;

		if (PORTS[lRetIdx][0] == lArrPort) {
			for (lArrIdx in PORTDESTS[lRetIdx]) {
				if (PORTS[lRetIdx][0] + '_' + PORTDESTS[lRetIdx][lArrIdx] == lRoute ) {
					$("#RetRoute").addOption(PORTS[lRetIdx][0] + '_' + PORTDESTS[lRetIdx][lArrIdx], PORTS[lRetIdx][1] + ' - ' + GetPortName(PORTDESTS[lRetIdx][lArrIdx]), false);
					lPortName   = PORTS[lRetIdx][1];
					lRouteGroup = ROUTEGROUPS[lRetIdx][lArrIdx];
					lGeoRG      = GEOROUTEGROUPS[lRetIdx][lArrIdx];
					gRouteGroup["Ret"].push(ROUTEGROUPS[lRetIdx][lArrIdx]);
				}
			}

			for (lArrIdx in PORTDESTS[lRetIdx]) {
				if (PORTS[lRetIdx][0] + '_' + PORTDESTS[lRetIdx][lArrIdx] != lRoute && lRouteGroup == ROUTEGROUPS[lRetIdx][lArrIdx]) {
					$("#RetRoute").addOption(PORTS[lRetIdx][0] + '_' + PORTDESTS[lRetIdx][lArrIdx], PORTS[lRetIdx][1] + ' - ' + GetPortName(PORTDESTS[lRetIdx][lArrIdx]), false);
					gRouteGroup["Ret"].push(ROUTEGROUPS[lRetIdx][lArrIdx]);
				}
			}
		}
	}
	// See if there are any GEO Routegroups that have similar routes.

	for (lRetIdx in PORTS) {
		if (PORTS[lRetIdx][0] != lArrPort) {
			for (lArrIdx in PORTDESTS[lRetIdx]) {
				if (GEOROUTEGROUPS[lRetIdx][lArrIdx] == lGeoRG && PORTS[lRetIdx][1]!= lPortName) {
					if (CheckRouteGroup(ROUTEGROUPS[lRetIdx][lArrIdx], lDupRGS) < 0) {
						$("#RetRoute").addOption(PORTS[lRetIdx][0] + '_' + PORTDESTS[lRetIdx][lArrIdx], PORTS[lRetIdx][1] + ' - ' + GetPortName(PORTDESTS[lRetIdx][lArrIdx]), false);
						lDupRGS.push(ROUTEGROUPS[lRetIdx][lArrIdx]);
						gRouteGroup["Ret"].push(ROUTEGROUPS[lRetIdx][lArrIdx]);
					}
				}
			}
		}
	}
	gRouteGroup["Ret"].push("$");
}
//******************************************************
function CheckRetDate() {
	if ($("#RetDay").val() == '-' || $("#RetMonth").val() == '-') return;
var lOutDay 	= $("#OutDay").val() *1;
var lOutDate	= new Date($("#OutMonth").val().split("_")[2], $("#OutMonth").val().split("_")[1], 1)
var lRetDate	= new Date($("#RetMonth").val().split("_")[2], $("#RetMonth").val().split("_")[1], 1)

	if (lRetDate.getTime() < lOutDate.getTime()) {
		$('#RetMonth').val('Ret_' + $("#OutMonth").val().split("_")[1] + '_' + $("#OutMonth").val().split("_")[2]);
		SetDays("Ret");
		SetRetDay(lOutDay);
		SetTimes("Ret");
	}

	lRetDay 	= $("#RetDay").val() * 1;

	if (lOutDate.getMonth() == lRetDate.getMonth() && lOutDate.getFullYear() == lRetDate.getFullYear()) {
		if (lRetDay < lOutDay) {
			SetRetDay(lOutDay);
			SetTimes("Ret");
		}
	}
}
//******************************************************
function SetRetDay(pOutDay) {
	for (lDay=0; lDay < document.getElementById('RetDay').options.length; lDay++) {
		if (document.getElementById('RetDay').options[lDay].value >= pOutDay) {
			$('#RetDay').attr('selectedIndex', lDay);
			break;
		}
	}
}
//******************************************************
function SetMonths(pDir) {
var lTimeTable = new Array();
var lDate      = new Date();
var lDateMilli = gStartDate.getTime();
var lToday     = new Date();
var lDayStr    = '';
var lRouteGroup= '';
var lRoute  	= $("#" + pDir + "Route").selectedValues();
var lDepPort   = lRoute.toString().split('_')[0];
var lArrPort   = lRoute.toString().split('_')[1];
var lRealRoute = '';
var lLastDate  = new Date();

	lToday.setHours(24);
	lToday.setMinutes(59);

	if (pDir == "Out") {
		gDaysArr 		= new Array();
		gDepTimeArr		= new Array();
		gArrTimeArr		= new Array();
		gTimeRoute.Out = new Array();
		gTimeRoute.Ret = new Array();
		lRouteGroup = gRouteGroup[pDir][$('#' + pDir + 'Route').attr('selectedIndex')];
	} else {
		lRouteGroup = gRouteGroup[pDir][$('#' + pDir + 'Route').attr('selectedIndex') - 1];
	}

	gMaxYer[pDir] = "2020";
	gMaxMth[pDir] = "11";
	gMaxDay[pDir] = "31";

	$("#" + pDir + "Month").removeOption(/./);


	if (lRoute == '$') {
		$('#OutRoute').focus();
		$("#RetMonth").addOption("-", Messages[gLng].Months, false);
		ShowOutOnly()
		return;
	}

	if (lRoute == '$' || lRoute == '-' || lRouteGroup == '-' || lRouteGroup == undefined)  {
		$("#" + pDir + "Month").addOption("-", Messages[gLng].Months, false);
		if (pDir == "Out") {
			ShowTimes("Out", false);
			ShowRoute("Ret", false);
		}
		ShowTimes("Ret", false);
		ShowPax();
		return;
	};

	for (x in ROUTEGROUPS) {
		for (y in ROUTEGROUPS[x]) {
			if (ROUTEGROUPS[x][y] == lRouteGroup &&
				GetPortName(lDepPort) == PORTS[x][1] && 
				GetPortName(lArrPort) == GetPortName(PORTDESTS[x][y])) {

				lRealRoute = PORTS[x][0] + '_' + PORTDESTS[x][y];
				lTimeTable = TT[PORTS[x][0] + PORTDESTS[x][y]];
				lDateMilli = gStartDate.getTime();

				for (lDayNum = 0; lDayNum < lTimeTable.length; lDayNum += 2) {
					if (lTimeTable.substr(lDayNum, 2) != "  ") {
						lDate.setTime(lDateMilli);
						if (lLastDate.getTime() < lDate.getTime()) lLastDate.setTime(lDate.getTime());

						if (lDate.getTime() >= (lToday.getTime() - gDayMillis)) {
							lIdxRef = pDir + "_" + lDate.getMonth() + "_" + lDate.getFullYear();

							if (AddMonth(pDir, lDate.getMonth(), lDate.getFullYear())) {
								gDaysArr[lIdxRef]    = new Array();
								gDepTimeArr[lIdxRef] = new Array();
								gArrTimeArr[lIdxRef] = new Array();
							}

							gDaysArr[lIdxRef].push(lDate.getDate());

							if (!gDepTimeArr[lIdxRef]['T' + lDate.getDate()]) {
								gDepTimeArr[lIdxRef].push('T' + lDate.getDate());
								gArrTimeArr[lIdxRef].push('T' + lDate.getDate());
								gDepTimeArr[lIdxRef]['T' + lDate.getDate()] = new Array();
								gArrTimeArr[lIdxRef]['T' + lDate.getDate()] = new Array();
							}

							for (lTimeIdx = 0;lTimeIdx < TM[lTimeTable.substr(lDayNum, 2)].length; lTimeIdx++) {
								gDepTimeArr[lIdxRef]['T' + lDate.getDate()].push(TM[lTimeTable.substr(lDayNum, 2)][lTimeIdx][0] + '|' + lRealRoute);
								gArrTimeArr[lIdxRef]['T' + lDate.getDate()].push(TM[lTimeTable.substr(lDayNum, 2)][lTimeIdx][1] + '|' + lRealRoute);
							}
						}
					}
					lDateMilli += gDayMillis;
				}
			}
		}
	}
	if (document.getElementById(pDir + 'Month').options.length == 0){
		$("#" + pDir + "Month").addOption("-", "Months", false);
		if (pDir == 'Out') {
			ShowTimes("Out", false);
			ShowRoute("Ret", false);
		}
		ShowTimes("Ret", false);
		alert(Messages[gLng].NoSailings);
	} else {
		ShowRoute("Out", true);
		ShowTimes("Out", true);
		ShowRoute("Ret", true);

		if ($("#RetRoute").attr("selectedIndex") > 1) {
			ShowTimes("Ret", true);
		}
	}
	ShowPax();
	$("#" + pDir + "Cal").datepicker("change", {maxDate: lLastDate});
}
//******************************************************
function AddMonth(pDir, pMonth, pYear) {
	if ($("#" + pDir + "Month").containsOption(pDir + "_" + pMonth + "_" + pYear)) {
		return false;
	} else {
		$("#" + pDir + "Month").addOption(pDir + "_" + pMonth + "_" + pYear, Months[gLng][pMonth] + ' ' + pYear, false);
		return true;
	}
}
//******************************************************
function SetDays(pDir) {
var lMonth  = $("#" + pDir + "Month").selectedValues().toString();

	$("#" + pDir + "Day").removeOption(/./);

	if (gDaysArr[lMonth] == undefined)  {
		$("#" + pDir + "Day").addOption("-", "Days", true);
		return;
	};

	gDaysArr[lMonth].sort( function(a,b){return a-b;});

	for (i=0; i < gDaysArr[lMonth].length; i++) {
		$("#" + pDir + "Day").addOption(gDaysArr[lMonth][i], gDaysArr[lMonth][i], false);
	}
}
//******************************************************
function SetTimes(pDir) {
var lMonth  = $("#" + pDir + "Month").selectedValues().toString();
var lDay    = $("#" + pDir + "Day").selectedValues();
var lTime   = '';
var lDate   = new Date();
	$("#" + pDir + "Time").removeOption(/./);

	if (gDaysArr[lMonth] == undefined)  {
		$("#" + pDir + "Time").addOption("-", "Time", true);
		return;
	};

	gDepTimeArr[lMonth]['T' + lDay].sort();
	gArrTimeArr[lMonth]['T' + lDay].sort();
	gTimeRoute[pDir] = new Array();

	lTime   = gDepTimeArr[lMonth]['T' + lDay][0].split('|')[0];

	lDate.setHours(lTime.split(":")[0], lTime.split(":")[1]);
	lDate.setTime(lDate.getTime() + (1 * 60 * 1000));

	$("#" + pDir + "Time").addOptionDup(gDepTimeArr[lMonth]['T' + lDay][0], Page[gLng].AnyTime, false);
	gTimeRoute[pDir].push(gDepTimeArr[lMonth]['T' + lDay][0].split('|')[1]);

	for (lTimeIdx in gDepTimeArr[lMonth]['T' + lDay]) {
		lTime = gDepTimeArr[lMonth]['T' + lDay][lTimeIdx].split('|')[0];
		$("#" + pDir + "Time").addOptionDup(gDepTimeArr[lMonth]['T' + lDay][lTimeIdx], lTime, false);
		gTimeRoute[pDir].push(gDepTimeArr[lMonth]['T' + lDay][lTimeIdx].split('|')[1]);
	}
}
//******************************************************
function CheckDate(pDate, pDir) {
var lMonth = pDir + "_" + pDate.getMonth() + "_" + pDate.getFullYear();
	if (gDaysArr[lMonth]) {
		for (i in gDaysArr[lMonth]) {
			if (gDaysArr[lMonth][i] == pDate.getDate()) {
				return [1, ''];
			}
		}
	}
	return [0, ''];
}
//******************************************************
function readLinked(pDir) {
var lDay 		= $("#" + pDir + "Day").val();
var lMth			= $("#" + pDir + "Month").val().split("_")[1];
var lYer 		= $("#" + pDir + "Month").val().split("_")[2];

	lMth = (lMth * 1) + 1;
	$("#" + pDir + "Cal").val(lMth + "/" + lDay + "/" + lYer);

	if (pDir == "Ret") {
		lDay 	= $("#OutDay").val();
		lMth	= $("#OutMonth").val().split("_")[1];
		lYer 	= $("#OutMonth").val().split("_")[2];
		$("#" + pDir + "Cal").datepicker("change", {minDate: new Date(lYer, lMth, lDay)});
	}
}
//******************************************************
function updateLinked(pDate, pDir) {
var lDay = pDate.substring(3, 5);
var lMth = pDate.substring(0, 2);
var lYer = pDate.substring(6, 10);
	lMth = (lMth * 1) - 1;
	$("#" + pDir + "Month").val(pDir + '_' + lMth + "_" + lYer); 
	SetDays(pDir);
	$("#" + pDir + "Day").val(lDay * 1);
	SetTimes(pDir);
	CheckRetDate();
	return {};
}
//******************************************************
function quickQuoteValid() {
var lOutDate	= new Date($("#OutMonth").val().split("_")[2], $("#OutMonth").val().split("_")[1], $('#OutDay').val())
var lRetDate	= new Date($("#RetMonth").val().split("_")[2], $("#RetMonth").val().split("_")[1], $('#RetDay').val())
var lMessage		= '';
var lTotalPaxOut	= 0;
var lTotalPaxRet	= 0;
	if ($('#OutRoute').val() == '-') 		lMessage += Messages[gLng].NoOutRoute;
	if ($('#OutDay').val() == '-')			lMessage += Messages[gLng].NoOutDay;
	if ($('#OutMonth').val() == '-')			lMessage += Messages[gLng].NoOutMonth;

	if ($("#RetRoute").attr("selectedIndex") == 0) {
		lMessage += Messages[gLng].NoRetRoute;
		if ($('#RetDay').val() == '-')		lMessage += Messages[gLng].NoRetDay;
		if ($('#RetMonth').val() == '-')		lMessage += Messages[gLng].NoRetMonth;
	}

	if ($('#OutAdult').val() == 0)			lMessage += Messages[gLng].NoAdult;
	if ($('#Vehicle').val() == 'freight')	lMessage += Messages[gLng].Freight;
	if ($('#Vehicle').attr('selectedIndex') == 0 || 
		($('#VehDims').attr('disabled') == false && $('#VehDims').attr('selectedIndex') == 0)){
		lMessage += Messages[gLng].NoVehicle;
	}

	if ($('#VehQty').attr('disabled') == false && $('#VehQty').val() == 0){
		lMessage += Messages[gLng].VehicleQuantity;
	}

	lTotalPaxOut += ($('#OutAdult').val() * 1) + ($('#OutChild').val() * 1) + ($('#OutInfant').val() * 1);
	lTotalPaxRet += ($('#RetAdult').val() * 1) + ($('#RetChild').val() * 1) + ($('#RetInfant').val() * 1);

	if (lTotalPaxOut > 9) lMessage += Messages[gLng].MaxPaxOut;
	if (lTotalPaxRet > 9) lMessage += Messages[gLng].MaxPaxRet;

	if (lMessage != '') {
		alert(lMessage)
		return false;
	}
	if (lRetDate.getTime() < lOutDate.getTime()) {
		alert(Messages[gLng].BadDate);
		return false;
	}
	return true;
}
//******************************************************
function SubmitQuote() {
	if (quickQuoteValid() == false) return;
	$('#VehName').val($('#Vehicle :selected').text());			
	$('#VehDimName').val($('#VehDims :selected').text());			

	if ($('#VehDims').attr('selectedIndex') > 0) {
		$('#VehCtgId').val($('#VehDims').val());
		$('#VehDimIdx').val($('#VehDims').attr('selectedIndex'));
	} else {
		$('#VehCtgId').val('foot');
	}

	$('#OutRealRoute').val(gTimeRoute.Out[$('#OutTime').attr('selectedIndex')]);
	$('#RetRealRoute').val(gTimeRoute.Ret[$('#RetTime').attr('selectedIndex')]);
	if ($('#TowingYes').attr('checked')) {
		$('#SubmitType').val('AdvancedSearch');
	} else {
		$('#SubmitType').val('Quote');
	}
	document.Step1Form.submit();
}
//******************************************************
function ChangeBooking() {
	$('#OutRealRoute').val(gTimeRoute.Out[$('#OutTime').attr('selectedIndex')]);
	$('#RetRealRoute').val(gTimeRoute.Ret[$('#RetTime').attr('selectedIndex')]);
	$('#SubmitType').val('ChangeBooking');
	document.Step1Form.submit();
}
//******************************************************
function AdvancedSearch() {
	if (quickQuoteValid() == false) return;
	$('#SubmitType').val('AdvancedSearch');
	document.Step1Form.submit();
}
;(function($) {
/******************************************************
 * Adds (single/multiple) options to a select box (or series of select boxes) - 
 * Doesn't check for duplicates!
 *
 * @name     addOptionDup
 * @author   Sam Collett (http://www.texotela.co.uk)
 * @type     jQuery
 * @example  $("#myselect").addOption("Value", "Text"); // add single value (will be selected)
 * @example  $("#myselect").addOption("Value 2", "Text 2", false); // add single value (won't be selected)
 * @example  $("#myselect").addOption({"foo":"bar","bar":"baz"}, false); // add multiple values, but don't select
 *
 */
$.fn.addOptionDup = function()
{
	var add = function(el, v, t, sO)
	{
		var option = document.createElement("option");
		option.value = v, option.text = t;
		// get options
		var o = el.options;
		// get number of options
		var oL = o.length;
		if(!el.cache)
		{
			el.cache = {};
			// loop through existing options, adding to cache
			for(var i = 0; i < oL; i++)
			{
				el.cache[o[i].value] = i;
			}
		}
		// add to cache if it isn't already
		el.cache[v] = oL;
		el.options[el.cache[v]] = option;
		if(sO)
		{
			option.selected = true;
		}
	};
	
	var a = arguments;
	if(a.length == 0) return this;
	// select option when added? default is true
	var sO = true;
	// multiple items
	var m = false;
	// other variables
	var items, v, t;
	if(typeof(a[0]) == "object")
	{
		m = true;
		items = a[0];
	}
	if(a.length >= 2)
	{
		if(typeof(a[1]) == "boolean") sO = a[1];
		else if(typeof(a[2]) == "boolean") sO = a[2];
		if(!m)
		{
			v = a[0];
			t = a[1];
		}
	}
	this.each(
		function()
		{
			if(this.nodeName.toLowerCase() != "select") return;
			if(m)
			{
				for(var item in items)
				{
					add(this, item, items[item], sO);
				}
			}
			else
			{
				add(this, v, t, sO);
			}
		}
	);
	return this;
};
})(jQuery);
