﻿var PassengersController=Class.create(BookingsTab,
{
		initialize:function($super,Containers,Observables,Buttons,NotifyDiv,MsgController,AjaxCallDiv,TabMapper)
		{
			$super(TABS['PASSENGERS'],Containers,Observables,Buttons,NotifyDiv,MsgController,TabMapper);
			//this.STEPS={TRAVELCLASS:1,PASSENGERS:2,VEHICLES:3}; //Not needed
			this.ACTIONTYPE={VERIFYPASSDETAILS:1, DOBCHANGE:2, AREACHANGE:3, PASSDETAILSCHANGE: 4};
			this.REQUESTTYPE={UPDATEPASSENGER:1,AREACHANGE:2,SPECIALOFFER:3};
			this.MESSAGES=	{
								LastNameMissing	:1201,
								FirstNameMissing:1202,
								PassportMissing	:1203,
								LastNameTooLong	:1204,
								FirstNameTooLong:1205,
								PassportTooLong	:1206,
								GenderMissing	:1207,
								DOBMissing		:1208,
								NationalityMissing:1209,
								PickUpPointMissing:1211,
								NoPassengersOfDrivingAge: 1212,
								InvalidFare			: 4000
							};
			this.PassengersColl=new PassengerCollection(0,new Array()); //Just initialize the collection, will be fed from the for
			this.selPass=null;
			this.selPassRow=-1;
			this.InstanceName='insPassController';
			this.AjaxCallDiv=$(AjaxCallDiv);
			this.isDisabled=false;
			this.ButtonColl.enableButtons(TabMovDir['BCK']); //enable the previous buttons
			this.SpecialOfferList=new SpecialOffers
			this.blnSpecialOffer=false;
		},// end initialize
		resetControls: function()
		{
			this.MsgController.ClearServerMessageContainer(); //clear out messages
			this.PassengersColl=new PassengerCollection(0,new Array()); //Just initialize the collection, will be fed from the numbers tab
			this.selPass=null;
			this.selPassRow=-1;
			this.isDisabled=false;
			this.PassDetails.resetControls();
			this.DisableControls();
			this.blnSpecialOffer=false;
		},
		HandleAreaChange: function(Items)
		{
			this.PassDetails.setPickupPoints(Items);
		},//end HandleAreaChange
		setAndInitPassengers: function(PassengerMap,BookingId,AreaHash)
		{
			this.PassengersColl.Passengers=PassengerMap;
			this.PassengersColl.BookingId=BookingId;
			this.PassList.setBookingId(BookingId);
			this.PassList.buildResTable(0,this.PassengersColl.Passengers);
			this.PassDetails.enableControls();

			this.selPass=this.PassengersColl.getFirstPass();
			this.selPassRow=0; //Automatically select the passenger at row 0
			this.selPass.clickedOnce=true;
			//here do something with the buttons
			this.PassDetails.setTitle(this.selPass.reservationId);
			if (AreaHash !=null)
			{
				this.PassDetails.setAreaHash(AreaHash);
			}
		},//end setAndInitPassengers
		HandleUpdatePassResponse: function(SelectedPassStatus,Fare,IsValidFare)
		{
			this.selPass.isSaved=SelectedPassStatus;
			if (this.selPass.isSaved)
			{
				if (IsValidFare)
				{
					this.selPass.fare=Fare;
					this.PassList.buildResTable(this.selPassRow,this.PassengersColl.Passengers);
				}
				else
				{
					this.MsgController.ShowLocalMsgs([this.MESSAGES['InvalidFare']]);
					this.setPassengerVerified(false);
					//this.ButtonColl.disableButtons(TabMovDir['FWD']);
				}
			}
			this.CheckAndContinue();
		}, //end HandleUpdatePassResponse
		CheckAndContinue: function()
		{
			var blnTest=true;
			try
			{
				this.PassengersColl.Passengers.each(function(i)
				{
					var pass=i.value;
					if (!pass.isVerified || !pass.isSaved)
					{
						blnTest=false;
						throw $break;
					}
				},this)
			}
			catch (err)
			{
				alert(err);
				blnTest=false;
			}
			if (blnTest && this.blnSpecialOffer)
				this.ButtonColl.enableButtons(TabMovDir['FWD']);
			else
				this.ButtonColl.disableButtons(TabMovDir['FWD']);
		},//end CheckAndContinue
		setRequest: function(requestType)
		{
			try
			{
					Element.show($(this.NotifyDiv));
					this.MsgController.ClearServerMessages();
					switch (requestType)
					{
						case this.REQUESTTYPE['UPDATEPASSENGER']:
						{
							this.UpdatePassengerRequest($(this.NotifyDiv));
							break;
						}
						case this.REQUESTTYPE['AREACHANGE']:
						{
							this.GetPickupPointsRequest($(this.NotifyDiv));
							break;
						}
						//NJF - 10032009
						case this.REQUESTTYPE['SPECIALOFFER']:
						{
							this.blnSpecialOffer = false;
							this.GetSpecialOffersRequest($(this.NotifyDiv));
							break;
						}
					}
			}
			catch (err)
			{
				alert(err)
				return false;
			}
		}, //end setRequest
		GetPickupPointsRequest: function(NotifyContainer)
		{
			new Ajax.Updater(this.AjaxCallDiv,this.url,
			{
				method: 'post',
				evalScripts: true,
				parameters:
				{
					ajaxLoad:	REQUESTTYPE['GETPICKUPPOINTS'],
					areaId:		this.PassDetails.getArea()
				},
				onComplete: function(transport) //note this keyword will not work in here
				{
					Element.hide(NotifyContainer);
				}
			});
		},//end GetPickupPointsRequest
		//NJF - 10032009
 		GetSpecialOffersRequest: function(NotifyContainer)
		{
			try
			{
				new Ajax.Updater(this.AjaxCallDiv,this.url,
				{
					method: 'post',
					evalScripts: true,
					parameters:
					{
						ajaxLoad:	REQUESTTYPE['SPECIALOFFER'],
						BookingId:	this.PassList.getBookingId(),
						Type	 :  'P'
					},
					onComplete: function(transport) //note this keyword will not work in here
					{
						Element.hide(NotifyContainer);
					}
				});
			}
			catch(err)
			{
				alert(err);
			}
		},//end GetSpecialOffersRequest
		//setSpecialOffer: function(OfferId,OfferRate,OfferDescription)
		setSpecialOffer: function(OfferId,OfferRate,OfferDescription,OfferLink,OfferNotice,OfferFareBasis,Entitlement,VehicleOfferRate,VehicleOfferFareBasis,VehicleOfferEntitlement,ImmediatePayment)
		{	
			this.SpecialOfferList.OfferId=OfferId;
			this.SpecialOfferList.OfferRate=OfferRate;
			this.SpecialOfferList.OfferDescription=OfferDescription;
			this.SpecialOfferList.OfferLink=OfferLink;
			this.SpecialOfferList.OfferNotice=OfferNotice;
			this.SpecialOfferList.OfferFareBasis=OfferFareBasis;
			this.SpecialOfferList.OfferEntitlement=Entitlement;
			this.SpecialOfferList.VehicleOfferRate=VehicleOfferRate;
			this.SpecialOfferList.VehicleOfferFareBasis=VehicleOfferFareBasis;
			this.SpecialOfferList.VehicleOfferEntitlement=VehicleOfferEntitlement;
			this.SpecialOfferList.ImmediatePayment=ImmediatePayment;			
			this.blnSpecialOffer = true; 
			this.CheckAndContinue();		
		},//end setSpecialOffer
		UpdatePassengerRequest: function(NotifyContainer)
		{
			var DateRet;
			if (this.TabMapper.RouteTab.IsExcursion)
				DateRet=this.TabMapper.RouteTab.DateOut.getTripDate();
			else
				DateRet=(this.TabMapper.RouteTab.DateRet.hasDates() ? this.TabMapper.RouteTab.DateRet.getTripDate():-1);

			new Ajax.Updater(this.AjaxCallDiv,this.url,
			{
				method: 'post',
				evalScripts: true,
				parameters:
				{
					ajaxLoad:	REQUESTTYPE['UPDATEPASS'],
					VoyIdOut:	this.TabMapper.RouteTab.outVoyage.getVoyageId(),
					VoyIdRet:	this.TabMapper.RouteTab.retVoyage.getVoyageId(),
					VoyPartOut:	this.TabMapper.RouteTab.outVoyage.getVoyagePartId(),
					VoyPartRet:	this.TabMapper.RouteTab.retVoyage.getVoyagePartId(),
					DateOut:	this.TabMapper.RouteTab.DateOut.getTripDate(),
					DateRet:	DateRet, //if it has date otherwise -1
					OpenEnded:	(this.TabMapper.RouteTab.IsOpenEnded() ? 1 : 0),
					ReservationId: this.selPass.reservationId,
					bookingId:	this.PassList.getBookingId(),
					FirstName:	this.selPass.firstName,
					LastName:	this.selPass.lastName,
					Gender:		this.selPass.getGenderCode(),
					DOB:		this.selPass.getDOB(),
					PassportNum:	this.selPass.passportNum,
					PassengerType:	this.selPass.getPassTypeIdOut(),
					NationalityId:	this.selPass.nationality,
					ImpEye:		this.selPass.impairedEye,
					ImpHear:	this.selPass.impairedHear,
					MedCond:	this.selPass.medicalProblems,
					RestMob:	this.selPass.restrictedMobility,
					//SpcPark:	this.selPass.specialParking,
					Remarks:	this.selPass.remarks,
					HasPickUp:	this.selPass.HasPickUp,
					AreaId:		this.selPass.getArea(), //encrypt this
					PickUpPointId:	this.selPass.pickUpPointId, //and this
					RoomNum:		(this.selPass.roomNum.length<1 ? ' ' : this.selPass.roomNum) //and this
				},
				onComplete: function(transport) //note this keyword will not work in here
				{
					Element.hide(NotifyContainer);
				}
			});
		},//end UpdatePassengerRequest
		SetPassengerFromDetails: function()
		{
			this.selPass.lastName=this.PassDetails.getLastName();
			this.selPass.firstName=this.PassDetails.getFirstName();
			this.selPass.passportNum=this.PassDetails.getPassPort();
			this.selPass.gender=this.PassDetails.getGender();
			this.selPass.DOB=this.PassDetails.getDOB();
			this.selPass.setAgeAndType(this.TabMapper.RouteTab.DateOut.getTripDateAsDate(),this.PassDetails.PassTypeColl);
			this.selPass.nationality=this.PassDetails.getNationality();
			this.selPass.impairedEye=this.PassDetails.getImpairedEye();
			this.selPass.impairedHear=this.PassDetails.getImpairedHear();
			this.selPass.medicalProblems=this.PassDetails.getMedicalProblems();
			this.selPass.restrictedMobility=this.PassDetails.getRestrictedMobility();
			//this.selPass.specialParking=this.PassDetails.getSpecialParking();
			this.selPass.remarks=this.PassDetails.getRemarks();
			this.selPass.areaId=this.PassDetails.getArea();
			this.selPass.pickUpPointId=this.PassDetails.getPickupPoint();
			this.selPass.roomNum=this.PassDetails.getRoomNum();
		},//end SetPassengerFromDetails
		SetActivePassenger: function(resvId,passRow)
		{
			this.selPass=this.PassengersColl.getPass(resvId);
			this.PassDetails.setPassenger(this.selPass);
			this.selPassRow=passRow-1;
			this.selPass.clickedOnce=true; //from now on read the items in the forms
		},//end SetActivePassenger
		setPassengerVerified: function(Value)
		{
			this.selPass.isVerified=Value;
			if (!Value) //otherwise leave them as you found them :)
				this.ButtonColl.disableButtons(TabMovDir['FWD']);
		},//setPassengerVerified
		setObservableEvent: function($super,sender,args)
		{
			$super(sender);
			if (sender===this.PassDetails)
			{
				if (args.length>0)
				{
					var requestType=args[0];
					switch (requestType)
					{
						case (this.ACTIONTYPE['VERIFYPASSDETAILS']):
						{
							this.MsgController.ClearServerMessageContainer();
							this.setPassengerVerified(false);
							if (this.VerifyPassengerDetails())
							{
								this.SetPassengerFromDetails();
								this.setPassengerVerified(true);
								this.setRequest(this.REQUESTTYPE['UPDATEPASSENGER']);
								this.setRequest(this.REQUESTTYPE['SPECIALOFFER']);
							}
							else
							{
								this.MsgController.ShowLocalMsgs(this.PassDetails.ValidationErrors);
							}
							break;
						}
						case (this.ACTIONTYPE['DOBCHANGE']):
						{
							this.selPass.DOB=this.PassDetails.getDOB();
							this.selPass.setAgeAndType(this.TabMapper.RouteTab.DateOut.getTripDateAsDate(),this.PassDetails.PassTypeColl);
							this.PassDetails.setPassType(this.selPass.getPassTypeLabel());
							this.setPassengerVerified(false);
							//This is done like this coz i can't fucking find where im disabling them both!!
							this.ButtonColl.disableButtons(TabMovDir['FWD']);
							this.ButtonColl.enableButtons(TabMovDir['BCK']);
							break;
						}
						case (this.ACTIONTYPE['AREACHANGE']):
						{
							//here we need a request to get the areas
							this.setRequest(this.REQUESTTYPE['AREACHANGE']);
							break;
						}
						case (this.ACTIONTYPE['PASSDETAILSCHANGE']):
						{
							this.setPassengerVerified(false);
							this.ButtonColl.disableButtons(TabMovDir['FWD']);
							this.ButtonColl.enableButtons(TabMovDir['BCK']);
							break;
						}
					}
				}
			}//end Sender===PassDetails
			else if (sender===this.PassList)
			{
				var resvId=args[0]; //reservationId
				var TableBodyId=args[1];
				var rowIndex=args[2];
				this.MsgController.ClearServerMessageContainer();
				if (this.VerifyPassengerDetails())
				{
					this.SetPassengerFromDetails();
					this.selPassRow=rowIndex-1;
					if (!this.isDisabled)
					{
						this.setPassengerVerified(true);
						//This request screws up stuff a bit sometimes so taken off
						//This means that the user always has to press the verify button!!

						//It is safer w/o it - this ensures that for each pass the verify is pressed

						//this.setRequest(this.REQUESTTYPE['UPDATEPASSENGER']); //Any click to another person will update the passenger
					}
					var rows=$A(TableBodyId.getElementsByTagName('tr')).map(Element.extend);
					var rNum=0;
					rows.each(function(r)
					{
						if (++rNum==rowIndex)
						{
							if (!r.hasClassName('highlight'))
								r.addClassName('highlight');
						}
						else
						{
							if (r.hasClassName('highlight'))
								r.removeClassName('highlight');
						}
					});
					this.SetActivePassenger(resvId,rowIndex);
					var form=theForm; //080809 - was $('aspnetForm'); however this is too dangereous so using theForm which is set by .net automatically...in this way form name can be anything we want..Expedia and Normal booking have different form names
					var rg=form.getInputs('radio','passResv');
					if (this.selPassRow>-1)
					{
						rg[this.selPassRow].checked=true;
						rg[this.selPassRow].activate();
					}
				}
				else
				{
					//put the radio button back where it was, cld be a simpler way to do this..no time to fnd out
					var form=theForm;//080809 - was $('aspnetForm'); however this is too dangereous so using theForm which is set by .net automatically...in this way form name can be anything we want..Expedia and Normal booking have different form names
					var rg=form.getInputs('radio','passResv');
					if (this.selPassRow>-1)
					{
						rg[this.selPassRow].checked=true;
						rg[this.selPassRow].activate();
					}
					this.MsgController.ShowLocalMsgs(this.PassDetails.ValidationErrors);
					return false;
				}
			}//end Sender===PassList
			else if (sender===this.ButtonColl)
			{
				try
				{
				switch (args[0])
				{
					case (TabMovDir['FWD']):
					{
						this.DisableControls();
						if (this.TabMapper.VehiclesTab.HasVehicleReservations())
						{
							var idx=0;
							var drvColl=new Hash();
							this.PassengersColl.Passengers.each(function(pass)
							{
								var aPass=pass.value;
								if (aPass.ageOnDOTOut>=18)
								{
								//idx++;
									var drv=aPass.getAsDriver(++idx);
									drvColl.set(idx,drv);
								}
							},this);

							var numDrivers=drvColl.keys().length;
							var numVehicles=this.TabMapper.VehiclesTab.VehicleReservations.getNumReservations();
							if (numDrivers>=numVehicles) //There must be at least one driver per car
							{
								this.TabMapper.VehiclesTab.setAndInitDrivers(new DriverCollection(drvColl));
								this.ButtonColl.disableButtons();
								this.ButtonColl.MoveToTab(TabMovDir['FWD']); //Move to vehicles tab
							}
							else
							{
								this.MsgController.ShowLocalMsgs([this.MESSAGES['NoPassengersOfDrivingAge']]);
								this.setPassengerVerified(false);
								this.ButtonColl.disableButtons(TabMovDir['FWD']);
								this.EnableControls();
							}
						}
						else
						{
							this.ButtonColl.DisableTab(TABS['VEHICLES']);				
							//this.setRequest(this.REQUESTTYPE['SPECIALOFFER']);
							this.TabMapper.ConfirmationTab.setAndInitFaresTable(this.PassList.getBookingId());
							this.ButtonColl.disableButtons();
							this.ButtonColl.MoveToTabIndex(TABS['CONFIRMATION']); //Otherwise move to the confirmation tab
						}
						break;
					}
					case (TabMovDir['BCK']):
					{
						this.resetControls();
						this.ButtonColl.MoveToTab(TabMovDir['BCK']);
						this.TabMapper.NumbersTab.enableControls();

						break;
					}
				}
			}
			catch (err)
			{
				alert(err);
			}
		}
	},// end setObservableEvent
	VerifyPassengerDetails: function()
		{
			var blnTest=true;
			var numErrors=0;
			this.PassDetails.ValidationErrors=new Array(); //Clear it out
			if (this.PassDetails.getLastName().length<1)
			{
				this.PassDetails.ValidationErrors[numErrors++]=this.MESSAGES['LastNameMissing'];
				blnTest=false;
			}
			if (this.PassDetails.getLastName().length>40)
			{
				this.PassDetails.ValidationErrors[numErrors++]=this.MESSAGES['LastNameTooLong'];
				blnTest=false;
			}
			if (this.PassDetails.getFirstName().length<1)
			{
				this.PassDetails.ValidationErrors[numErrors++]=this.MESSAGES['FirstNameMissing'];
				blnTest=false;
			}
			if (this.PassDetails.getLastName().length>40)
			{
				this.PassDetails.ValidationErrors[numErrors++]=this.MESSAGES['FirstNameTooLong'];
				blnTest=false;
			}
			if (this.PassDetails.getPassPort().length<1) //do > 40 check too
			{
				this.PassDetails.ValidationErrors[numErrors++]=this.MESSAGES['PassportMissing'];
				blnTest=false;
			}
			if (this.PassDetails.getPassPort().length>40)
			{
				this.PassDetails.ValidationErrors[numErrors++]=this.MESSAGES['PassportTooLong'];
				blnTest=false;
			}
			if (this.PassDetails.getGender()==0)
			{
				this.PassDetails.ValidationErrors[numErrors++]=this.MESSAGES['GenderMissing'];
				blnTest=false;
			}
			if (this.PassDetails.getDOB()==null) //here other logic for the various combinations etc etc
			{
				this.PassDetails.ValidationErrors[numErrors++]=this.MESSAGES['DOBMissing'];
				blnTest=false;
			}
			if (this.PassDetails.getNationality()<1)
			{
				this.PassDetails.ValidationErrors[numErrors++]=this.MESSAGES['NationalityMissing'];
				blnTest=false;
			}
			if (this.PassDetails.getArea()>0 && this.PassDetails.getPickupPoint()<1)
			{
				this.PassDetails.ValidationErrors[numErrors++]=this.MESSAGES['PickUpPointMissing'];
				blnTest=false;
			}
			return blnTest;
		},//end VerifyPassengerDetails
		DisableControls: function()
		{
			this.PassDetails.disableControls();
			this.isDisabled=true;
		},
		EnableControls: function()
		{
			this.PassDetails.enableControls();
			this.isDisabled=false;
		}
});//end PassengersController

