/***************************************
 ***	Default variables.
 ****************************************/
var gcCount 	= 0; 			// default gift card index.
var gcArray 	= new Array(); 	// create default array to hold gift cards being PURCHASED.
var gcRedeem 	= new Array(); 	// create default array to hold gift cards being REDEEMED.
var oTotal		= 0; 			// set order total to a var.

// Function for validating page one of the checkout process.
function validateStep1(){
	// set form to var
	var f = document.purchase;
	
	// set voucher quantity to a var... if it's defined.
	if(f.Quantity) var vQty = f.Quantity.value*1;
	else var vQty = 0;
	
	// set gift card quantity to a var.
	var gcQty = f.GCQuantity.value*1;
	
	// first see if there is a quantity of vouchers and of gift cards.
	if((vQty + gcQty) <= 0) {
		alert("You must add at least one Flight Voucher or Digital Gift Card to proceed.");
		return false;
	}

	// now if voucher quantity is non-zero make sure a flightype is chosen.
	if(vQty > 0) {
		if(f.flighttype) { // if flighttype is defined
			var isCheck = false;
			for(var i=0; i<f.flighttype.length; i++) { // loop through flighttype radios and see if one is selected
				if(f.flighttype[i].checked) isCheck = true;
			}
			if(!isCheck) { // no flighttype checked, throw alert.
				alert("You have entered " + vQty + " flight vouchers but haven't chosen a flight type.\n\nEither enter 0 for Quantity or choose a flight type.");
				return false;
			}
		}
		else { // flight type isn't defined.
			alert("You have entered " + vQty + " flight vouchers but haven't chosen a flight type.\n\nEither enter 0 for Quantity or choose a flight type.");
			return false;
		}
	}
	
	// set voucher quantity back to enabled... if it's defined.
	if(f.Quantity) f.Quantity.disabled = false;
	
	return true
}

// Function for validating login values.
function validateLogin(s1) {
	// Check that logEmail is valid.
	if (!checkEmail(s1.logEmail.value)) {
		alert("Please enter a valid Email Address.");
		s1.logEmail.focus();
		return false;
	}
	// Check they've inputted an Email address.
	if(s1.logPassword.value.trim().length < 5) {
		alert("Please enter your Password to login.\nPasswords are 5 characters or longer.");
		s1.logPassword.focus();
		return false;
	}
	
	return true;
}

