// when to doc is ready attach events
$(document).ready( function(){
	// bind ajaxForm to form if it exists.
	if(document.checkout){
		// set form options
		var frmOptions = { 
			beforeSubmit: validateUpgrade, 							// pre-submit 	callahead 
	        success:      function(data){upgradeComplete(data)}  	// post-submit 	callback 
	    }
		$('#checkout').ajaxForm(frmOptions); 	
	}

	// bind mousover,mousout
	$("#button_processUpgrade").hover(function(){$(this).attr("src", "/images/processUpgrade_on.png")}, function(){$(this).attr("src", "/images/processUpgrade.png")} )
	$("#button_cancelUpgrade").hover(function(){$(this).attr("src", "/images/cancelUpgrade_on.png")}, function(){$(this).attr("src", "/images/cancelUpgrade.png")} )

});

// This function will validate the rebooking Reference ID.
function validateRebook(frm) {
	var f = frm.BookingReference.value.trim();
	if(f.length == 0) {
		alert("Please enter your Booking Reference ID.")
		frm.BookingReference.focus();
		return false;
	}
}

// This function will ensure Voucher ID's are numeric and that authcodes are entered.
// It also checks that at least one voucher id and authcode are passed for booking. 
function validateBook(frm) {
	var oneValid 	= false;
	var urlString 	= new Array();
	var vidArray	= new Array();	// default array of voucher id's
	var vidFound	= false;		// default var for if a voucher id was already found in the vidArray
	
	for(var i=1;i<=8;i++) {
		var f = "document.book.VoucherID_" + i;
			f = eval(f).value.trim();
		var g = "document.book.AuthCode_" + i;
			g = eval(g).value.trim();
		if(!isNaN(f) && f.length > 0) {
			if(g.length) {
				oneValid = true;
				urlString[urlString.length] = f + "|" + g; // Add this item to the urlString array.
				
				// now loop through vidArray and determine if this vid is already used.
				for(var a=0;a<vidArray.length;a++) {
					if(vidArray[a].trim() == f) { 
						vidFound = true;
					}
				}
				// if this item isn't already in the array.
				if(!vidFound) vidArray[vidArray.length] = f; 
				// if this voucher ID was already in the array, send alert and cancel processing.
				else { 
					alert("You have entered Voucher ID: " + f + " more than once.\n\nYou can only use one voucher per passenger.");
					eval("document.book.VoucherID_" + i).value 	= "";
					eval("document.book.AuthCode_" + i).value 	= "";
					return false;
				}
			}
			else {
				alert("Please enter the AuthCode for Voucher ID #" + i);
				return false;
			}
		}
	}
	
	
	if(oneValid) {
		// Send voucher_id's and authcodes to balloon_rides_validateAuth.cfm to ensure authcode is valid.
		document.book.submitBut.value = "Validating AuthCodes..."; // Change submit button text
		document.book.submitBut.disabled = true; // Disable submit button while validation occurs.
		validateAuth(urlString.join(","))	
		return false;
	}
	else {
		alert("Please enter at least one Voucher ID and AuthCode to proceed.");
		return false;
	}
}