var PassengerTypeColl=Class.create(
{
	initialize: function(Map)
	{
		var passTypes=new Hash();
		passTypes.merge(Map);
		Map.each(function(pType)
		{
			passTypes.set(pType.key,new PassengerType(pType.key,pType.value));
		});
		this.passTypes=passTypes;
	},
	getPassengerByAge: function(age)
	{
		//default to adult
		var pass=null; //this.passTypes[PassengerTypes['Adult']];
		age=(age<1)?1:age; //when its 0 the check fucks up due to 0 and false being equivalent so make it 1
		//loop over the collection and find the match where the from and to ages match
		this.passTypes.each(function(pa)
		{
			var aPass=pa.value;
			if ((age>=aPass.fromAge) && (age<=aPass.toAge))
			{
				pass=aPass;
				throw $break;
			}
		},this);
		return pass;
	}
});//End PassengerTypeColl

var PassengerType=Class.create(
{
	initialize: function(id,Map)
	{
		this.id=id;
		this.reference=Map.get('Reference');
		this.description=Map.get('Description');
		this.fromAge=Map.get('FromAge');
		this.toAge=Map.get('ToAge');
		this.passType=Map.get('PassengerType');
	}
});//End PassenerType

var PassengerCollection=Class.create(
{
	initialize: function(BookingId,Passengers)
	{
		this.bookingId=BookingId;
		this.Passengers=Passengers;
	},//end initialize
	getFirstPass: function()
	{
		return this.Passengers.get(this.Passengers.keys().first());
	},//end getFirstPass
	getPass: function(resvId)
	{
		return this.Passengers.get(resvId); //Note, this has changed since the api has changed
	},//end getPass
	getReservations: function()
	{
		return this.Passengers;
	}//end getReservations
});//End PassengerColl