// Function for validating the purchaser information page.
function validateStep2(s1) {
	// Check a Purchaser FirstName is entered.
	if(s1.FirstName.value.trim().length == 0) {
		alert("You must enter your First Name.");
		s1.FirstName.value = "";
		s1.FirstName.focus();
		return false;
	}
	// Check a Purchaser LastName is entered.
	if(s1.LastName.value.trim().length == 0) {
		alert("You must enter your Last Name.");
		s1.LastName.value = "";
		s1.LastName.focus();
		return false;
	}
	// Check a Purchaser Address1 is entered.	
	if(s1.Address1.value.trim().length == 0) {
		alert("You must enter your Address.");
		s1.Address1.value = "";
		s1.Address1.focus();
		return false;
	}
	// Check a Purchaser City is entered.
	if(s1.City.value.trim().length == 0) {
		alert("You must enter your City.");
		s1.City.value = "";
		s1.City.focus();
		return false;
	}
	// Check a Purchaser Country is selected.	
	if(!s1.Country_ID.value>0) {
		alert("You must choose your Country.");
		s1.Country_ID.focus();
		return false;
	}
	// Check if state0 is visible and if so check a value is entered.
	if(document.getElementById('state0').style.display != 'none' && !s1.state0.value.trim().length>0) {
		alert("You must enter your Region.");
		s1.state0.value = "";
		s1.state0.focus();
		return false;
	}
	// Check if state1 is visible and if so check an option is selected.
	if(document.getElementById('state1').style.display != 'none' && !s1.state1.value>0) {
		alert("You must enter your Province.");
		s1.state1.focus();
		return false;
	}
	// Check if state2 is visible and if so check an option is selected.
	if(document.getElementById('state2').style.display != 'none' && !s1.state2.value>0) {
		alert("You must enter your State.");
		s1.state2.focus();
		return false;
	}
	// Check a Purchaser Zip code is entered.
	if(s1.Zip.value.trim().length == 0) {
		alert("You must enter your Postal/Zip Code.");
		s1.Zip.value = "";
		s1.Zip.focus();
		return false;
	}
	// Check if state1 is visible and if so, ensure that a proper postal code is entered.	
	if(document.getElementById('state1').style.display != 'none') {
		var valZip = isPostal(s1.Zip.value);
		if (!valZip) {
			alert("You must enter a valid Canadian Postal Code.");
			s1.Zip.focus();
			return false;
		}
	}	
	// Check if state2 is visible and if so, ensure that a proper zip code is entered.	
	if(document.getElementById('state2').style.display != 'none') {
		var valZip = isZip(s1.Zip.value);
		if (!valZip) {
			alert("You must enter a valid U.S. Zip Code.");
			s1.Zip.focus();
			return false;
		}
	}	
	// Check a Purchaser HomePhone is entered.
	if(s1.HomePhone.value.trim().length == 0) {
		alert("You must enter your Home Phone.");
		s1.HomePhone.value = "";
		s1.HomePhone.focus();
		return false;
	}
	
	// Only run these checks if the customer hasn't logged in
	// because email and password fields don't show otherwise.
	if(s1.Customer_ID.value*1 == 0) {
		// Check that email is valid.
		if (!checkEmail(s1.Email.value)) {
			alert("Please enter a valid Email Address.");
			s1.Email.focus();
			return false;
		}
		// Make sure they've entered a password.
		if(s1.Password.value.trim().length < 5 || s1.Password.value.trim().length > 15) {
			alert("You must enter a password that is 5 to 15 characters long.");
			s1.Password.focus();
			return false;
		}
		// Make sure they've confirmed their password.
		if(s1.Password.value != s1.Password2.value) {
			alert("Your password and password confirmation do not match.");
			s1.Password2.focus();
			return false;
		}
	}
	
	// Check if state1 or state2 is visible and if so, ensure that a proper HomePhone is entered.
	if(document.getElementById('state2').style.display != 'none' || document.getElementById('state1').style.display != 'none') {
		if (s1.HomePhone.value.trim().length != 10) {
			alert("You must enter a valid 10 digit Home Phone Number.");
			s1.HomePhone.focus();
			return false;
		}
	}	

	// Check they've chosen a delivery method.
	if(s1.DeliveryMethod.options[s1.DeliveryMethod.selectedIndex].value.split("|")[1] < 0) {
		alert("Please choose a delivery method.");
		s1.DeliveryMethod.focus();
		return false;
	}
	
	// Check delivery method. If email make sure it's a valid email addy.
	if(s1.DeliveryMethod.options[s1.DeliveryMethod.selectedIndex].value.split("|")[1] == 1) {
		if (!checkEmail(s1.EmailToAddress.value)) {
			alert("Please enter a valid email address for email delivery.");
			s1.EmailToAddress.focus();
			return false;
		}
	}
	else {


		// Check a Purchaser FirstName is entered.
		if(s1.Shipping_Name.value.trim().length == 0) {
			alert("You must enter the Shipping Name.");
			s1.Shipping_Name.value = "";
			s1.Shipping_Name.focus();
			return false;
		}
		// Check a Purchaser Address1 is entered.	
		if(s1.Shipping_Address1.value.trim().length == 0) {
			alert("You must enter the Shipping Address.");
			s1.Shipping_Address1.value = "";
			s1.Shipping_Address1.focus();
			return false;
		}
		// Check a Purchaser City is entered.
		if(s1.Shipping_City.value.trim().length == 0) {
			alert("You must enter the Shipping City.");
			s1.Shipping_City.value = "";
			s1.Shipping_City.focus();
			return false;
		}
		// Check a Purchaser Country is selected.	
		if(!s1.Shipping_Country_ID.value>0) {
			alert("You must choose the Shipping Country.");
			s1.Shipping_Country_ID.focus();
			return false;
		}
		// Check if state3 is visible and if so check a value is entered.
		if(document.getElementById('state3').style.display != 'none' && !s1.state3.value.trim().length>0) {
			alert("You must enter the Shipping Region.");
			s1.state3.value = "";
			s1.state3.focus();
			return false;
		}
		// Check if state4 is visible and if so check an option is selected.
		if(document.getElementById('state4').style.display != 'none' && !s1.state4.value>0) {
			alert("You must enter the Shipping Province.");
			s1.state4.focus();
			return false;
		}
		// Check if state5 is visible and if so check an option is selected.
		if(document.getElementById('state5').style.display != 'none' && !s1.state5.value>0) {
			alert("You must enter the Shipping State.");
			s1.state5.focus();
			return false;
		}
		// Check a Purchaser Zip code is entered.
		if(s1.Shipping_Zip.value.trim().length == 0) {
			alert("You must enter the Shipping Postal/Zip Code.");
			s1.Shipping_Zip.value = "";
			s1.Shipping_Zip.focus();
			return false;
		}
		// Check if state1 is visible and if so, ensure that a proper postal code is entered.	
		if(document.getElementById('state4').style.display != 'none') {
			var valZip = isPostal(s1.Shipping_Zip.value);
			if (!valZip) {
				alert("You must enter a valid Canadian Shipping Postal Code.");
				s1.Shipping_Zip.focus();
				return false;
			}
		}	
		// Check if state2 is visible and if so, ensure that a proper zip code is entered.	
		if(document.getElementById('state5').style.display != 'none') {
			var valZip = isZip(s1.Shipping_Zip.value);
			if (!valZip) {
				alert("You must enter a valid U.S. Shipping Zip Code.");
				s1.Shipping_Zip.focus();
				return false;
			}
		}	

	}
	
	// only check payment options if a payment is required.
	if(s1.payment.value*1 > 0) {
	
		// 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.");
			s1.Pay_Type.focus();
			return false;
		}
	
		// If they have chosen to use a credit card to pay ensure they have filled in all info.
		if(s1.Pay_Type.options[s1.Pay_Type.selectedIndex].value.split("|")[1] == 1) {
			if(s1.card_name.value.trim().length == 0) {
				alert("You must enter the name on the credit card.");
				s1.card_name.value = "";
				s1.card_name.focus();
				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 = "";
				s1.pan.focus();
				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]);
				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.");
				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 = "";
				s1.expiry_m.focus();
				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 = "";
				s1.expiry_y.focus();
				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.")
		return false;
	}
	
	
	// Set the country name value.	
	var w = s1.Country_ID.selectedIndex;
	s1.CountryName.value = s1.Country_ID.options[w].text;
	// Set the shipping country name value.
	var w = s1.Shipping_Country_ID.selectedIndex;
	s1.Shipping_CountryName.value = s1.Shipping_Country_ID.options[w].text;
	
	document.getElementById("formDiv").style.display 		= "none";
	document.getElementById("loadScreen").style.display 	= "";

	// Validation passed, submit form.
	return true;
	
}