// Function for making sure that at least one voucher has been selected for booking.
// Checks for expired and expended vouchers and a balance owing.
function validateBooking(frm,act) {
	
	var expiredVouchers = new Array();
	var expendedVouchers = new Array();
	var oneVoucherCheck = false;
	var oneCantBook		= false;
	var canCancel		= false;
	var voucherIDs		= "";
	var allowSend 		= false;
	var flightTypes 	= new Array();
	var balanceOwing	= new Array();
	var totalOwing		= 0;
	var orders			= new Array();
	var cities			= new Array();
	var sweethearts		= 0;
	var checkedVouchers = 0;
	
	
	// If there was only one voucher in order check the box and proceed.	
	if(frm.voucher_ID) {
		frm.voucher_ID.checked = true;
	}
	
	// loop through elements
	for(i=0; i<frm.elements.length; i++) {
		// If the name is voucher_ID
		if(frm.elements[i].name == "voucher_ID") {
			// If the checkbox is checked...
			if(frm.elements[i].checked) {
				// split the checkbox value [0] = voucher_ID, [1] = yes/no expired
				var thisVal = frm.elements[i].value.split("|");
				// If this voucher is expired add it to array.
				if (thisVal[1]>0) {
					expiredVouchers[expiredVouchers.length] = thisVal[0] + "|" + (getAge(thisVal[2].split("/")[0],thisVal[2].split("/")[1],thisVal[2].split("/")[2])+1);
				}
				// If this voucher is expended add it to array.
				if (thisVal[3]>0) {
					expendedVouchers[expendedVouchers.length] = thisVal[3];
				}
				// Set value that shows at least one original voucher is checked.
				if(frm.elements[i].name == "voucher_ID") {
					oneVoucherCheck = true;
				}
				
				// Add flight type category info to array, if it's not already present.
				var catPresent = false;
				for(var a=0;a<flightTypes.length;a++) {
					if(flightTypes[a] == thisVal[4] + "|" + thisVal[5] + "|" + thisVal[6]) {
						catPresent = true;
					}
				}
				// If this flight type category isn't in the array add it now.
				if(!catPresent) flightTypes[flightTypes.length] = thisVal[4] + "|" + thisVal[5] + "|" + thisVal[6];
				
				// Add this order id to orders array
				var orderPresent = false;
				for(var a=0;a<orders.length;a++) {
					if(orders[a] == thisVal[7]) {
						orderPresent = true;
					}
				}
				// If this order id isn't present then add it to the array.
				if(!orderPresent) orders[orders.length] = thisVal[7];


				// Add this city to city array
				var cityPresent = false;
				for(var a=0;a<cities.length;a++) {
					if(cities[a] == thisVal[8]) {
						cityPresent = true;
					}
				}
				// If this order id isn't present then add it to the array.
				if(!cityPresent) cities[cities.length] = thisVal[8];
				
				//If canBook == 0 set oneCantBook to true. This is if one voucher has a flight booked in the next 72 hours.
				if(thisVal[10] == 0) oneCantBook = true;
				
				//If they have a current booking set canCancel = true
				if(thisVal[12] == 1) canCancel = true;
				
				// If this voucher is a sweetheart increment the sweethearts var.
				// If all checked vouchers are sweethearts then don't allow booking online.
				if(thisVal[6] == 1) sweethearts++;
				
				// Increment checkedVouchers var. This counts how many vouchers are checked for comparison against sweethearts var.
				checkedVouchers++
				
			}
			// create voucherID's list.
			voucherIDs += ((voucherIDs.length)?(","):("")) + frm.elements[i].value;
		}
	}

	// If sweethearts var is equal to vouchersIDs.length then all checked vouchers are sweethearts.
	// If so then alert and tell user they must call the office for this booking.
	if(checkedVouchers == sweethearts) {
		alert("You cannot schedule sweetheart flights online.\n\nPlease contact our office to schedule your flight.");
		return false;
	}
	
	
	// Make sure the vouchers aren't from different cities.
	if (cities.length > 1 && act == "book") {
		alert("You can only book a flight with vouchers for the same city.")
		return false;
	}

	// Make sure the vouchers aren't expended, if they are tell them they can't book a flight.
	if (expendedVouchers.length) {
		alert("You have expended vouchers selected.\nYou cannot book a flight with an expended voucher.\n\nUnselect the expended voucher(s) to continue with\nthis booking or use Edit Vouchers to reactivate them.")
		return false;
	}
	
	// If one of the chosen vouchers has a flight booked in the next 72 hours alert and return false;
	if (oneCantBook) {
		if(act == "book") {
			alert("Alert: Booking can not proceed!\n\nOne or more of the vouchers selected has a\nflight scheduled within the next 72 hours.\n\nYou cannot cancel or reschedule a flight\nonline when you have a booking that is\nless than 72 hours away.\n\nPlease contact our office to make this change.");
		}
		else {
			alert("One or more of the vouchers selected has a\nflight scheduled within the next 72 hours.\n\nYou cannot cancel a flight online when you have a\nbooking that is less than 72 hours away.\n\nPlease contact our office to make this change.");
		}
		return false;
	}
	
	
	// If there are linked vouchers that are selected and the flight types are different display message.
	// If there is only one item in the array all selected flight types are the same, proceed.
	if(flightTypes.length > 1 && act == "book") {
		var thisFlightType = getLowestFlightType(flightTypes);
		var ft 	= thisFlightType.split("|");
		var tmsg = "You are booking a flight with vouchers that are valid\nfor different flight types.\n\nThis booking will only be valid for:\n\n";
			tmsg += ft[0] + " - " + ((ft[1]=="AM")?"Morning":"Evening") + " flights.\n\nClick OK to proceed.";

		// Ask person if they wish to continue.
		var proceed = confirm(tmsg);
		// If they clicked cancel, return false;
		if(!proceed) return false;
		// Set the flight type form variable.
		frm.lowFlightType.value = thisFlightType;
	}

	// Loop through orders and if there is a balanceOwing then add it to the balanceOwing array.
	if(act == "book") { // Only run this if they are trying to book.
		var theseOwing = frm.balanceOwing.value.split(",");
		for(var i=0;i<theseOwing.length;i++) {
			if(theseOwing[i].split("|")[1] > 0) {
				balanceOwing[balanceOwing.length] = theseOwing[i];
				// loop through order id's of checked vouchers.
				// if this order id is check add it's balance owing to totalOwing.
				for(var a=0;a<orders.length;a++) {
					if(orders[a] == theseOwing[i].split("|")[0]) {
						totalOwing = totalOwing + theseOwing[i].split("|")[1]*1;
					}
				}
			}
		}
	}

/*************************************************************************************************************/
/**** Generate confirmation message if vouchers are expired or if there is a balanceOwing on the account. ****/
/*************************************************************************************************************/

	// set frm.action based on whether act is book or cancel.
	if (act == "book") {
		frm.action = "/schedule/balloon_rides_book2.cfm";
	}
	else {
		frm.action = "/schedule/balloon_rides_cancel.cfm"
		if(!canCancel) {
			alert("None of the vouchers selected have a booked flight.");
			return false;
		}
		if(!confirm("Are you sure you want to cancel these bookings?")) return false;
	}
	
	// finally, see if they owe money, if so go immediate to payment.
	if ((expiredVouchers.length || totalOwing > 0) && act == "book") {
		// set the location to payment and go immediately
		frm.action = "https://www.sundanceballoons.com/schedule/payment.cfm";
		frm.submit(); 
				
		//alert("Balance Owing. This booking cannot proceed. Please contact our office.");
		//return false;
	}


	
	// Make sure they've checked an item, if there's only one voucher in order you don't need to check the box.
	if (oneVoucherCheck || allowSend) {
		frm.submit();
	}
	else {
		if (voucherIDs.split(",").length > 1) {
			alert("You must select at least one voucher from this order first.");
			return false;
		}
	}
}