//Refer to old Expedia version - seriously improved :)
var PassengerDetails=Class.create(ReservationDetails,
{
	initialize: function($super,ControlHierarchy,Controls,PassTypeColl,DobControl,PickupsStep)
	{
		$super(ControlHierarchy,Controls);
		this.DOB=ControlHierarchy + DobControl;
		this.PassTypeColl=PassTypeColl;
		this.GenderMap={F:1,M:2}; //Just a quick enum

		this.PickupsStep=$(PickupsStep);
		Element.hide(this.PickupsStep);
		this.disableControls(); //must be the last call
	//	this.isSetup=false;
//		$(this.LastName).observe('onkeyup', this.RaiseKeyUp()); //experimental but this needs to be done with bindingAsEventListener
		//this.isSetup=true;
	},
	setAreaHash: function(AreaHash)
	{
		clearSelectButTitle(this.PickupArea); //just in case
		if (AreaHash.length>0)
		{
			Element.show(this.PickupsStep);
			var idx=0;
			AreaHash.each(function(itm)
			{
				AddToCombo(this.PickupArea,++idx,new Option(itm.get('text'),itm.get('value')));
			},this);
		}
		else
		{
			Element.hide(this.PickupsStep);
		}
	},
	setPickupPoints: function(Items)
	{
		clearSelectButTitle(this.PickupPoint);
		var idx=0;
		Items.each(function(itm)
		{
			AddToCombo(this.PickupPoint,++idx,new Option(itm.get('text'),itm.get('value')));
		},this);
	},
	//maps ids to index
	//Can and should be improved....
	getNationalityIndex: function(NationalityId)
	{
		var opts=$A(this.Nationality.options);
		var idx=-1;
		var blnFound=false;
		opts.each(function(itm)
		{
			idx++;
			if (itm.value==NationalityId)
			{
				blnFound=true;
				throw $break;
			}
		});
		if (!blnFound)
		{
			idx=0;
		}
		return idx;
	},
	RaiseKeyDown: function(e)
	{
		//not implemented yet
		//return noSpecialCharacters(e);
	},
	RaiseKeyUp: function(ctl)
	{
			if (this.observer.selPass.isVerified)
				this.observer.setObservableEvent(this,[this.observer.ACTIONTYPE['PASSDETAILSCHANGE']]);
	},
	RaiseItemChange: function(ctl)
	{
		if (this.observer.selPass.isVerified)
			this.observer.setObservableEvent(this,[this.observer.ACTIONTYPE['PASSDETAILSCHANGE']]);

	},//RaiseItemChange
	RaiseVerifyEvent: function()
	{
		try
		{
			this.observer.setObservableEvent(this,[this.observer.ACTIONTYPE['VERIFYPASSDETAILS']]);
		}
		catch (err)
		{
			alert(err);
		}
		return false;
	},//end RaiseVerifyEvent
	RaiseDobChangedEvent: function(oEdit, oldValue, oEvent)
	{
		try
		{
			if (this.getDOB()!=null)
			{
				this.observer.setObservableEvent(this,[this.observer.ACTIONTYPE['DOBCHANGE']]);
			}
		}
		catch (err)
		{
			alert(err);
		}
	},//end RaiseDobChangedEvent
	RaiseAreaChangeEvent: function()
	{
		try
		{
			if (this.getArea()>0)
			{
				this.observer.setObservableEvent(this,[this.observer.ACTIONTYPE['AREACHANGE']]);
			}
			else
			{
				clearSelectButTitle(this.PickupPoint);//clears up all the options but the title
				this.PickupPoint.selectedIndex=0;
			}
		}
		catch (err)
		{
			alert(err);
		}
	},
	disableControls: function($super)
	{
		$super(); //make a call to super class
		var edit=this.getDOBControl();
		if (typeof(edit) != "undefined") //This check is needed since infragistics controls are defined at end of page
			edit.setEnabled(false);
	},//end disableControls
	enableControls: function($super)
	{
		$super(); //makes a call to super class
		var edit=this.getDOBControl();
		if (typeof(edit) != "undefined") //This check is needed since infragistics controls are defined at end of page
			edit.setEnabled(true);
	},//end enableControls
	resetControls: function()
	{
			this.setLastName(''); //should have a clear function which loops over the whole collection or use prototype's
			this.setFirstName('');
			this.setPassPort('');
			this.setGender(0);
			this.setDOB(null);
			this.setNationality(0);
			this.setImpairedEye(false);
			this.setImpairedHear(false);
			this.setMedicalProblems(false);
			this.setRestrictedMobility(false);
			//this.setSpecialParking(false); //Client request to remove it
			this.setRemarks('');
			this.setPassType('');
			//Might need a check first
			this.setArea(0);
			this.setPickupPoint(0);
			this.setRoomNum('');
	},
	setPassenger: function(aPass)
	{
		this.setTitle(aPass.reservationId);
		if (!aPass.clickedOnce)
		{
			this.resetControls();
		}
		else
		{
			this.setLastName(aPass.lastName);
			this.setFirstName(aPass.firstName);
			this.setPassPort(aPass.passportNum);
			this.setGender(aPass.gender);
			this.setDOB(aPass.DOB);
			this.setNationality(aPass.nationality);
			this.setImpairedEye(aPass.impairedEye);
			this.setImpairedHear(aPass.impairedHear);
			this.setMedicalProblems(aPass.medicalProblems);
			this.setRestrictedMobility(aPass.restrictedMobility);
			//this.setSpecialParking(aPass.specialParking);
			this.setRemarks(aPass.remarks);
			this.setPassType(aPass.getPassTypeLabel());
			this.setArea(aPass.getArea());
			this.setPickupPoint(aPass.pickUpPointId);
			this.setRoomNum(aPass.roomNum);
		}
	},//end setPassenger
	setLastName: function(str)
	{
		$(this.LastName).value=str.toUpperCase(); //style sheet is taking care of this but need it in db
	},//end setLastName
	getLastName: function()
	{
		return $F(this.LastName).toUpperCase();;
	},//end getLastName
	setFirstName: function(str)
	{
		$(this.FirstName).value=str.toUpperCase();
	},//end setFirstName
	getRoomNum: function()
	{
		return $F(this.RoomNum).toUpperCase();;
	},//end getLastName
	setRoomNum: function(str)
	{
		$(this.RoomNum).value=str.toUpperCase();
	},//end setFirstName
	getFirstName: function()
	{
		return $F(this.FirstName).toUpperCase();;
	},//end getFirstName
	setPassPort: function(str)
	{
		$(this.Passport).value=str;
	},//end setPassPort
	getPassPort: function()
	{
		return $F(this.Passport);
	},//end getPassPort
	getGender: function()
	{
		return $F(this.Gender);
	},//end getGender
	setGender: function(value)
	{
		var idx=this.GenderMap[value];
		if (idx=='undefined')
			idx=0;
		$(this.Gender).selectedIndex=idx;
	},//end setGender
	getArea: function()
	{
		return $F(this.PickupArea);
	},
	setArea: function(AreaId)
	{
		var opts=$A(this.PickupArea.options);
		var idx=-1;
		var blnFound=false;
		opts.each(function(itm)
		{
			idx++;
			if (itm.value==AreaId)
			{
				blnFound=true;
				throw $break;
			}
		});
		if (!blnFound)
		{
			idx=0;
		}
		this.PickupArea.selectedIndex=idx;
	},
	getPickupPoint: function()
	{
		return $F(this.PickupPoint);
	},
	setPickupPoint: function(PickupPointId)
	{
		var opts=$A(this.PickupPoint.options);
		var idx=-1;
		var blnFound=false;
		opts.each(function(itm)
		{
			idx++;
			if (itm.value==PickupPointId)
			{
				blnFound=true;
				throw $break;
			}
		});
		if (!blnFound)
		{
			idx=0;
		}
		this.PickupPoint.selectedIndex=idx;
	},
	getDOBControl: function()
	{
		return igedit_getById(this.DOB);
	},//end getDOBControl
	getDOB: function() //Note this needs special handling since its an infragisitics control
	{
		var editor=igedit_getById(this.DOB);
		return editor.getValue();
	},//end getDOB
	setDOB: function(date) //Note this needs special handling since its an infragisitics control
	{
		var editor=igedit_getById(this.DOB);
		editor.setDate(date);
	},//end setDOB
	getNationality: function()
	{
		return $F(this.Nationality); //Will always be the number
	},
	setNationality: function(nid)
	{
		this.Nationality.selectedIndex=this.getNationalityIndex(nid); //FIX THIS!!!
	},
	setImpairedEye: function(val)
	{
		$(this.snEyesight).checked=val;
	},
	getImpairedEye: function()
	{
		return $(this.snEyesight).checked;
	},
	setImpairedHear: function(val)
	{
		$(this.snHearing).checked=val;
	},
	getImpairedHear: function()
	{
		return $(this.snHearing).checked;
	},
	setMedicalProblems: function(val)
	{
		$(this.snMedical).checked=val;
	},
	getMedicalProblems: function()
	{
		return $(this.snMedical).checked;
	},
	setRestrictedMobility: function(val)
	{
		$(this.snMobility).checked=val;
	},
	getRestrictedMobility: function()
	{
		return $(this.snMobility).checked;
	},
	/*setSpecialParking: function(val)
	{
		$(this.snParking).checked=val;
	},
	getSpecialParking: function()
	{
		return $(this.snParking).checked;
	},*/
	setRemarks: function(val)
	{
		$(this.Remarks).value=val;
	},
	getRemarks: function()
	{
		return $(this.Remarks).value;
	},
	setPassType: function(val)
	{
		this.PassengerType.innerHTML=val;
	},
	getPassType: function()
	{
		return this.PassengerType.innerHTML;
	}
});//End Pass Details