// Function for validating the purchaser information page.
function validateStep2Retry(s1) {
	
	// 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.");
		s1.Pay_Type.focus();
		return false;
	}

	// If they have chosen to use a credit card to pay ensure they have filled in all info.
	if(s1.Pay_Type.options[s1.Pay_Type.selectedIndex].value.split("|")[1] == 1) {
		if(s1.card_name.value.trim().length == 0) {
			alert("You must enter the name on the credit card.");
			s1.card_name.value = "";
			s1.card_name.focus();
			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 = "";
			s1.pan.focus();
			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 = "";
			s1.expiry_m.focus();
			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 = "";
			s1.expiry_y.focus();
			return false;
		}
	}
	
	document.getElementById("formDiv").style.display 		= "none";
	document.getElementById("loadScreen").style.display 	= "";

	// Validation passed, submit form.
	return true;
	
}

// Function for setting the subtotal field.
/*
function setTotals() {
	// Check to make sure prInfo is defined.
	if(typeof prInfo != "undefined"){
		var taxtotal = 0;
		var x = document.gc;
		var qty = x.Quantity.value;
		var thisPR;
		
		// Loop through prInfo array until you find the right flight type based on quantity of tickets.
		var satisfied = false;
		for(var i=0;i<prInfo.length;i++) {
			if(qty >= prInfo[i][1] && qty <= prInfo[i][2]) {
				thisPR = prInfo[i];
				// Set flightTypeID
				x.FlightTypeID.value = prInfo[i][0];
				satisfied = true;
			}
			else {
				if(!satisfied) {
					thisPR = prInfo[i];
					// Set flightTypeID
					x.FlightTypeID.value = prInfo[i][0];
				}
			}
		}

		x.subtotal.value 	= formatCurrency(((x.Quantity.value) * (thisPR[3]*1)),true);
		
		if(x.Tax1) {
			x.Tax1.value 	= ((((x.Quantity.value) * (thisPR[3]*1))) * t1);
			taxtotal 		+= x.Tax1.value
			x.Tax1.value 	= formatCurrency(x.Tax1.value,true);
		}
		if(x.Tax2) {
			x.Tax2.value 	= ((((x.Quantity.value) * (thisPR[3]*1))) * t2);
			taxtotal 		+= x.Tax2.value
			x.Tax2.value 	= formatCurrency(x.Tax2.value,true);
		}
		
		
		x.total.value 	= formatCurrency(((x.Quantity.value) * (thisPR[3]*1)) + (taxtotal*1),true);
	
		// update order total var.
		oTotal = (((x.Quantity.value) * (thisPR[3]*1)) + (taxtotal*1));
	}
}
*/