// Function for determining the lowest value flight type of all vouchers checked.
function getLowestFlightType(flightTypes) {

// If there are linked vouchers that are selected and the flight types are different display message.
// If there is only one item in the array all selected flight types are the same, proceed.

	// create vars to hold different flight types.
	var hasTwoPerson 	= false;
	var hasGroup 		= false;
	var hasWeekdayAM	= false;
	var hasWeekdayPM	= false;
	var hasWeekendAM 	= false;
	var hasWeekendPM	= false;

	//Now you need to determine what the least value flight type is.
	//Loop through flight types and set vars for evaluation.
	for(var b=0;b<flightTypes.length;b++) {

		switch(flightTypes[b].toLowerCase()) {

			// If this is a weekdayAM, non-sweetheart.
			case "weekday|am|0" :
				hasGroup 		= true;
				hasWeekdayAM 	= true;
			break;
		
			// If this is a weekdayAM, sweetheart.
			case "weekday|am|1" :
				hasTwoPerson 	= true;
				hasWeekdayAM 	= true;
			break;
		
			// If this is a weekdayPM, non-sweetheart.
			case "weekday|pm|0" :
				hasGroup 		= true;
				hasWeekdayPM 	= true;
			break;
		
			// If this is a weekdayPM, sweetheart.
			case "weekday|pm|1" :
				hasTwoPerson 	= true;
				hasWeekdayPM 	= true;
			break;
		
			// If this is a weekendAM, non-sweetheart.
			case "weekend|am|0" :
				hasGroup	 	= true;
				hasWeekendAM 	= true;
			break;
		
			// If this is a weekendAM, sweetheart.
			case "weekend|am|1" :
				hasTwoPerson 	= true;
				hasWeekendAM 	= true;
			break;
		
			// If this is a weekendPM, non-sweetheart.
			case "weekend|pm|0" :
				hasGroup 		= true;
				hasWeekendPM 	= true;
			break;
		
			// If this is a weekendPM, sweetheart.
			case "weekend|pm|1" :
				hasTwoPerson	= true;
				hasWeekendPM 	= true;
			break;
		}
	}

	// Set some vars to hold the lowest value flight.
	var thisFlight 		= "";
	
	if(hasGroup && hasWeekdayAM) {		// If this is a weekdayAM, non-sweetheart.
		thisFlight = "Weekday|AM|0";
		return thisFlight;
	}
	if(hasTwoPerson && hasWeekdayAM) {	// If this is a weekdayAM, sweetheart.
		thisFlight = "Weekday|AM|1";
		return thisFlight;
	}
	if(hasGroup && hasWeekdayPM) {		// If this is a weekdayPM, non-sweetheart.
		thisFlight = "Weekday|PM|0";
		return thisFlight;
	}
	if(hasTwoPerson && hasWeekdayPM) {		// If this is a weekdayPM, sweetheart.
		thisFlight = "Weekday|PM|1";
		return thisFlight;
	}
	if(hasGroup && hasWeekendAM) {		// If this is a weekendAM, non-sweetheart.
		thisFlight = "Weekend|AM|0";
		return thisFlight;
	}
	if(hasTwoPerson && hasWeekendAM) {	// If this is a weekendAM, sweetheart.
		thisFlight = "Weekend|AM|1";
		return thisFlight;
	}
		
	if(hasGroup && hasWeekendPM) {		// If this is a weekendPM, non-sweetheart.
		thisFlight = "Weekend|PM|0";
		return thisFlight;
	}
	if(hasTwoPerson && hasWeekendPM) {	// If this is a weekendPM, sweetheart.
		thisFlight = "Weekend|PM|1";
		return thisFlight;
	}
}