var Passenger=Class.create(
{
	initialize: function(PassMap)
	{
		PassMap.each(function(passData)
		{
			this[passData.key]=passData.value;
		},this);
		this.gender=0;
		this.DOB=null;
		this.isVerified=false;
		this.clickedOnce=false;
		this.nationality=0;
		//this.requiresVisa=false;
		//this.visa=false;
		this.specialNeeds=false;
		this.remarks='';
		this.impairedEye=false;
		this.impairedHear=false;
		this.medicalProblems=false;
		this.restrictedMobility=false;
		//this.specialParking=false;
		this.isSaved=false;
		this.passengerTypeOut=null;
		//this.passengerTypeRet=null;
		this.ageOnDOTOut=-1; //age on date of travel - this determinies the fare
		this.fare=null;
		this.areaId=0;
		this.pickUpPointId=0;
		this.roomNum='';
	},
	getArea: function()
	{
		if (this.areaId<1)
			this.areaId=0;
		return this.areaId;
	},
	getPassTypeLabel: function()
	{
		var str='';
		if (this.ageOnDOTOut!=-1 && this.getPassTypeIdOut!=-1) //put in undefined check too
		{
			if (this.passengerTypeOut.description!='undefined')
				str=this.passengerTypeOut.description;
		}
		return str;
	},
	getPassTypeIdOut: function()
	{
		var id=-1;
		if (this.passengerTypeOut!=null) //put in undefined check too
		{
			id=this.passengerTypeOut.id;
		}
		return id;
	},
	getFullName: function()
	{
		return this.lastName + ' ' + this.firstName;
	},
	getRadioAndImageHTML: function(rowNum,isSelected,objRef)
	{
		var id="passResv" + (rowNum + 1);
		var str ="<label for=\"" + id + "\">"
		str +="<img align=\"absbottom\" src=\"../../images/icons/people/manSmall.png\" width=\"11\" height=\"16\" alt=\"Passenger Icon\" />";
		str +="</label>";
		str +="<input id=\""+ id + "\" type=\"radio\" value=\"" + this.reservationId + "\" name=\"passResv\" onclick=\"" + objRef + ".RaiseItemSelected(this," + (rowNum+1) + ")\" style=\"border: none;\""
		if (isSelected)
			str +=" checked=\"checked\""

		str +="/>"
		return str;
	},
	getNameHTML: function(rowNum)
	{
		var id="passResv" + (rowNum + 1);
		var str ="<label for=\"" + id + "\">"
		str +=this.getFullName();
		str +="</label>";
		return str;
	},
	getReservationIdHTML: function(rowNum)
	{
		var id="passResv" + (rowNum + 1);
		var str ="<label for=\"" + id + "\">"
		str +=this.reservationId;
		str +="</label>";
		return str;
	},
	getGenderCode: function()
	{
		return this.gender;
	},
	getDOB: function()
	{
		return this.DOB.getFullYear()+'/'+ (this.DOB.getMonth()+1)+ '/'+this.DOB.getDate();
	},
	getFareResvNumHTML: function() //reservation number cell in fares table
	{
		var str ="<label>"
		str+=this.reservationId; //label does not need id as non selectable
		str+="</label>";
		return str;
	},
	getFareDetailsHTML: function()
	{
		var str ="<label id=\"FareName\">"
		str+=this.getFullName();
		str+="</label>";
		return str;
	},
	setAgeAndType: function(dtOfTravel,passTypes)
	{
		//Modified from http://www.javascriptkit.com/script/script2/calculateage.shtml
		var age=-1;
		if (dtOfTravel!=-1 && this.DOB!=null)
		{
			//Note for this to work properly, the passenger types data must be accurate
			try
			{
			var one_day=1000*60*60*24;
			var one_month=1000*60*60*24*30;
			var one_year=1000*60*60*24*30*12;
			var dob=new Date(this.DOB.valueOf()); //clone it, otherwise you change the reference
			var yr=dob.getFullYear();
			var mon=dob.getMonth();
			var day=dob.getDate();
			//set dob to same time as dot - This was an old idea...now it will always be midnight - not sure if this applies anymore
			dob.setHours(dtOfTravel.getHours());
			dob.setMinutes(dtOfTravel.getMinutes());
			dob.setSeconds(dtOfTravel.getSeconds());
			var decimals=1;
			yearspast=dtOfTravel.getFullYear()-yr-1;
			tail=(dtOfTravel.getMonth()>mon-1 || dtOfTravel.getMonth()==mon-1 && dtOfTravel.getDate()>=day)? 1 : 0;
			dob.setFullYear(dtOfTravel.getFullYear());
			dob2=new Date(dtOfTravel.getFullYear()-1, mon-1, day);
			tail=(tail==1)? tail+Math.floor((dtOfTravel.getTime()-dob.getTime())/(one_year)*decimals)/decimals : Math.floor((dtOfTravel.getTime()-dob2.getTime())/(one_year)*decimals)/decimals;
			age=yearspast+tail;
			if (age>99)
				age=99; //just in case as db is only char(2)!!
			}
			catch (err)
			{
				alert(err);
			}
		}
		//Note refer to old code, since this was originally dependant on age of travel on out and return
		//Business logic has changed for this
		this.ageOnDOTOut=age;
		this.passengerTypeOut=passTypes.getPassengerByAge(age);
	},
	getAsDriver: function(idx) //Note dependency on vehicles.js
	{
		return new Driver(idx,this.getFullName(),this.reservationId);
	}
});//End Passenger