// This function will toggle the deliver information div.
// If it's email, then it will display an email field, otherwise it will display a textarea for an address to go in.
function toggleDelivery(tVal) {

	switch(tVal*1) {
		case -1 :
			document.getElementById("emailTo").style.display="none";
			document.getElementById("mailTo").style.display="none";
		break
		
		case 0 :
			document.getElementById("emailTo").style.display="none";
			document.getElementById("mailTo").style.display="";
		break
		
		case 1 :
			document.getElementById("emailTo").style.display="";
			document.getElementById("mailTo").style.display="none";
		break

	}
}

// This function will set the email address of the voucher recipient.
function toggleEmailDelivery(addyType) {

	switch(addyType*1) {
		case 0 :
			document.checkout.EmailToAddress.value = "";
		break
		
		case 1 :
			document.checkout.EmailToAddress.value = document.checkout.Email.value;
		break
		
	}
}

// This function will set the mailing address of the voucher recipient.
function toggleMailDelivery(addyType) {
	
	var f = document.checkout;
	
	switch(addyType*1) {
		case 0 :
			f.Shipping_Name.value 		= "";
			f.Shipping_Address1.value 	= "";
			f.Shipping_Address2.value 	= "";
			f.Shipping_City.value		= "";
			
			document.getElementById("state3").style.display = "";
			document.getElementById("state4").style.display = "none";
			document.getElementById("state5").style.display = "none";
			f.state3.value = "";

			f.state4.selectedIndex = 0;
			f.state5.selectedIndex = 0;
			f.Shipping_Country_ID.selectedIndex = 0;
			f.Shipping_Zip.value = "";
		break
		
		case 1 :
			f.Shipping_Name.value 		= f.FirstName.value + " " + f.LastName.value;
			f.Shipping_Address1.value 	= f.Address1.value;
			f.Shipping_Address2.value 	= f.Address2.value;
			f.Shipping_City.value		= f.City.value;
				
			if (document.getElementById("state0").style.display == "") {
				document.getElementById("state3").style.display = "";
				document.getElementById("state4").style.display = "none";
				document.getElementById("state5").style.display = "none";
				f.state3.value = f.state0.value;
			}
			if (document.getElementById("state1").style.display == "") {
				document.getElementById("state3").style.display = "none";
				document.getElementById("state4").style.display = "";
				document.getElementById("state5").style.display = "none";
				f.state4.selectedIndex = f.state1.selectedIndex;
			}
			if (document.getElementById("state2").style.display == "") {
				document.getElementById("state3").style.display = "none";
				document.getElementById("state4").style.display = "none";
				document.getElementById("state5").style.display = "";
				f.state5.selectedIndex = f.state2.selectedIndex;
			}
			
			f.Shipping_Country_ID.selectedIndex = f.Country_ID.selectedIndex;
			
			f.Shipping_Zip.value = f.Zip.value;
				
		break
		

	}
}



// This function will trim the input to the specified length.
function trimVMsg(msg,len) {
	//If it's longer than it's suppossed to be trim it.
	if(msg.value.length > len) {
		msg.value=msg.value.substring(0,len)
	}
} 

// This function will set a voucher message to the previous one.
function doSameAs(vID,isChecked) {
	var x = document.checkout;
	
	if(isChecked) {
		eval("x.voucherMessage" + vID + ".value = x.voucherMessage" + (vID-1) + ".value");
	}
	else {
		eval("x.voucherMessage" + vID + ".value = ''");
	}
}


// this function will validate a promo code and display neccessary info about it.
function applyPromo(fName,ftID,ft,qty) {
	
	var f = eval("document." + fName); 		// set form var
	code = f.promo_code.value.trim();	// set promo code to var
	
	if(!code.length) { // stop processing if there is no code added.
		resetPromo(f); // reset all promo related fields and values
		return false; 
	}

	// Create a new xml object
	xmlHttp=GetXmlHttpObject();
	if (xmlHttp==null) {alert ("Browser does not support HTTP Request");return false;} 


	var url="/globalFunctions/authPromoCode.cfm";

	url += "?Code=";
	url += code;
	url += "&FTID=";
	url += ftID;
	url += "&frmName=";
	url += fName;
	url += "&valid=";
	url += ft;
	url += "&qty=";
	url += qty;
	url += "&sid="+Math.random();
	
	xmlHttp.onreadystatechange=respPromoCode;
	xmlHttp.open("GET",url,true);
	xmlHttp.send(null);
	
	return false;
}