// Function for populating passenger info.
function popPax(CIDsplit,ID) {
	
	var xCID 	= CIDsplit.split("|");
	var CID 	= xCID[1];
	var popAct 	= xCID[0];

	var x = document.doPax;
	
	//If popAct = -1 copy info from the specified passenger.
	if (popAct == -1) {
	
		eval("x.FirstName_" + ID).value = "";
		eval("x.LastName_" + ID).value 	= eval("x.LastName_" + CID).value;
		eval("x.Company_" + ID).value 	= eval("x.Company_" + CID).value;
		eval("x.Address1_" + ID).value	= eval("x.Address1_" + CID).value;
		eval("x.Address2_" + ID).value	= eval("x.Address2_" + CID).value;
		eval("x.City_" + ID).value		= eval("x.City_" + CID).value;
		
	
		//Loop through country until you have the right Country_ID;
		var l = eval("document.doPax.Country_ID_" + ID);
		if (eval("x.Country_ID_" + CID).value>0){ // Check to make sure the Country_ID is defined.
	
			for(var a=0;a<l.options.length;a++) {
				if (l.options[a].value == eval("x.Country_ID_" + CID).value) {
					l.options[a].selected = true;
				}
			}
		}
		else { l.options[0].selected = true; }
		
		
		// Set visibility of region/prov/state field.
		var b = "state0_" + ID;
		var c = "state1_" + ID;
		var d = "state2_" + ID;
		var e = eval("document.doPax.Country_ID_" + ID);
	
		countryPick(e,b,c,d,'document.doPax');
	
		//Loop through state until you have the right State_ID;
		switch (eval("x.Country_ID_" + ID).value*1) {
			case 1:
				var l = eval("document.doPax.state1_" + ID);
				var k = eval("document.doPax.state1_" + CID).selectedIndex;
				l.options[k].selected = true;
			break;
		
			case 2:
				var l = eval("document.doPax.state2_" + ID);
				var k = eval("document.doPax.state2_" + CID).selectedIndex;
				l.options[k].selected = true;
			break;
			
			default :
				// Set value of region field.
				var l = eval("document.doPax.state0_" + ID);
				l.value = eval("document.doPax.state0_" + CID).value;
			break;
		}
	
		eval("x.Zip_" + ID).value			= eval("x.Zip_" + CID).value;
		eval("x.HomePhone_" + ID).value		= eval("x.HomePhone_" + CID).value;
		//eval("x.WorkPhone_" + ID).value		= eval("x.WorkPhone_" + CID).value;
		//eval("x.WorkExt_" + ID).value		= eval("x.WorkExt_" + CID).value;
		//eval("x.CellPhone_" + ID).value		= eval("x.CellPhone_" + CID).value;
		//eval("x.FaxPhone_" + ID).value		= eval("x.FaxPhone_" + CID).value;
		//eval("x.AltPhone_" + ID).value		= eval("x.AltPhone_" + CID).value;
		//eval("x.AltExt_" + ID).value		= eval("x.AltExt_" + CID).value;
		eval("x.Customer_ID_" + ID).value	= 0;	
		
		eval("x.FirstName_" + ID).focus();
	}

	// If this is a customer search, display search window.
	else if (popAct == -2) {
		setWindows(ID);
	}
	
	//If popAct = -3 copy Address info from the purchaser or purchasee.
	if (popAct == -3) {
	
		/*
		00 = Customer_FirstName			01 = Customer_LastName			02 = Customer_Company
		03 = Customer_Address1			04 = Customer_Address2			05 = Customer_City
		06 = Customer_State				07 = Customer_StateID			08 = Customer_CountryID
		09 = Customer_Zip				10 = Customer_HomePhone			11 = Customer_WorkPhone
		12 = Customer_WorkExt			13 = Customer_CellPhone			14 = Customer_FaxPhone
		15 = Customer_AltPhone			16 = Customer_AltExt			17 = Customer_Email
		18 = Customer_Birthday */
		
		var i = eval("Customer_" + CID);

		eval("x.FirstName_" + ID).value = "";
		eval("x.LastName_" + ID).value 	= unescape(i[1]);;
		eval("x.Company_" + ID).value 	= "";
		eval("x.Address1_" + ID).value	= unescape(i[3]);
		eval("x.Address2_" + ID).value	= unescape(i[4]);
		eval("x.City_" + ID).value		= unescape(i[5]);
		
	
		//Loop through country until you have the right Country_ID;
		var l = eval("document.doPax.Country_ID_" + ID);
		if (i[8]>0){ // Check to make sure the Country_ID is defined.
	
			for(var a=0;a<l.options.length;a++) {
				if (l.options[a].value == i[8]) {
					l.options[a].selected = true;
				}
			}
		}
		else { l.options[0].selected = true; }
		
		
		// Set visibility of region/prov/state field.
		var b = "state0_" + ID;
		var c = "state1_" + ID;
		var d = "state2_" + ID;
		var e = eval("document.doPax.Country_ID_" + ID);
	
		countryPick(e,b,c,d,'document.doPax');
	
		//Loop through state until you have the right State_ID;
		switch (i[8]*1) {
			case 1:
				var l = eval("document.doPax.state1_" + ID);
				for(var a=0;a<l.options.length;a++) {
					if (l.options[a].value.split("|")[0] == i[7]) {
						l.options[a].selected = true;
					}
				}
			break;
		
			case 2:
				var l = eval("document.doPax.state2_" + ID);
				for(var a=0;a<l.options.length;a++) {
					if (l.options[a].value.split("|")[0] == i[7]) {
						l.options[a].selected = true;
					}
				}
			break;
			
			default :
				// Set value of region field.
				var l = eval("document.doPax.state0_" + ID);
				l = i[6];
			break;
		}
	
		eval("x.Zip_" + ID).value			= unescape(i[9]);

		eval("x.HomePhone_" + ID).value		= unescape(i[10]);
		eval("x.WorkPhone_" + ID).value		= "";
		eval("x.WorkExt_" + ID).value		= "";
		eval("x.CellPhone_" + ID).value		= "";
		eval("x.FaxPhone_" + ID).value		= "";
		eval("x.AltPhone_" + ID).value		= "";
		eval("x.AltExt_" + ID).value		= "";
		eval("x.Email_" + ID).value			= "";
		eval("x.DOB_" + ID).value			= "";
		eval("x.Age_" + ID).value			= "";
		eval("x.Weight_" + ID).value		= "";
		
		eval("x.Customer_ID_" + ID).value	= 0;	
		
		eval("x.FirstName_" + ID).focus();
	}


	// Else if this is a call to set purchaser or purchasee to pax. 
	else if (popAct >= 0) {
	
		
		var i = eval("Customer_" + CID);
	
	
		// Check to make sure this Customer_ID isn't already assigned to a passenger.
		for (var a=1;a<=x.PaxNum.value;a++) {
			// Set b = customer ID of current passenger being searched.
			var b = eval("x.Customer_ID_" + a + ".value");
			// Check to see if the customer ID is already used on another passenger.
			if(b > 0 && b == CID && a != ID) {
				// If this customer ID is already used throw message and reset drop down.
				alert("You cannot set the same customer as a passenger more than once.");
				var c = eval("x.drop_" + ID);
				c.selectedIndex = 0;
				return false;
			}
		}
	
		/*
		00 = Customer_FirstName			01 = Customer_LastName			02 = Customer_Company
		03 = Customer_Address1			04 = Customer_Address2			05 = Customer_City
		06 = Customer_State				07 = Customer_StateID			08 = Customer_CountryID
		09 = Customer_Zip				10 = Customer_HomePhone			11 = Customer_WorkPhone
		12 = Customer_WorkExt			13 = Customer_CellPhone			14 = Customer_FaxPhone
		15 = Customer_AltPhone			16 = Customer_AltExt			17 = Customer_Email
		18 = Customer_Birthday */
		
		eval("x.FirstName_" + ID).value = unescape(i[0]);
		eval("x.LastName_" + ID).value 	= unescape(i[1]);
		eval("x.Company_" + ID).value 	= unescape(i[2]);
		eval("x.Address1_" + ID).value	= unescape(i[3]);
		eval("x.Address2_" + ID).value	= unescape(i[4]);
		eval("x.City_" + ID).value		= unescape(i[5]);
		
	
		//Loop through country until you have the right Country_ID;
		var l = eval("document.doPax.Country_ID_" + ID);
		if (i[8]>0){ // Check to make sure the Country_ID is defined.
	
			for(var a=0;a<l.options.length;a++) {
				if (l.options[a].value == i[8]) {
					l.options[a].selected = true;
				}
			}
		}
		else { l.options[0].selected = true; }
		
		
		// Set visibility of region/prov/state field.
		var b = "state0_" + ID;
		var c = "state1_" + ID;
		var d = "state2_" + ID;
		var e = eval("document.doPax.Country_ID_" + ID);
	
		countryPick(e,b,c,d,'document.doPax');
	
		//Loop through state until you have the right State_ID;
		switch (i[8]*1) {
			case 1:
				var l = eval("document.doPax.state1_" + ID);
				for(var a=0;a<l.options.length;a++) {
					if (l.options[a].value.split("|")[0] == i[7]) {
						l.options[a].selected = true;
					}
				}
			break;
		
			case 2:
				var l = eval("document.doPax.state2_" + ID);
				for(var a=0;a<l.options.length;a++) {
					if (l.options[a].value.split("|")[0] == i[7]) {
						l.options[a].selected = true;
					}
				}
			break;
			
			default :
				// Set value of region field.
				var l = eval("document.doPax.state0_" + ID);
				l = i[6];
			break;
		}
	
		eval("x.Zip_" + ID).value			= unescape(i[9]);
		eval("x.HomePhone_" + ID).value		= unescape(i[10]);
		eval("x.WorkPhone_" + ID).value		= unescape(i[11]);
		eval("x.WorkExt_" + ID).value		= unescape(i[12]);
		eval("x.CellPhone_" + ID).value		= unescape(i[13]);
		eval("x.FaxPhone_" + ID).value		= unescape(i[14]);
		eval("x.AltPhone_" + ID).value		= unescape(i[15]);
		eval("x.AltExt_" + ID).value		= unescape(i[16]);
		eval("x.Email_" + ID).value			= unescape(i[17]);
		eval("x.DOB_" + ID).value			= unescape(i[18]);
		eval("x.Age_" + ID).value			= i[19];
		eval("x.Weight_" + ID).value		= "";
		eval("x.Customer_ID_" + ID).value	= CID;
	}
}



