/*  ALL OF THE REX BOOKING FORM JAVASCRIPT EVENT HANDLERS/FUNCTIONS ARE HERE !! */
	
	//function doneRequest(response){
		//j = new Json.evaluate(response);
	//}
	
	function showLoading(){
		$('#loading').show();
	}
	function showProfileIdExplain(obj){
		togglePopWin('what_is_traveller_id');
	}
	function doneLoading(){
		$('#loading').hide();
	}
	
	
	function doneLoadingSelectTripOptionsForm(){
		doneLoading();
		
		Calendar.setup({
	        inputField     :    "d1",     // id of the input field
	        ifFormat       :    "%Y-%m-%d",     // format of the input field
	        button         :    "f_trigger_1",  // trigger for the calendar (button ID)
	        align          :    "Tl",           // alignment (defaults to "Bl")
	        singleClick    :    true
	    });
		Calendar.setup({
	        inputField     :    "d2",     // id of the input field
	        ifFormat       :    "%Y-%m-%d",     // format of the input field
	        button         :    "f_trigger_2",  // trigger for the calendar (button ID)
	        align          :    "Tl",           // alignment (defaults to "Bl")
	        singleClick    :    true
	    });
		
	}
	function checkEmail(strEmail) {
		//if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(strEmail)){
		if (/^[-a-z0-9~!$%^&*_=+}{\'?]+(\.[-a-z0-9~!$%^&*_=+}{\'?]+)*@([a-z0-9_][-a-z0-9_]*(\.[-a-z0-9_]+)*\.([a-z][a-z]+)|([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}))(:[0-9]{1,5})?$/i.test(strEmail)){
			return (true);
		}
		return (false);
	}
	function checkPhone(str) { 
		if (str.length > 9) {
	   		return true;
	 	}
		
		return false;
	}

	function toggle(myID){
		if($('#'+myID).is(":hidden")){ 
			$('#'+myID).show();
		}else{ 
			$('#'+myID).hide();
		}
	}
	function drawSelectTripOptionsForm(){
		showLoading();
		$('input[type=button]').attr('disabled','disabled');
		
		// reset Number Icons
		$('#booking_steps li').removeClass('active');
		$('#booking_step_1').addClass('active');
		
		// page tracking
		//pageTracker._trackPageview('/booking/search_again');

		$('#form_container').load('handler.rex.php?action=drawSelectTripOptionsForm', function() {
			doneLoadingSelectTripOptionsForm();
		});	
	}
	function getDestinations(origin){
		showLoading();
		//var myAjax = new Ajax('handler.rex.php?action=getDestinations', {method: 'post', update: $('destination_select'), postBody: "origin="+origin, onComplete: doneLoading}).request();
		$('#destination_select').load('handler.rex.php?action=getDestinations', {'origin': origin}, function() {
			$('select#origin option:first').remove();
			doneLoadingSelectTripOptionsForm();
		});	

	}
	function showReturnOptions(checkbox){
		if(checkbox.checked){
			$('#return_options').show('slow');
			$('#d2').val( "0000-00-00" );
		}else{
			$('#return_options').hide();
			$('#d2').val("");
		}
	}
	function showFareOptions(radio,i){
		senior_age_box = "#senior_age"+i;
		if(radio.value == 'senior'){
			$(senior_age_box).show();
		}else{
			$(senior_age_box).hide();
		}
	}
	function handleFindAvailability(){
		
		// check for back-dated travel - don't allow this.
		if(isDateInPast($('#d1').val() )){
			alert('You may not book a trip in the past. Please double check your departure date.')
		}else if($('#returnTripCheck').is(':checked') && isReturnBeforeDeparture($('#d1').val() ,$('#d2').val() )){
			alert('You may not book a return trip in the before your departure. Please double check your return date.')
		}else{
			showLoading();
			$('#cmsContent').hide();

			// grey out button while loading...
			$('#btn_check_availability').attr('disabled', 'disabled');
			
			var dataArray = $('#f').serializeArray();
			
			$.post( 'handler.rex.php?action=handleFindAvailability', dataArray,  function(data) {
				$('#booking_steps li').removeClass('active');
				$('#booking_step_2').addClass('active');
				doneLoading();					
				$('#form_container').empty().append(data);
				$( 'html, body' ).animate( { scrollTop: 0 }, 0 );
			});
			
			// page tracking
			//pageTracker._trackPageview('/booking/check_availability');
		}
	}
	function handleTripChoice(){
		showLoading();
		// grey out button while loading...
		$('input[type="btn2"]').attr('disabled','disabled');
		
		var dataArray = $('#f').serializeArray();
		
		$.post( 'handler.rex.php?action=handleTripChoice', dataArray,  function(data) {
			// reset Number Icons
			$('#booking_steps li').removeClass('active');
			$('#booking_step_3').addClass('active');
			doneLoading();					
			$('#form_container').empty().append(data);
			$( 'html, body' ).animate( { scrollTop: 0 }, 0 );
		});
		
		//pageTracker._trackPageview('/booking/create_booking');
	}
	function handleCustomerLogin(){
		showLoading();
		
		var u = $('#username').val();
		var p = $('#password').val();
		
		$.post( 'handler.rex.php?action=handleCustomerLogin', { "u": u, "p":p },  function(data) {
			doneLoading();					
			$('#customer_login_container').empty().append(data);
			if( $('#loginWelcome').length ){
				//var nameBits = $('#loginWelcome strong').html().split(' ');
				$('#form_container').prepend( '<h2>' + $('#loginWelcome').html() + '</h2>' );
				//$('#adultFirstName1').val(nameBits[0]);
				//$('#adultLastName1').val(nameBits[1]);
			}
		});
		 
		// page tracking
		//pageTracker._trackPageview('/booking/signin');
	}
	function handleForgotPassword(){
		var email = $('#email').val();
		if(checkEmail(email)){
			showLoading();
			$.post( 'handler.rex.php?action=handleForgotPassword', { "email": email, "p":p },  function(data) {
				doneLoading();					
				$('#forgot_password_container').empty().append(data);
			});

		}else{
			alert("Invalid E-mail Address! Please re-enter.");
			$('#email').focus();
		}
	}
	function handleCreateBooking(){
		
		// Validate Name/Phone Fields if traveller is NOT using ID
		var numAdults = $('#numAdults').val();
		var numChildren = $('#numChildren').val();
		var errorMsg = "";
		
		for(i=1;i<=numAdults;i++){
			if($('#travellerID'+i).val()  == ""){ 
				if($('#adultFirstName'+i).val()  == ""){
					alert('If you are not using a Traveller ID, please ensure you have filled in your Full Name');
					$('#adultFirstName'+i).focus(); return false;
				}
				if($('#adultLastName'+i).val()  == ""){
					alert('If you are not using a Traveller ID, please ensure you have filled in your Full Name');
					$('#adultLastName'+i).focus(); return false;
				}
				if( !(checkPhone($('#adultPhone'+i).val())) ){
					alert('Please ensure you have filled in your Phone Number, including your area code.');
					$('#adultPhone'+i).focus(); return false;
				}
			}
		}
		for(i=1;i<=numChildren;i++){
			if($('#childTravellerID'+i).val()  == ""){ 
				if($('#childFirstName'+i).val()  == ""){
					alert('If you are not using a Traveller ID, please ensure you have filled in your Full Name');
					$('#childFirstName'+i).focus(); return false;
				}
				if($('#childLastName'+i).val()  == ""){
					alert('If you are not using a Traveller ID, please ensure you have filled in your Full Name');
					$('#childLastName'+i).focus(); return false;
				}
				if( !(checkPhone($('#childPhone'+i).val())) ){
					alert('Please ensure you have filled in your Phone Number');
					$('#childPhone'+i).focus(); return false;
				}
			}
		}
		

		// validation good. get on with it
		$('input[type="button"]').attr('disabled','disabled');		
		showLoading();
		
		var dataArray = $('#f').serializeArray();
		$.post( 'handler.rex.php?action=handleCreateBooking', dataArray,  function(data) {
			// reset Number Icons
			$('#booking_steps li').removeClass('active');
			$('#booking_step_4').addClass('active');			
			
			doneLoading();					
			$('#form_container').empty().append(data);			
		});

		// page tracking
		//pageTracker._trackPageview('/booking/select_your_seats');
	}
	/*
	function handleSeatAssignment(){
		
		// first, check for the same seats assigned to different passengers..
		var seats = new Array();
		var returnSeats = new Array();
		$('form select[name^=seatSelection] option:selected').each(function(){ 
			seats.push($(this).val() );
		});
		$('form select[name^=returnSeatSelection] option:selected').each(function(){ 
			returnSeats.push($(this).val() );
		});

		
		if(checkForDuplicateSeats(seats) || checkForDuplicateSeats(returnSeats)){
			alert('Please ensure that passengers do not occupy the same seat.'); return false;			
		}
		else{
			$('input[type="button"]').attr('disabled','disabled');		
			showLoading();
			
			var dataArray = $('#f').serializeArray();
			$.post( 'handler.rex.php?action=handleSeatAssignment', dataArray,  function(data) {
				// reset Number Icons
				$('#booking_steps li').removeClass('active');
				$('#booking_step_5').addClass('active');		
				
				doneLoading();					
				$('#form_container').empty().append(data);			
			});

			// page tracking
			//pageTracker._trackPageview('/booking/complete_your_reservation');
		} 
	}
	*/
	function handleSeatAssignment(){
		// make sure that a seat is selected
		var noSeatSelect = false;
		$('form select[name^=seatSelection],form select[name^=returnSeatSelection]').each(function(){
			if($(this).find(' option:selected').length == 0){
				noSeatSelect = true;
			}
		});
		
		// first, check for the same seats assigned to different passengers..
		var seats = new Array();
		var returnSeats = new Array();
		$('form select[name^=seatSelection] option:selected').each(function(){ 
			seats.push($(this).val() );
		});
		$('form select[name^=returnSeatSelection] option:selected').each(function(){ 
			returnSeats.push($(this).val() );
		});

		if(noSeatSelect){
			alert('You must select a seat for each leg of your trip.\n\nIf there are no seats available, please Search Again');
		}else if(checkForDuplicateSeats(seats) || checkForDuplicateSeats(returnSeats)){
			alert('Please ensure that passengers do not occupy the same seat.');
			return false;			
		}else{
			$('input[type="button"]').attr('disabled','disabled');		
			showLoading();
			
			var dataArray = $('#f').serializeArray();
			$.post( 'handler.rex.php?action=handleSeatAssignment', dataArray,  function(data) {
				// reset Number Icons
				$('#booking_steps li').removeClass('active');
				$('#booking_step_5').addClass('active');		
				
				doneLoading();					
				$('#form_container').empty().append(data);			
			});

			// page tracking
			//pageTracker._trackPageview('/booking/complete_your_reservation');
		} 
	}	
	function checkForDuplicateSeats(options){
		var values = new Array(), duplicateSeats = false;
		$.each(options, function(index, value) {
			if( $.inArray( value, values ) > -1 ){
				duplicateSeats = true;
			}else{
				values.push( value );
			}
		});
		return duplicateSeats;
	}
	
	function handleConfirmBooking(){
		//$('input[type="button"]').attr('disabled','disabled');		
		showLoading();
		
		var dataArray = $('#f').serializeArray();
		$.post( 'handler.rex.php?action=handleConfirmBooking', dataArray,  function(data) {
			// reset Number Icons
			$('#booking_steps li').removeClass('active');
			$('#booking_step_6').addClass('active');		
			
			$('#form_container').empty().append(data);
			
			startPaymentPage();				
	
		});

		// page tracking
		//pageTracker._trackPageview('/booking/confirm_your_reservation');
	}
	function startPaymentPage(){
		
		doneLoading();
		
		setTimeout("cancelBookingTimeout()", 600000)// cancel booking if user has not entered credit card in 10 minutes
		//setTimeout("cancelBookingTimeout()", 5000)// TEST cancel booking if user has not entered credit card in 5 seconds 
	}
		function cancelBookingTimeout(){
			if($('#success').length > 0){
				handleCancelBooking('Session Timeout - extended period of inactivity'); 			// cancel booking
			}
		}
	function handlePayment(){
	
		// Client side form validation for CC
		if($('#cardHolder').val() == ""){alert('Please enter your Name on Card');return false;}
		if($('#cardNumber').val() == ""){alert('Please enter your Credit Card Number');return false;}
		//if($('#cardSecurity').val() == ""){alert('Please enter your CVD/CVS Number');return false;}
	
		if($('#billingFirstName').length){ // Validate the Customer name combo for Anonymous Customers
			if($('#billingFirstName').val() == ""){alert('Please enter your Billing First Name');return false;}
			if($('#billingLastName').val() == ""){alert('Please enter your Billing Last Name');return false;}
			if(!(checkPhone($('#billingPhone').val()))){alert('Please enter your Billing Phone Number');return false;}
			if(!(checkEmail($('#billingEmail').val()))){alert('Please enter a valid Email address');return false;}
			if($('#billingEmail').val() != $('#confirmBillingEmail').val()){alert('Email addresses do not match');return false;}
		}else{
			if(!(checkEmail($('#billingEmail').val()))){alert('Please enter a valid Email address');return false;}
			if($('#billingEmail').val() != $('#confirmBillingEmail').val()){alert('Email addresses do not match');return false;}
		}
		// disable button to avoid multiple submissions
		$('#btn_submit_payment').attr('disabled','disabled');
		$('#btn_cancel').attr('disabled','disabled');
		
		showLoading();
		var dataArray = $('#f').serializeArray();
		$.post( 'handler.rex.php?action=handlePayment', dataArray,  function(data) {			
			$('#booking_steps li').removeClass('active');
			$('#form_container').empty().append(data);	
			doneLoading();					
		});

		// page tracking
		//pageTracker._trackPageview('/booking/process_payment_now');
	}
	
	function handleCancelBooking(strReason){
	
		$('input[type="button"]').attr('disabled','disabled');
		
		var cancelParams = {
			orderID : $('#orderID').val() ,
			orderItemID : $('#orderItemID').val() ,
			orderItemIDReturn : $('#orderItemIDReturn').val(), 
			reason : strReason
		}
		$.post( 'handler.rex.php?action=handleCancelBooking', cancelParams,  function(data) {			
			$('#form_container').empty();
			drawSelectTripOptionsForm();	
			doneLoading();					
		});
		// page tracking
		//pageTracker._trackPageview('/booking/cancel_booking');
	}
	
	
	function toggleFormInputs(action){
		$('select').each(function(){
			$(this).css('display',action);
		});
	}
	
	function togglePopWin(e){
		if($('#'+e).is(":hidden")){ 
			$('#'+e).show();
			toggleFormInputs('none');// hide all the select boxes
		}else{ 
			$('#'+e).hide();
			toggleFormInputs('inline');// show all the select boxes
		}
	}
	function setLastElementTouched(el){
		lastElementTouched = $('#'+el);
	}
	function setSeatSelector(val){
		$(lastElementTouched).val(val);
	}
	
	function isDateInPast(d){

		var today = new Date(); 
	   	var myDate = new Date(); 
		var parts = d.split("-");
		myDate.setFullYear(parts[0]);
		myDate.setMonth(parts[1]-1);
		myDate.setDate(parts[2]);

		//alert('today: '+today.toString());
		//alert('myDate: '+myDate.toString());

	   	if(myDate < today){
	   		return true;
	   	}else{
			return false;
	   	}
	}
	function isReturnBeforeDeparture(d,r){
		var departureDate = new Date(); 
	   	var returnDate = new Date(); 
		
		var parts1 = d.split("-");
		departureDate.setFullYear(parts1[0]);
		departureDate.setMonth(parts1[1]-1);
		departureDate.setDate(parts1[2]);

		var parts2 = r.split("-");
		returnDate.setFullYear(parts2[0]);
		returnDate.setMonth(parts2[1]-1);
		returnDate.setDate(parts2[2]);

	   	if(departureDate > returnDate){
	   		return true;
	   	}else{
			return false;
	   	}
	
	}

	function setTripWithinTime(t,el){
		$(el).value = t;
	}
	function padNum(str){
		str = '00'+str;
		return str.substring(str.length-2,str.length);
	}
	
	function doAgree(obj){
		if(obj.checked){
			$('#btn_check_availability').removeAttr('disabled');
		}else{
			$('#btn_check_availability').attr('disabled','disabled');
		}
	}