// Run after promo code is validated.
function respPromoCode() {
	if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete") { 
		var resp 	= xmlHttp.responseText.trim().split("|");
		var status 	= resp[0]*1;
		dis = 0; // make sure you reset the discount so that discounts aren't stacked.
		
		if(!status) { // status is 0 (invalid) alert message.
			resetPromo(eval("document." + resp[2].trim())); // reset promo fields and values
			alert(resp[1].trim());
		}
		else { // else code is good, proceed.
			// resp[1] = CodeID
			// resp[2] = Code
			// resp[3] = Amount
			// resp[4] = Type: 0=Dollar, 1=Percent
			// resp[5] = ApplyTo: 0=Total Order, 1=Each Voucher
			// resp[6] = Single: 0=unlimited, 1=single use
			// resp[7] = frmName (name of form)
			
			var f = eval("document." + resp[7].trim()); //set form to var
			var d = 0; //default for discount value
			
			// if this is to be applied to all vouchers in order...
			if(resp[5]*1) { 
				if(resp[4]*1) { // if this is percent
					dis = formatCurrency((((qty*ppp)*(resp[3]*1))/100)*-1); // set discount amount. quantity x price per x percent / 100 x -1 to get discount.
				}
				else { // otherwise this is an amount per voucher to discount
					dis = formatCurrency((qty*(resp[3]*1))*-1); // set discount amount. quantity x discount x -1 to get discount.
				}
			}
			// otherwise it's to be applied to the subtotal
			else { 
				if(resp[4]*1) { // if this is percent
					dis = formatCurrency((((qty*ppp)*(resp[3]*1))/100)*-1); // set discount amount. quantity x price per x percent / 100 x -1 to get discount.
				}
				else { // otherwise this is an amount per order to discount
					dis = formatCurrency((resp[3]*1)*-1); // set discount amount. discount x -1 to get discount.
				}
			}
			f.discount.value = formatCurrency(dis,true); // format currency and set form field to display discount.
			f.codeID.value = resp[1]; // set codeID.
			setFinalTotals(); // run function for setting totals
			
			$("promoTD").innerHTML = "<img src=\"/images/round_check.gif\" align=\"texttop\" vspace=\"2\"> &nbsp;&nbsp;" + "\'" + resp[2].trim() + "\' promotion applied. " + ((resp[4]*1)?'':'$') + formatCurrency(resp[3]*1) + ((resp[4]*1)?'%':'') + " off " + ((resp[5]*1)?"each voucher.":"total order.");
			$("promoTR").style.display = "";
			
		}
	} 
}

// function to reset promo fields, td and values.
function resetPromo(f) {
	$("promoTD").innerHTML = ""; 		// reset promo td
	$("promoTR").style.display = "none";// hide promo tr
	f.discount.value = "$0.00";			// reset discount value
	f.codeID.value = 0; // reset codeID to 0.
	dis = 0; // reset discount var
	setFinalTotals(); // run function for setting totals
}

// Function for setting the subtotal field.
function setFinalTotals() {
	var x = document.checkout;
	var dm = x.DeliveryMethod.value.split("|")[0]*1;
	var tax1 = 0;
	var tax2 = 0;
	var taxtotal = 0;
	var thisPR;
	var gcRedeemTtl = getGCRedeemTotal();
	
	dis = dis*1; //multiply discount x 1 to ensure it's a number.
		
	x.vSub.value 	= formatCurrency(((qty) * (ppp*1)),true); // set subtotal: quantity x price per voucher
	x.gcSub.value	= formatCurrency(gcsub,true); // set gift card total.

	x.discount.value	= formatCurrency(dis,true); // set discount field

	x.delivery.value	= formatCurrency(dm,true); // set delivery field
	
	if(x.Tax1) {
		tax1 			= ((((qty * (ppp*1)) + dm) + dis ) * t1); // set tax 1 total. subtotal + delivery - discount x tax1
		taxtotal 		= taxtotal + tax1;
		x.Tax1.value 	= formatCurrency(tax1,true);
	}
	if(x.Tax2) {
		tax2 			= ((((qty * (ppp*1)) + dm) + dis ) * t2);  // set tax 2 total. subtotal + delivery - discount x tax2
		taxtotal 		= taxtotal + tax2;
		x.Tax2.value 	= formatCurrency(tax2,true);
	}
		
	x.total.value 	= formatCurrency((((qty * (ppp*1)) + dm) + dis) + (taxtotal*1) + gcsub,true);
	
	oTotal = formatCurrency(((((qty * (ppp*1)) + dm) + dis) + (taxtotal*1) + gcsub),false);
	
	
	x.gcRedeem.value = "$-" + formatCurrency(gcRedeemTtl,false); // set the gift cards redeemed value
	
	x.payment.value = formatCurrency(oTotal-gcRedeemTtl); // set hidden payment field
	x.payTotal.value = formatCurrency(oTotal-gcRedeemTtl,true); // set amount outstanding field.
	
}

// This will reset the city drop down.
function resetCities() {
	$("citiesPull").options.selectedIndex = 0;
}