// This function will validate the information on the passengers page.
function validatePax(s1) {

	var hasAdult 	= false;
	var needsAdult 	= false;
	var hasEmail	= false; // Param for if at least one email is specified.
	var maxWeight 	= 250;	 // Param for the maximum weight a passenger can be.
	var overWeight 	= false; // Param for if a pax is over maxWeight. If they are don't allow booking.
	
	// loop through all passengers.
	for(i=1;i<=s1.PaxNum.value;i++) {
	
		// Check a Passenger FirstName is entered.
		if(eval("s1.FirstName_" + i + ".value.trim().length") == 0) {
			alert("You must enter Passenger #" + i + "'s First Name.");
			eval("s1.FirstName_" + i + ".focus()");
			return false;
		}
		// Check a Passenger LastName is entered.
		if(eval("s1.LastName_" + i + ".value.trim().length") == 0) {
			alert("You must enter Passenger #" + i + "'s Last Name.");
			eval("s1.LastName_" + i + ".focus()");
			return false;
		}
		// Check a Passenger Address1 is entered.	
		if(eval("s1.Address1_" + i + ".value.trim().length") == 0) {
			alert("You must enter Passenger #" + i + "'s Address.");
			eval("s1.Address1_" + i + ".focus()");
			return false;
		}
		// Check a Passenger City is entered.
		if(eval("s1.City_" + i + ".value.trim().length") == 0) {
			alert("You must enter Passenger #" + i + "'s City.");
			eval("s1.City_" + i + ".focus()");
			return false;
		}
		// Check a Passenger Country is selected.	
		if(!eval("s1.Country_ID_" + i + ".value")>0) {
			alert("You must choose Passenger #" + i + "'s Country.");
			eval("s1.Country_ID_" + i + ".focus()");
			return false;
		}
		// Check if state0 is visible and if so check a value is entered.
		if(document.getElementById('state0_' + i).style.display != 'none' && !eval("s1.state0_" + i + ".value.trim().length")>0) {
			alert("You must enter Passenger #" + i + "'s Region.");
			eval("s1.state0_" + i + ".focus()");
			return false;
		}
		// Check if state1 is visible and if so check an option is selected.
		if(document.getElementById('state1_' + i).style.display != 'none' && !eval("s1.state1_" + i + ".value")>0) {
			alert("You must enter Passenger #" + i + "'s Province.");
			eval("s1.state1_" + i + ".focus()");
			return false;
		}
		// Check if state2 is visible and if so check an option is selected.
		if(document.getElementById('state2_' + i).style.display != 'none' && !eval("s1.state2_" + i + ".value")>0) {
			alert("You must enter Passenger #" + i + "'s State.");
			eval("s1.state2_" + i + ".focus()");
			return false;
		}
		// Check a Passenger Zip code is entered.
		if(eval("s1.Zip_" + i + ".value.trim().length") == 0) {
			alert("You must enter Passenger #" + i + "'s Postal/Zip Code.");
			eval("s1.Zip_" + i + ".focus()");
			return false;
		}
		// Check if state1 is visible and if so, ensure that a proper postal code is entered.	
		if(document.getElementById('state1_' + i).style.display != 'none') {
			var valZip = isPostal(eval("s1.Zip_" + i + ".value"));
			if (!valZip) {
				alert("You must enter a valid Canadian Postal Code for Passenger #" + i + ".");
				eval("s1.Zip_" + i + ".focus()");
				return false;
			}
		}	
		// Check if state2 is visible and if so, ensure that a proper zip code is entered.	
		if(document.getElementById('state2_' + i).style.display != 'none') {
			var valZip = isZip(eval("s1.Zip_" + i + ".value"));
			if (!valZip) {
				alert("You must enter a valid U.S. Zip Code for Passenger #" + i + ".");
				eval("s1.Zip_" + i + ".focus()");
				return false;
			}
		}	
		// Check a Passenger HomePhone is entered.
		if(eval("s1.HomePhone_" + i + ".value.trim().length") == 0) {
			alert("You must enter Passenger #" + i + "'s Home Phone.");
			eval("s1.HomePhone_" + i + ".focus()");
			return false;
		}
		// Check if state1 or state2 is visible and if so, ensure that a proper HomePhone is entered.
		if(document.getElementById('state2_' + i).style.display != 'none' || document.getElementById('state1_' + i).style.display != 'none') {
			if (eval("s1.HomePhone_" + i + ".value.trim().length") != 10) {
				alert("You must enter a valid 10 digit Home Phone Number for Passenger #" + i + ".");
				eval("s1.HomePhone_" + i + ".focus()");
				return false;
			}
		}	
		
		// If they have entered an email then set hasEmail = true
		if(eval("s1.Email_" + i + ".value.trim().length") > 0) hasEmail = true;
		
		
		
		// Check that they've filled in an additional number.		
		// **** Removed checking for an additional number as per Barry's request.
		// **** Sept 25th, 2007
		//if(eval("s1.WorkPhone_" + i + ".value") == "" && eval("s1.CellPhone_" + i + ".value") == "" && eval("s1.AltPhone_" + i + ".value") == "") {
		//	alert("There must be at least two phone numbers for Passenger #" + i + ".");
		//	document.location = "#" + i;
		//	return false;
		//}
		
		// Check that the age is a number and not blank.
		if(isNaN(eval("s1.Age_" + i + ".value")) || eval("s1.Age_" + i + ".value") == "") {
			alert("You must enter the age of Passenger #" + i + ".");
			eval("s1.Age_" + i + ".focus()");
			return false;
		}

		// Check that the age is greater than 10.
		if(eval("s1.Age_" + i + ".value")< 10 ) {
			alert("Passenger #" + i + " is too young to fly.\nThis booking is not allowed.");
			document.location = "#" + i;
			return false;
		}
		
		//Check to see if this is an adult.
		if(eval("s1.Age_" + i + ".value")>= 18 ) hasAdult = true;
		if(eval("s1.Age_" + i + ".value")< 16 ) needsAdult = true;

		// Check to see the weight is entered properly.		
		if(isNaN(eval("s1.Weight_" + i + ".value")) || eval("s1.Weight_" + i + ".value") == "") {
			alert("You must enter the weight of Passenger #" + i + ".");
			eval("s1.Weight_" + i + ".focus()");
			return false;
		}
		
		// Check to see the weight is entered properly.		
		if(eval("s1.Weight_" + i + ".value")<=0) {
			alert("Please enter a valid weight for Passenger #" + i + ".");
			eval("s1.Weight_" + i + ".focus()");
			return false;
		}

		// Check to see the weight of pax isn't over the maxWeight value..		
		if(eval("s1.Weight_" + i + ".value") > maxWeight) {
			overWeight = true;	
		}
		
		// if HotelPickup_#x# exists, ensure it's had a radio button checked and possibly a hotel name entered
		if(eval("s1.HotelPickup_" + i)) {
			// field exists, Application.HotelPickupEnabled must == true.
			// ensure an item was checked
			if(!eval("s1.HotelPickup_" + i)[0].checked && !eval("s1.HotelPickup_" + i)[1].checked)
			{
				alert("Please indicate if Passenger #" + i + " needs Hotel Pickup.");
				return false;
			}
			// if they chose yes, but didn't enter a hotel name...
			if(eval("s1.HotelPickup_" + i)[0].checked && eval("s1.HotelName_" + i).value.trim().length == 0)
			{
				alert("Please input Passenger #" + i + "'s Hotel Name.");
				eval("s1.HotelName_" + i + ".focus()");
				return false;
			}
		}
	}
	
	
	// Check to see the weight of pax isn't over the maxWeight value..		
	if(overWeight) {
	
		overWeightPaxNote(s1.Voucher_ID.value,maxWeight);
		alert("This booking can not be made online.\n\nPlease contact our office to make this booking.");
		return false;
	}
	
	
	// If there is no other passenger 18 or older and passenger is under 16 throw alert.
	if (needsAdult && !hasAdult) {
		alert("An adult must accompany all passengers under 16.\nThis booking is not allowed.");
		return false;
	}
	
	// If they didn't input at least one email alert and return false;
	if (!hasEmail) {
		alert("You must input an email address for at least one passenger.\n\nFlight confirmation and cancellation messages are sent via email.");
		return false;		
	}
	
	return true;

}