function invalidDOB(oEdit, fields, oEvent)
{
	var typeOfInvalidText = fields.type;
	if(typeOfInvalidText == 0)  //String cannot be converted to a date
	{
		fields.date=null;
        oEdit.setText(oEdit.nullText);
		oEdit.setValue(oEdit.nullText);
    }
	if(typeOfInvalidText == 1)//New value is out of Min/Max range of dates
	{
		fields.date=null;
        oEdit.setText(oEdit.nullText);
		oEdit.setValue(oEdit.nullText);
    }
	if(typeOfInvalidText == 2) //1 or more field have invalid values
	{
		fields.date=null;
        oEdit.setText(oEdit.nullText);
		oEdit.setValue(oEdit.nullText);
    }
	oEvent.cancel = true;
}

//Unfortanetly this is the only way found of getting this to work reliably..the instance
//name of the pass details object has to be hard coded here...anonymous functions do not work
//well with infragistics objects...there might be a way to hook an observable event to this.
function DOBValueChanged(oEdit,oldValue, oEvent)
{
	insPassengerDetails.RaiseDobChangedEvent(oEdit,oldValue, oEvent);
}

//Special Offer
var SpecialOffers=Class.create(
{
	initialize: function(OfferId,OfferRate,OfferDescription,OfferLink,OfferNotice,OfferFareBasis,OfferEntitlement,VehicleOfferRate,VehicleOfferFareBasis,VehicleOfferEntitlement,ImmediatePayment)
	{
		this.OfferId=0;
		this.OfferRate=0;
		this.OfferDescription='No Special Offer';
		this.OfferLink='http://localhost/VirtuWeb/pages/E/specialoffers.aspx';
		this.OfferNotice='Click here to read the Special Offer Conditions.';
		this.OfferFareBasis='';
		this.OfferEntitlement=0;
		this.VehicleOfferRate=0;
		this.VehicleOfferFareBasis='';
		this.VehicleOfferEntitlement;
		this.ImmediatePayment=0;
	}//end initialize
});//end SpecialOffer