// this function will get city pricing.
function getCityPricing(CityID) {

	// set the price per voucher value to zero.
	document.purchase.PPP.value = 0;

	if(CityID*1 == 0) { // if they chose a value that's not a city.
		if(document.purchase.Quantity)
			document.purchase.Quantity.value = 0; // reset the qauntity to zero.
		$("Pricing").innerHTML = ""; // Clear html.
		return false;
	}
	
	$("Pricing").innerHTML = "<center><br><br><b>Loading Flight Types...</b>&nbsp;&nbsp;&nbsp;&nbsp;<br><br><br></center>";
	
	
	// Create a new xml object
	xmlHttp=GetXmlHttpObject();
	if (xmlHttp==null) {alert ("Browser does not support HTTP Request");return false;} 


	var url="/globalFunctions/showPricing.cfm";

	url += "?CityID=";
	url += CityID;
	url += "&sid="+Math.random();
	
	xmlHttp.onreadystatechange=respCityPricing;
	xmlHttp.open("GET",url,true);
	xmlHttp.send(null);
	
	return false;
}

// Run after city pricing is returned.
function respCityPricing() {
	if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete") { 
		$("Pricing").innerHTML = xmlHttp.responseText;

		// set the price per voucher value to zero.
		document.purchase.PPP.value = 0;
	} 
}

// this function for tally subtotal cost of vouchers.
// city is cityID. fd is FlightDay. ft is FlightTime. is2 is bit for isSweetheart.
function cartChangeFT(city,fd,ft,is2) {
	// set form to a var.
	var f = document.purchase;
	
	// set the price per voucher value to zero.
	f.PPP.value = 0;
	// set flight types field to an array.
	var ftl = f.ftList.value.trim().split(",");
	
	// check if quantity is a number.
	if (f.Quantity.value.trim() <= 0) {
		f.Quantity.value = 1;
	}
	// set q = quantity
	var q = f.Quantity.value.trim()*1;
	
	// loop through flight types until you find the right one.
	for(var i=0; i<ftl.length; i++) {
		var x = ftl[i].split("|");
		// #FlightDay#|#FlightTime#|#MinPax#|#MaxPax#|#UnitPrice#|#isTwoPerson#
		if( (x[0]==fd) && (x[1]==ft) && (q>=(x[2]*1)) && (q<=(x[3]*1)) && (is2==x[5]*1) ) {
			// if this is a sweetheart add "/ couple" to end
			if(is2*1==1) { 
				$("costTD").innerHTML = "x " + formatCurrency(x[4]*2,true) + " <b>/ couple</b>";
				f.Quantity.disabled = true;
				f.Quantity.value = 1;
				// set the price per voucher value.
				f.PPP.value = (x[4]*1)*2;
				// display additional info for sweetheart flights
				$("SweetheartInfo").style.display = "";
			}
			else {
				$("costTD").innerHTML = "x " + formatCurrency(x[4],true); 
				f.Quantity.disabled = false;
				// set the price per voucher value.
				f.PPP.value = x[4];
				// hide additional info for sweetheart flights
				$("SweetheartInfo").style.display = "none";
			}
			// now set subTotal;
			calcVSub();
			return false;
			
		}

	}	
	
	return false;
}

// check the qauntity value inputted.
function checkVQty(item) {
	verifyNum(item); // verify a number was entered.

	var f = document.purchase; // set form to a var.
	var city = f.City_ID.value; // set city
	var fd, ft, is2; // set up vars for flightday, flighttime, is2

	// loop through form radio buttons and get flight info.
	for(var x=0;x<f.flighttype.length;x++) {
		if(f.flighttype[x].checked) {
			var info = f.flighttype[x].value.split("_");
				is2 = (info[0]=="Sweetheart")?1:0;
				fd 	= info[1];
				ft 	= (info[2]=="Morning")?"AM":"PM";
		}
	}
	
	// run cartChangeFT function to ensure it's calculating the right flight type & quantity.
	cartChangeFT(city,fd,ft,is2)
	
	//calcVSub();		 // calculate subtotal of vouchers
}


// this function will calculate subtotal value.
function calcVSub(){
	// set form to a var.
	var f = document.purchase;
	var q = f.Quantity.value.trim()*1; // set var to quantity
	var p = f.PPP.value.trim()*1; // set price per voucher
	// set subtotal value.
	f.voucherSub.value = formatCurrency((q*p),true);
	
}