// This function will return available flights.
function getFlights(start,end) {
	// Set div to searching animation.
	var fDiv_HTML = "<div id=\"container\">";
		fDiv_HTML += "<table width=\"95%\" cellpadding=2 cellspacing=0 border=0 id=\"CS_Results\" style=\"margin-top:8px;\" align=\"center\" class=\"incentiveTable\">";
		fDiv_HTML += "<tr>";
		fDiv_HTML += "<td align=\"center\" style=\"padding:30px 0px 30px 0px;font-family:tahoma, arial;font-size:12px;\">";
		fDiv_HTML += "Searching Flight Registry.<br><br><img src=\"/images/ajax-loader.gif\" alt=\"\" border=\"0\"><br><br>One Moment Please.";
		fDiv_HTML += "</td>";
		fDiv_HTML += "</tr>";
		fDiv_HTML += "</table>";
		fDiv_HTML += "</div>";
	
	
	$("#fDiv").html(fDiv_HTML);

	var url="/schedule/balloon_rides_findFlights.cfm";
	
	// set url params
	url += "?voucher_ID=" + vID + "&totalPass=" + tP + "&totalWght=" + tW + "&today=" + tD + "&start=" + start + "&end=" + end + "&recPP=" + recPP;
	url += "&City_ID=" + City_ID + "&FlightDay=" + FlightDay + "&FlightTime=" + FlightTime + "&isTwoPerson=" + isTwoPerson + "&City_Name=" + City_Name;
	url += "&sid="+Math.random();
	
	$.get(url, function(result){
		// set html and attach the tool tips
		$("#fDiv").html(result).delay(0,attachToolTips); 
	});

	return false;
}

// attach fancy tooltips to upgrade buttons
function attachToolTips(){
	$(".ftUpgrade").tipTip({maxWidth:"300px"});
}


// This function is for setting which page is being viewed.
function setPage(pageAction) {

	// Hide the currently viewed page.
	$("#page" + curPage).hide();
	// set maxPage value to a var.
	var lastPage = $("#maxPage").val();
	
	// Determine what page the user is requesting.
	switch(pageAction) {
		case "first" :
			$("#page1").show();
			curPage = 1;
		break;
	
		case "prev" :
			var tPage = curPage-1;
			if(tPage > 0) curPage = tPage;
			$("#page" + curPage).show();
		break;

		case "next" :
			var tPage = curPage+1;
			if(tPage <= lastPage) curPage = tPage;
			$("#page" + curPage).show();
		break;

		case "last" :
			$("#page" + lastPage).show();
			curPage = lastPage;
		break;
	}
	
	// Set the "Now Viewing" values.
		var end = ((curPage*1) * (recPP*1));
		var start = end - (recPP-1);
		if(end > $("#records").val())
			end = $("#records").val();
	
		$("#startValue").html(start);
		$("#endValue").html(end);

}

// This function will search the pages to find out which page a submitted date is on then display it.
function jumpPage() {
	// NOTE: The date values are set as "yyyymmdd" for value comparison.

	// Create array of start dates for each page.
	var dateArray	= $("#PageDates").val().split(",");
	// Create date value to compare against dateArray.
	var xds 		= $("#FindDate").val().split("/");
	var dateSearch	= xds[2] + "" + xds[0] + "" + xds[1];
	
	// Set default var for which page to display.
	var pageJump = 1;
	// loop through dateArray to do date comparison.
	for(var i=0;i<dateArray.length;i++) {
		// If compare date this page and next page set the page value.
		if( ((dateSearch*1) >= (dateArray[i]*1)) && ((dateSearch*1) <= (dateArray[i+1]*1)) ) {
			pageJump = i+1;
		}
	
	}
	// Do a check to make sure that the date searched isn't later than the last page.
	// If it is then display the last page.
	if((dateSearch*1) >= (dateArray[dateArray.length-1]*1)) {
		pageJump = dateArray.length;
	}
	
	// Hide the currently viewed page.
	$("#page" + curPage).hide();
	// Set the new current page.
	curPage = pageJump;
	// Display the new current page.
	$("#page" + curPage).show();
	
	// Set the "Now Viewing" values.
		var end = ((curPage*1) * (recPP*1));
		var start = end - 4;
		if(end > $("#records").val()) 
			end = $("#records").val();
	
		$("#startValue").html(start);
		$("#endValue").html(end);
	

}