// this function will add/remove gift cards.
function doGiftCard(action,obj) {
	// set to forum
	var f = document.purchase;
	
	// if this is a delete.
	if(action*1 == 0) {
		var t = new Array(); // create temp array to hold gc's.
		for(var i=0;i<gcArray.length;i++) {
			if(i != (obj*1)) {
				t[t.length] = gcArray[i]; // add gc to temp array
			}
		}
		gcArray = t; // set gcArray to temp.
	}
	// if this is an add.	
	else if(action*1 == 1) {
		
		if(f.gcTo.value.trim().length == 0 || f.gcFrom.value.trim().length == 0) {
			alert("You must input values in the \"To Line\" and \"From Line\" fields.");
			return false;
		}
	
		var amount 	= f.gcAmount.options[f.gcAmount.selectedIndex].value; // set value;
		var to 		= escape(f.gcTo.value.trim()); // set to line.
		var from	= escape(f.gcFrom.value.trim()); // set from line.
		var val 	= amount + "|" + to + "|" + from; // create value for array.
		gcArray[gcArray.length] = val; // add item to gcArray;
	}
	
	$("cardsTD").innerHTML = ""; // Clear the cards div.
	var cont 	= ""; // var to hold content
	var GCTotal	= 0;
	for(var a=0;a<gcArray.length;a++) {
		var x = gcArray[a].split("|"); // split value into an array
		// add item;	
		cont += "<div class='gcItem" + ((a % 2)?"1":"2") + "'>";
		cont += "<div class='gcNum'><b>#" + (a+1) + "</b></div>";
		cont += "<div class='gcTo'><b>To:</b> " + unescape(x[1].trim()) + "</div>";
		cont += "<div class='gcFrom'><b>From:</b> " + unescape(x[2].trim()) + "</div>";
		cont += "<div class='gcAmount'><b>Amount: $" + x[0] + "</b></div>";
		cont += "<div class='gcDelete'><img src=\"/images/icon_removeGC.gif\" onclick=\"doGiftCard(0," + a + ")\" style=\"cursor:pointer\"><input type=\"hidden\" name=\"GC\" value=\"" + gcArray[a] + "\"></div>";
		cont += "</div>";
		// add this amount to the sum
		GCTotal += x[0]*1;
	}
	// set div content
	$("cardsTD").innerHTML = cont;
	// set gift card count 
	f.GCQuantity.value = gcArray.length;
	// set gift card total
	f.GCSub.value = formatCurrency(GCTotal,true);
	
	// clear 'from' and 'to' fields
	f.gcTo.value = ""; 	 // set to line.
	f.gcFrom.value = ""; // set from line.

	// set the transaction totals;
//	setTotals();
}


// this function is for validating gift cards that are entered.
function validateGC(frm) {
	var f = eval("document." + frm);
	
	var gcID 	= f.gcID.value.trim(); 	// set gift card ID to a var.
	var gcCode 	= f.gcCode.value.trim();// set gift card auth code to a var.
	
	if(gcID.length == 0 || gcCode.length == 0) { // check that a card ID and auth code have been entered.
		alert("You must enter a Gift Card ID and Gift Card Code.");
		f.gcID.focus();
		return false;
	}
	
	// Create a new xml object
	xmlHttp=GetXmlHttpObject();
	if (xmlHttp==null) {alert ("Browser does not support HTTP Request");return false;} 


	var url="/globalFunctions/authGiftCard.cfm";

	url += "?gcID=";
	url += gcID;
	url += "&gcCode=";
	url += gcCode;
	url += "&frm=";
	url += frm;
	url += "&sid="+Math.random();
	
	xmlHttp.onreadystatechange=respGiftCard;
	xmlHttp.open("GET",url,true);
	xmlHttp.send(null);
}

// Run after gift card is validated.
function respGiftCard() {
	if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete") { 
	
		var resp 	= xmlHttp.responseText.trim().split("|");
		var status 	= resp[0]*1;

		var f = eval("document." + resp[3].trim()); //set form to var
		
		if(!status) { // status is 0 (invalid) alert message.
			alert(resp[1].trim());
			f.gcID.focus();
		}
		else { // else code is good, proceed.
			// resp[1] = CodeID
			// resp[2] = Balance
			// resp[3] = frmName (name of form)
			
			// loop through gcRedeem and see if it's already in there
			var gcFound = false;
			for(var i=0; i<gcRedeem.length; i++) {
				if(gcRedeem[i].split("|")[0] == resp[1]) {
					gcFound = true;
				}
			}
			// add to array if not found.
			if(!gcFound) gcRedeem[gcRedeem.length] = resp[1] + "|" + resp[2] + "|" + 0;
			
			// clear values.
			f.gcID.value 	= "";
			f.gcCode.value 	= "";			
			
			// now populate the gift cards table.
			popGiftCards();
			
			//setFinalTotals(); // run function for setting totals
			
			
		}
	} 
}