// This function simply sets the Flight Number form field and submits the form.
function doBooking(IDIN,curFD,curFT,doAlert) {
	var doGo = true; // set default for proceeding.

	document.doBook.Flight_Number.value = IDIN;

	// if they have a current flight booked make them confirm they want to proceed.
	if(doAlert) {
		doGo = confirm("You can only have one flight booked at a time.\n\nYou currently have a flight booked for " + curFD + " in the " + curFT + ".\n\nIf you choose a new flight you will be removed from the previous flight.\n\nAre you sure you wish to continue?");
	}
	
	if(doGo) {
		
		var frm = document.doBook;
	
		// create form
		formIN = "a=a";
	
		for(i=0; i<frm.elements.length; i++) {
			formIN += "&";
			formIN += frm.elements[i].name;
			formIN += "=";
			formIN += frm.elements[i].value;
		}
	
		//set the current step value to 2.
		currentStep = 2
	
		// send form
		bookingStep(2);
	}
}

// This function simply sets the Flight Number form field and submits the form to the upgrade page.
function doUpgrade(IDIN,curFD,curFT,doAlert) {
	var doGo = true; // set default for proceeding.

	document.doBook.Flight_Number.value = IDIN;

	// if they have a current flight booked make them confirm they want to proceed.
	if(doAlert) {
		doGo = confirm("You can only have one flight booked at a time.\n\nYou currently have a flight booked for " + curFD + " in the " + curFT + ".\n\nIf you choose a new flight you will be removed from the previous flight.\n\nAre you sure you wish to continue?");
	}
	// if they confirm...
	if(doGo) {
		document.doBook.action = secureURL + "/schedule/balloon_rides_upgrade1.cfm";
		document.doBook.submit();
	}
}



// This function is for when a passenger is overWeight it will add a passenger note to their file.
function overWeightPaxNote(vouchers,weight) {
	// create the url string
	var url="/schedule/balloon_rides_overWeight.cfm";
	url += "?voucher_ID=";
	url += vouchers;
	url += "&maxWeight=";
	url += weight;
	url += "&sid="+Math.random();
	// fire url.
	$.get(url);	
}


// This function is for when a passenger is overWeight it will add a passenger note to their file.
function validateAuth(vouchers) {

	var url="/schedule/balloon_rides_validateAuth.cfm";
	url += "?voucher_ID=";
	url += vouchers;
	url += "&sid="+Math.random();

	$.get(url, function(result){

		// This function will alert user if validation failed.
		var invalidArray = result.split(",");
		// If there are items in the invalidArray then create the alert message.
		if(invalidArray.length && invalidArray[0].trim().length) {
			// create alert message.
			var msg = "Invalid AuthCode for Voucher ID";
			if(invalidArray.length > 1) msg += "'s";
			msg += ": " + result.trim();
			msg += "\n\nPlease enter proper AuthCode";
			if(invalidArray.length > 1) msg += "s";
			
			// Re-enable submit button and change button text
			document.book.submitBut.value = "Make Booking";
			document.book.submitBut.disabled = false;
	
			alert(msg);
		}
		else document.book.submit();
		
	});

}

// This function will send the data to the different steps of the flight booking process.
function bookingStep(step) {

	currentStep = step;

	// Set var to formIN	
	var send = formIN + "&sid="+Math.random();

	if(step == 1) {
		// get flights step 1, append number of records per page.
		var url="/schedule/balloon_book_step1.cfm";
		//pre-pend records per page
		send = "recPP=" + recPP + "&" + send;
	}
	else if(step == 2) {
		var url="/schedule/balloon_book_step2.cfm";
	}
	else if(step == 3) {
		var url="/schedule/balloon_book_step3.cfm";
	}
	// submit form and call back function
	$.post(url, send, function(response){ responseBookingStep(step,response); } );

	return false;	
}

// Display content after response is returned
function responseBookingStep(step, response) {
	if(step == 1) {
		// Display response in dynContent TD.
		$('#dynContent').html(response);
		// function to set vars to local	
		setVars();
		// Now get flights
		getFlights(1,recPP);
	}
	else if (step == 2) {
	
		// Set var to response text, split by ~.
		var resp = response.split("~");

		// Display response in dynContent TD.
		$('#dynContent').html(resp[1]);
	
		if(resp[0])
			ActivateCountDown('CountDownPanel', 180);
	}
	else if (step == 3) {
		
		// Display response in dynContent TD.
		$('#dynContent').html(response);
		
		if(document.doConfirm)
			document.doConfirm.submit();
	}
}

// This will set form values in step 1 to JS vars
function setVars() {
	tD			= $('#tD').val();
	tP			= $('#tP').val();
	tW			= $('#tW').val();
	vID			= $('#vID').val();
	// set vars for passing voucherInfo to findFlights.cfm
	City_ID 	= $('#City_ID').val();
	FlightDay 	= $('#FlightDay').val();
	FlightTime 	= $('#FlightTime').val();
	isTwoPerson = $('#isTwoPerson').val();
	City_Name 	= $('#City_Name').val();
		
}

// This function is for confirming a flight booking.
function confirmBooking() {
	
	// Set form to local var.
	frm = document.doConfirm;
	
	// create form
	formIN = "a=a";
	
	// loop through form.	
	for(i=0; i<frm.elements.length; i++) {
		formIN += "&";
		formIN += frm.elements[i].name;
		formIN += "=";
		formIN += frm.elements[i].value;
	}
	
	// Set confirmation wait message.
	$('#dynContent').html("<span style=\"font-size:12px; font-family:tahoma, Trebuchet MS, tahoma, arial;\"><center><br><br><br>Confirming Booking.<br><img src=\"/images/ajax-loader.gif\" alt=\"\" border=\"0\"><br>Please Wait.</center><br><br><br><br><br></span>");

	//Set current step to 3
	currentStep = 3;
	
	// send form.
	bookingStep(3);
}

// Function for validating the purchaser information page.
function validateUpgrade() {
	
	var s1 			= document.checkout; 	// set form object
	var vHTML 		= ""; 					// open the UL.
	var errCount 	= 0; 					// set default for issues counted. 
	var doFocus 	= false; 				// set default focus();

	// make sure they've chosen a payment method.
	if(s1.Pay_Type.options[s1.Pay_Type.selectedIndex].value.split("|")[0] == 0) {
		//alert("You must select a method of payment.");
		doFocus = ((doFocus)?doFocus:s1.Pay_Type);
		vHTML += "<li>You must select a method of payment.</li>";
		errCount++;
		//return false;
	}

	// If they have chosen to use a credit card to pay ensure they have filled in all info.
	if(s1.card_name.value.trim().length == 0) {
		//alert("You must enter the name on the credit card.");
		s1.card_name.value = "";
		doFocus = ((doFocus)?doFocus:s1.card_name);
		vHTML += "<li>You must enter the name on the credit card.</li>";
		errCount++;
		//return false;
	}
	
	if(s1.pan.value.trim().length < 13 || isNaN(s1.pan.value.trim())) {
		//alert("You must enter a valid credit card number.\n\nDo not include spaces, dashes or any non-numeric characters.");
		//s1.pan.value = "";
		doFocus = ((doFocus)?doFocus:s1.pan);
		vHTML += "<li>You must enter a valid credit card number.\n\nDo not include spaces, dashes or any non-numeric characters.</li>";
		errCount++;
		//return false;
	}
	
	// do Mod 10 check on CC number
	var isCC = checkCreditCard (s1.pan.value.trim(),s1.Pay_Type.options[s1.Pay_Type.selectedIndex].value.split("|")[2]);
	// if it didn't pass the mod 10 check alert.
	if(!isCC) {
		//alert (ccErrors[ccErrorNo]);
		doFocus = ((doFocus)?doFocus:s1.Pay_Type);
		vHTML += "<li>" + ccErrors[ccErrorNo] + "</li>";
		errCount++;
		//return false;
	}

	// set vars for the first digit of the cc number and the prefix to validate against.
	var prefix 	= s1.Pay_Type.options[s1.Pay_Type.selectedIndex].value.split("|")[4];
	var digit 	= s1.pan.value.trim().substring(0,1);
	var cctype 	= s1.Pay_Type.options[s1.Pay_Type.selectedIndex].value.split("|")[2];

	if(	prefix*1 != digit*1) {
		//alert("The card number you entered does not appear to be a valid " + cctype + ".\n\nPlease ensure you've chosen the proper card type.");
		doFocus = ((doFocus)?doFocus:s1.pan);
		vHTML += "<li>The card number you entered does not appear to be a valid " + cctype + ".\n\nPlease ensure you've chosen the proper card type.</li>";
		errCount++;
		//return false;
	}
	
	if(s1.expiry_m.value < 1 || s1.expiry_m.value > 12) {
		//alert("You must enter a valid exipry month.");
		s1.expiry_m.value = "";
		doFocus = ((doFocus)?doFocus:s1.expiry_m);
		vHTML += "<li>You must enter a valid exipry month.</li>";
		errCount++;
		//return false;
	}
	
	// Set current date
	var curdate = new Date();
	var year = curdate.getFullYear().toString().substr(2,2);
	// Check to see if the year is a valid value.
	if(s1.expiry_y.value.length == 0 || s1.expiry_y.value < year) {
		//alert("You must enter a valid exipry year.");
		s1.expiry_y.value = "";
		doFocus = ((doFocus)?doFocus:s1.expiry_y);
		vHTML += "<li>You must enter a valid exipry year.</li>";
		errCount++;
		//return false;
	}
	
	// Check to see that they've read the terms and conditions.
	if(!s1.terms.checked) {
		//alert("You must agree to the terms & conditions to complete this transaction.")
		doFocus = ((doFocus)?doFocus:s1.terms);
		vHTML += "<li>You must agree to the terms & conditions to complete this transaction.</li>";
		errCount++;
		//return false;
	}
	// close the unordered list.	
	vHTML = "<b>" + errCount + " Errors:</b><br/><ul>"+ vHTML + "</ul>";
	
	if(errCount) {
		$("#purchError").html(vHTML).slideDown(300);
		doFocus.focus();	// now set the focus.
		return false;
	}
	
	
	/* OK, they've passed validation, display loading screens then return true. */
	$("#purchError").html("").slideUp(300);

	$("#purchButtons").fadeOut(0, function(){
		$("#loaderDiv").fadeIn(0, function(){
			// Validation passed, submit form.
			return true;
		});
	});

}

// this function handles the completion of the upgrade
function upgradeComplete(dataIN)
{	
	//split the response
	var response = dataIN.trim().split("|");

	if(response[0] == "false")
	{
		$("#purchError").html("<center><b>" + response[1] + "</b></center>").slideDown(300);

		$("#loaderDiv").fadeOut(300, function(){
			$("#purchButtons").fadeIn(300);
		});

		return false;
	}
	else if(response[0] == "true") 
	{
		$('#checkout').attr("action","balloon_rides_upgrade_complete.cfm");
		document.checkout.authcode.value = response[2]; // set the authcode value
		$('#checkout').unbind(); 	
		$('#checkout').submit();

		return false;
	}
	else {
		alert("Unexpected Response!");
		$("#loaderDiv").fadeOut(300, function(){
			$("#purchButtons").fadeIn(300);
		});
		return false;
		
	}

	//hide loader
	$("#loaderDiv").slideUp(300, function() {
		// show confirmation
		$("#confirmDiv").slideDown(300).delay(1750).slideUp(300,function(){
			doFormDialog(posID);
		});
	});
}

/* This function will do the change */
function doChange(urlIN){
	
	// set the action
	$("#checkout").attr("action", urlIN);
	// unbind ajaxForm
	$("#checkout").unbind();
	// submit
	$("#checkout").submit();
}

/* This function toggle the Hotel Name and Travel Type rows depending on if Hotel Pickup is Yes or NO. */
function toggleHotelPickup(hotelPickup,x)
{
	document.getElementById("HotelPickup_HotelName_" + x).style.display = ((hotelPickup)?"table-row":"none");
	document.getElementById("TravelTime_" + x).style.display = ((hotelPickup)?"none":"table-row");
	document.getElementById("TravelTimeDesc_" + x).style.display = ((hotelPickup)?"none":"table-row");
}