// this function will populate the giftCard redemption table.
function popGiftCards() {
	var gcHTML = ""; // create var to hold the gift card html
		gcHTML += "<table width=\"100%\" cellpadding=\"0\" cellspacing=\"0\" border=\"0\" class=\"incentiveTable\" align=\"left\">";

	// loop through gift cards.
	var io = 0;
	for(var i=0; i<gcRedeem.length; i++) {
		var v = gcRedeem[i].split("|"); // create local var for array element.

		gcHTML += "<tr bgcolor=\"#" + ((io)?("eaeaea"):("ffffff")) + "\">";
		gcHTML += "<td width=\"30\" align=\"right\" class=\"gc_td2\">#" + (i+1) + "&nbsp;</td>";
		gcHTML += "<td width=\"100\" align=\"center\" class=\"gc_td2\">" + v[0].trim() + "</td>";
		gcHTML += "<td width=\"100\" align=\"center\" class=\"gc_td2\">" + formatCurrency(v[1],true) + "</td>";
		gcHTML += "<td width=\"130\" align=\"center\" class=\"gc_td2\">";
		gcHTML += "<input type=\"text\" name=\"gc_" + v[0].trim() + "\" value=\"" + formatCurrency(v[1],false) + "\" size=\"5\" onkeyup=\"verifyDec(this)\" style=\"text-align:right;\">";
		gcHTML += "</td>";
		gcHTML += "<td align=\"center\" class=\"gc_td2\">";
		gcHTML += "<input type=\"Button\" value=\"APPLY TO ORDER\" onclick=\"applyGC(" + v[0].trim() + ",'checkout');\" class=\"gc_button\">"
		gcHTML += "<input type=\"hidden\" name=\"gcTtl_" + v[0].trim() + "\" value=\"" + formatCurrency(v[1],false) + "\">";
		gcHTML += "</td>";
		gcHTML += "<td width=\"130\" id=\"gcTD_" + v[0].trim() + "\" align=\"right\" class=\"gc_td2\">" + formatCurrency(v[2],true); + "</td>";
		gcHTML += "</tr>";
		
		io++;
		if (io > 1) io = 0; // reset style toggle.
	}
		gcHTML += "</table>";

	$("gcTD").innerHTML = gcHTML; // set the page html for the gift cards.
	$("gcTR").style.display = ""; // show the page html for the gift cards.
}


// this function will apply an amount of a gift card
function applyGC(gcID,frm) {
	var f	= eval("document." + frm + ".gc_" + gcID); 		// set applied amount text field to a var.
	var h	= eval("document." + frm + ".gcTtl_" + gcID); 	// set hidden amount field to a var.
	var gcRedeemTtl = getGCRedeemTotal(gcID); // get current redemption total;
	var gcI = getGCItem(gcID); // get item in the array.
	var gcF = f.value*1;
	
	if(gcF > (gcI[1]*1)) { // check amount isn't greater than balance.
		f.value = formatCurrency(gcI[1],false); // set form value to balance.
		gcF = f.value*1; // update gcF
	}
	
	if(gcF > (oTotal*1)-(gcRedeemTtl*1)) { // check to see amount isn't greater than the order total.
		f.value = formatCurrency((oTotal*1)-(gcRedeemTtl*1),false); // set form value to order total.
		gcF = f.value*1; // update gcF
	}
	
	upGCItem(gcID,gcF); // update the gcRedeem array item.

	gcI = getGCItem(gcID); // get updated item in the array.
	
	// display applied amount in td.
	var td = "gcTD_" + gcID;
	$(td).innerHTML = formatCurrency(gcI[2],true);
	
	
	f.value = formatCurrency(gcI[2],false); // format the text field value.
	h.value = formatCurrency(gcI[2],false); // format the hidden field value.
	
	setFinalTotals(); // now update all the values.
	
}

// this function will retrieve an item in the gcRedeem array
function getGCItem(gcID) {
	for(var i=0; i<gcRedeem.length; i++) {
		var x = gcRedeem[i].split("|");
		if(gcID == x[0]) return x; // if this is the item return it.
	}	
}

// this function will update an item in the gcRedeem array
function upGCItem(gcID,amount) {
	for(var i=0; i<gcRedeem.length; i++) {
		var x = gcRedeem[i].split("|");
		if(gcID == x[0]) { // if this is the item update it.
			gcRedeem[i] = x[0] + "|" + x[1] + "|" + amount;
		}
	}	
}

// this function will tally the gift card redemption amounts and return it.
function getGCRedeemTotal(gcID) {
	var t = 0; // set a var to zero
	
	for(var i=0; i<gcRedeem.length; i++) {
		var x = gcRedeem[i].split("|");
		if(gcID != x[0]) {
			t += x[2]*1; // add redeemed amount to total
		}
	}	
	return formatCurrency(t,false);
}
